From govisathish at gmail.com Thu Sep 13 10:39:41 2007 From: govisathish at gmail.com (python_lover) Date: Thu, 13 Sep 2007 07:39:41 -0700 Subject: Help to start python In-Reply-To: <1189693433.545822.89580@o80g2000hse.googlegroups.com> References: <1189693144.493878.130220@w3g2000hsg.googlegroups.com> <1189693433.545822.89580@o80g2000hse.googlegroups.com> Message-ID: <1189694381.957459.232350@y42g2000hsy.googlegroups.com> On Sep 13, 7:23 pm, kyoso... at gmail.com wrote: > python_lover wrote: > > Hi All, > > > I'm new to python. I installed python 2.5 and IDLE 1.2.1 . I'm able > > to run shell commands. > > > But I don't know how to execute a python program using this. When I'm > > opeing a py program a seperate IDLE window opeing with program text. > > But I don't know to to execute the prg. > > > Please help me on this . > > > thank you > > > regards > > Sat > > When in IDLE, you can go to the Run menu and choose Run Module (or > press F5) in the window that has the program code. > > Hope that helps! > > Mike- Hide quoted text - > > - Show quoted text - Thankx mike. It is working well. Please guide me some good sites to start web based programing on python. thank you. sat From steve at holdenweb.com Fri Sep 21 14:30:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Sep 2007 14:30:10 -0400 Subject: TRying to import files from my folder not pythons lib folder In-Reply-To: <1190396569.732154.234270@r29g2000hsg.googlegroups.com> References: <1190395964.541835.114350@50g2000hsm.googlegroups.com> <1190396569.732154.234270@r29g2000hsg.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Sep 21, 12:32 pm, "tedpot... at gmail.com" > wrote: >> Hi, >> >> I'm trying to create my own lib of functions, but it seems like I can >> only import them if they are in pythons lib folder. >> >> Example >> I have a folder called >> K:\mypython >> >> Now in the interactive python shell I type >> Import k:\mypython\listall >> And get a error on : >> >> If I store listall.py in pythons lib folder and type >> Limport listall >> >> It works fins. >> >> Can I create my own library of functions and store them in a separate >> dir???? >> >> Also I try to creat a folder in pythomns lib folder and that did not >> work >> >> Help >> -Ted > > One workaround is to do to this: > > > > import sys > sys.path.append(r'K:\mypython') > import listall > > > > You can also add your path to the .pth file, but I've never done that, > so I can't tell you how. > > Hope that helps! > > Mike > The easiest way, particularly for testing, is to set the PYTHONPATH variable. It should be a colon-separated list of directories on Unices, and a semi-colon separated list on Windows. Those directories will be added to sys.path. See http://docs.python.org/tut/node8.html for yet more. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From rbonvall at gmail.com Mon Sep 3 13:04:57 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Mon, 03 Sep 2007 17:04:57 -0000 Subject: Problem with extremely small real number In-Reply-To: <1188831370.133673.205230@r29g2000hsg.googlegroups.com> References: <1188831370.133673.205230@r29g2000hsg.googlegroups.com> Message-ID: <1188839097.832915.231490@w3g2000hsg.googlegroups.com> On 3 sep, 10:56, Andrea wrote: > def binomial(n, k): > assert n>0 and isinstance(n, (int, long)) and isinstance(k, > (int,long)) Don't use assert to check whether the parameters have the right value. assert should be used to claim that a certain condition always hold in your program. Prefer the following form, which will make debugging clearer: if n <= 0: raise ValueError("Wrong value of n") if not isinstance(n, (int, long)): raise TypeError("Wrong type of n") if not isinstance(k, (int, long)): raise TypeError("Wrong type of k") Anyway, you shouldn't be checking the type of the parameters either. It could be more useful if you cast to the desired type. This way, your function will handle gracefully the case when you accidentally pass a string as a parameter: n = int(n) k = int(k) if n <= 0: raise ValueError("Wrong value of n: %d" % n) Best regards, -- Roberto Bonvallet From steve at holdenweb.com Mon Sep 24 23:04:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Sep 2007 23:04:03 -0400 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> Message-ID: <46F87AA3.4040106@holdenweb.com> Robert Dailey wrote: > What I meant was that it's not an option because I'm trying to learn > regular expressions. RE is just as built in as anything else. > > On 9/24/07, *Steve Holden * > wrote: > > Robert Dailey wrote: > > > > > > On 9/24/07, *Gabriel Genellina* > > >> > wrote: > > > > Yes: forget about regular expressions. ElementTree does that > for free: > > > > > > That's not an option. > > > Even though it's built into Python 2.5? That's a strange requirement. > > Fair enough, but be aware that (as has already been pointed out) RE limitations will make it difficult to parse some XML. Still, trying to use them for that purpose is a good way of learning about them, I suppose. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From ldo at geek-central.gen.new_zealand Fri Sep 21 05:20:39 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 21 Sep 2007 21:20:39 +1200 Subject: urllib2 POST problem References: <1190231918.779534.22810@v29g2000prd.googlegroups.com> Message-ID: In message <1190231918.779534.22810 at v29g2000prd.googlegroups.com>, darran wrote: > entry = "testing API3.5 hours>6575079702 task_id>Thu, 13 Sep 2007" ... > # this POST (same data as the above curl example) fails with an > internal server error (500) > req = urllib2.Request(url='http://subdomain.harvestapp.com/daily/add', > data=entry) > response = opener.open(req) > print response.read() Perhaps the value of "entry" needs to be URL-encoded? From hyena at gmail.com Sun Sep 30 09:38:04 2007 From: hyena at gmail.com (hyena) Date: Sun, 30 Sep 2007 15:38:04 +0200 Subject: is it possible to use different font within one wxpython static text widget? In-Reply-To: <1189613154.244069.15590@o80g2000hse.googlegroups.com> References: <1189613154.244069.15590@o80g2000hse.googlegroups.com> Message-ID: kyosohma at gmail.com ??: > On Sep 12, 10:26 am, "hyena" wrote: >> problem is as title, bear me if this too silly or too naive. >> >> I use wx.statictext widget to show some information in GUI, there are some >> numbers in the text to be emphasized in bigger other color. For example, in >> sentence "the travel speed of this car is 40 km /hour", I would like "40" to >> be bigger and in red color. I know I can use several statictext to get this >> effect. But i am quite relucktant to do so since I am quite unfamiliar with >> manageing the layout of widgets. >> >> Is there a convinient way to have this done? Thanks for any .input > > > Without knowing what kind of interface you're making, I can only shoot > in the dark. From your question, I would think that the FancyText > widget would suffice. Other widgets that would be harder to use would > be the StyledTextCtrl and the HtmlWindow (which I use for About > dialogs). > > Check out the wxPython Demo for sample code on each of these widgets > and sizers. Also see the Wiki for tips and tricks on using Sizers. > There's a new SizedControl that's supposed to simplify creating > layouts, although I haven't used it. And there's also XRC too. > > Mike > Sorry did not check this group for a while. Thanks Mike for your input. I will go take a look at the fancytext widget. Thanks again. From stefan.behnel-n05pAM at web.de Sat Sep 15 10:41:03 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 15 Sep 2007 16:41:03 +0200 Subject: python 2.5 cElementTree entity troubles In-Reply-To: <5l22jsF5taqoU1@mid.uni-berlin.de> References: <5l22jsF5taqoU1@mid.uni-berlin.de> Message-ID: <46EBEEFF.80106@web.de> Diez B. Roggisch wrote: > Any suggestions on how to teach the built-in ET-parser entities? As you already do it in your code. http://effbot.org/elementtree/elementtree-xmlparser.htm#tag-ET.XMLParser.entity But I guess your version of cET is just too old. Stefan From zzbbaadd at aol.com Tue Sep 4 01:00:28 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 03 Sep 2007 22:00:28 -0700 Subject: parameter list notation Message-ID: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> I am trying to use a database written in Python called buzhug. In looking at some of the functions I see this prototype: def create(self,*fields,**kw): I am not clear on what the * and the ** are for or what they represent. Or, what are they referred to as so I can do a query for information on them. Thanks TFD From tim at tdw.net Sat Sep 15 05:27:36 2007 From: tim at tdw.net (Tim Williams) Date: Sat, 15 Sep 2007 10:27:36 +0100 Subject: trim start and trailing space chars from string In-Reply-To: <46EBA4B1.1030302@yahoo.gr> References: <46EBA4B1.1030302@yahoo.gr> Message-ID: <9afea2ac0709150227j3ef7516cx401678b60bffa10c@mail.gmail.com> On 15/09/2007, Konstantinos Pachopoulos wrote: > Hi, > is there something corresponding to the java String.trim() method, ie > trim start and trailing space/tab chars from string? > say convert " asdf " to "asdf"? >>> ' asdf '.strip() 'asdf' >>> ' asdf '.rstrip() ' asdf' >>> ' asdf '.lstrip() 'asdf ' >>> From gagsl-py2 at yahoo.com.ar Mon Sep 17 15:36:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Sep 2007 16:36:48 -0300 Subject: UnicodeEncodeError in Windows References: <1190025496.308969.51400@n39g2000hsh.googlegroups.com> Message-ID: En Mon, 17 Sep 2007 07:38:16 -0300, geoff_ness escribi?: > def buildString(warrior): > """Build a string from a warrior's stats > > Returns string for output to warStat.""" > return "!tr!!td!!id!"+str(warrior.ID)+"!/id!!/td!"+\ > "!td!"+str(warrior.damage)+"!/td!!td!"+str(warrior.kills)+\ > "!/td!!td!"+str(warrior.survived)+"!/td!!/tr!" > > This code runs fine on my linux machine, but when I sent the code to a > friend with python running on windows, he got the following error: > > Traceback (most recent call last): > File "C:\Documents and Settings\Administrator\Desktop > \reparser_014(2)\iotp_alt2.py", line 169, in buildString > "!/td!!td!"+str(warrior.survived)+"!/td!!/tr!" > UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in > position 0: ordinal not in range(128) > > As I understand it the error is related to the ascii codec being > unable to cope with the unicode string u'\ufeff'. > The issue I have is that this error doesn't show up for me - ascii is > the default encoding for me also. Any thoughts or assistance would be > welcomed. Some of those `warrior` attributes is an Unicode object that contains characters outside ASCII. str(x) tries to convert to string, using the default encoding, and fails. This happens on Windows and Linux too, depending on the data. I've seen that you use codecs.open: you should write Unicode objects to the file, not strings, and that would be fine. Look for some recent posts about this same problem. -- Gabriel Genellina From bbxx789_05ss at yahoo.com Fri Sep 7 19:13:35 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 07 Sep 2007 16:13:35 -0700 Subject: why should I learn python In-Reply-To: References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <1189117798.506367.278560@y42g2000hsy.googlegroups.com> <1189118200.040934.151520@57g2000hsv.googlegroups.com> <1189133913.480902.289070@57g2000hsv.googlegroups.com> Message-ID: <1189206815.524056.153820@o80g2000hse.googlegroups.com> On Sep 6, 10:51 pm, James Stroud wrote: > BartlebyScrivener wrote: > > On Sep 6, 5:36 pm, Andr? wrote: > > >> Easy to read, easy to write, good libraries and, I have found, an > >> extremely helpful community. > > >> Hobbyists (like me) can work on projects written in Python on and off > >> (sometimes for weeks if not months without programming) and be able to > >> resume the work very quickly (because it's so easy to read and > >> understand the code). > > > I second these. I am not a programmer. You can get busy with other > > projects for weeks and come back to Python code and pick up where you > > left off, because it uses WORDS. Try remembering what (<>) or <*> > > means after being away from Perl for a month. > > > rd > > Better is to try to remember the differences between and uses of: > > $stupidPerl[4] > ${stupidPerl}[4] > $stupidPerl->[4] > ${stupidPerl}->[4] > $#stupidPerl[4] > $#{stupidPerl}[4] > $#{stupidPerl}->[4] > $#{$stupidPerl}->[4]->[4] > > And so on. > > Quiz: which are valid? (Careful now.) > > The friggin' language is useless (except for the fact that, like > window$, a lot of people insist on using it over superior alternatives > and so you find yourself confronting it from time to time). In fact, it > was the need to use nested data structures that made me move to python > when I realized all of the above would be a thing of the past (also made > useless my perl "cheat sheet" that sits in my big-fat-useless-camel-book). > > $Perl->[Useless] > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ rofl. From deets at nospam.web.de Wed Sep 19 13:41:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Sep 2007 19:41:25 +0200 Subject: compile for ARM In-Reply-To: References: Message-ID: <5ld5avF7ne3mU1@mid.uni-berlin.de> Rafael Marin Perez schrieb: > Hello > > I'm Rafael Marin, and work as reseacher in University of Murcia (Spain). > > I want to install and compile modules of python2.4 in a ARMv5b > architecture. > > Any idea? You might consider looking at the gumstix-project. They feature a linux-distro including python that is used by the gumstix running a XScale255-controller. That machine is ARM-based- so you might get a clue on how to cross-compile for that architecture by looking at the gumstix-stuff. Diez From deets at nospam.web.de Thu Sep 20 08:29:21 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 20 Sep 2007 14:29:21 +0200 Subject: I MEANT ONIX.... [it was Re: ONYX] In-Reply-To: <1190283378.175422.73290@r29g2000hsg.googlegroups.com> References: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> <46f1726f$0$15276$426a74cc@news.free.fr> <1190282489.824709.29050@r29g2000hsg.googlegroups.com> <1190283378.175422.73290@r29g2000hsg.googlegroups.com> Message-ID: <5lf7dsF7vn3qU1@mid.uni-berlin.de> korovev76 at gmail.com schrieb: > i'm such a lame... i meant onix... not onyx... > http://xml.coverpages.org/onix.html > > the questions remain the same ones... lxml is a validating parser for python. Diez From dmitrey.kroshko at scipy.org Wed Sep 19 07:39:44 2007 From: dmitrey.kroshko at scipy.org (dmitrey.kroshko at scipy.org) Date: Wed, 19 Sep 2007 04:39:44 -0700 Subject: lambda-funcs problem Message-ID: <1190201984.062329.182460@k79g2000hse.googlegroups.com> hi all, I need to create a Python list of lambda-funcs that are dependent on the number of the ones, for example F = [] for i in xrange(N): F.append(lambda x: x + i) however, the example don't work - since i in end is N-1 it yields x+ (N-1) for any func. So what's the best way to make it valid? Evaluation speed is also very important to me. Thank you in advance, D. From larry.bates at websafe.com Mon Sep 17 11:06:12 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 17 Sep 2007 10:06:12 -0500 Subject: Parsing problems: A journey from a text file to a directory tree In-Reply-To: <1189958074.670245.17910@n39g2000hsh.googlegroups.com> References: <1189958074.670245.17910@n39g2000hsh.googlegroups.com> Message-ID: <1uSdnaBGwMtvCnPbnZ2dnUVZ_tjinZ2d@comcast.com> Since you are going to need to do a dialog, I would use wxWindows tree control. It already knows how to do what you describe. Then you can just walk all the branches and create the folders. -Larry Martin M. wrote: > Hi everybody, > > Some of my colleagues want me to write a script for easy folder and > subfolder creation on the Mac. > > The script is supposed to scan a text file containing directory trees > in the following format: > > [New client] > |-Invoices > |-Offers > |--Denied > |--Accepted > |-Delivery notes > > As you can see, the folder hierarchy is expressed by the amounts of > minuses, each section header framed by brackets (like in Windows > config files). > > After the scan process, the script is supposed to show a dialog, where > the user can choose from the different sections (e.g. 'Alphabet', > 'Months', 'New client' etc.). Then the script will create the > corresponding folder hierarchy in the currently selected folder (done > via AppleScript). > > But currently I simply don't know how to parse these folder lists and > how to save them in an array accordingly. > > First I thought of an array like this: > > dirtreedb = {'New client': {'Invoices': {}, 'Offers': {'Denied': {}, > 'Accpeted': {}}, 'Delivery notes': {}}} > > But this doesn't do the trick, as I also have to save the hierarchy > level of the current folder as well... > > Argh, I really don't get my head around this problem and I need your > help. I have the feeling, that the answer is not that complicated, but > I just don't get it right now... > > Your desperate, > > Martin > From tigerb at yahoo.com Wed Sep 12 19:36:18 2007 From: tigerb at yahoo.com (TonyB) Date: Wed, 12 Sep 2007 23:36:18 -0000 Subject: struct is saving 4 bytes instead of 2 In-Reply-To: <5kr8fkF53m8gU1@mid.individual.net> References: <1189632217.661924.25520@r34g2000hsd.googlegroups.com> <5kr8fkF53m8gU1@mid.individual.net> Message-ID: <1189640178.267346.321040@r34g2000hsd.googlegroups.com> On Sep 12, 6:45 pm, Bjoern Schliessmann wrote: > TonyB wrote: > > When I inspect the file with a hex editor it show that the > > variable is being saved as 4 bytes. How can I make it save the > > value as 2 bytes? > > Use an aligment specifier in the format string (you want "standard" > alignment). See: > > http://docs.python.org/lib/module-struct.html > > Regards, > > Bj?rn > > -- > BOFH excuse #428: > > Firmware update in the coffee machine Bj?rn, I tried f.write(struct.pack('=h',thevariable)) and it works. Many thanks, Tony From kyosohma at gmail.com Thu Sep 27 10:26:24 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 27 Sep 2007 14:26:24 -0000 Subject: setuptools without unexpected downloads In-Reply-To: References: <87ejgmklep.fsf@benfinney.id.au> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> <5luv0iFaai82U1@mid.uni-berlin.de> <1190808836.056298.232640@57g2000hsv.googlegroups.com> <1190840682.716950.131830@r29g2000hsg.googlegroups.com> Message-ID: <1190903184.578243.192110@n39g2000hsh.googlegroups.com> On Sep 26, 5:52 pm, Steve Holden wrote: > kyoso... at gmail.com wrote: > > On Sep 26, 8:30 am, Steve Holden wrote: > >> Fredrik Lundh wrote: > >>> Paul Boddie wrote: > >>>> P.S. Of course, the package maintainer problem manifests itself most > >>>> prominently on Windows where you often see people asking for pre-built > >>>> packages or installers. > >>> for the record, I'd love to see a group of volunteers doing stuff like > >>> this for Windows. there are plenty of volunteers that cover all major > >>> Linux/*BSD distributions (tons of thanks to everyone involved in this!), > >>> but as far as I can remember, nobody has ever volunteered to do the same > >>> for Windows. > >> I'd like to see something like this happen, too, and if a group of > >> volunteers emerges I'll do what I can through the PSF to provide > >> resources. Activities that benefit the whole community (or a large part > >> of it) are, IMHO, well worth supporting. > > > What would it entail to do this? Using py2exe + some installer (like > > Inno Setup) to create an installer that basically copies/installs the > > files into the site-packages folder or wherever the user chooses? If > > that's all it is, I would think it would be fairly easy to create > > these. Maybe I'm over-simplifying it though. > > > What are a some examples of packages that need this? > > MySQLdb and psycopg are two obvious examples I have had to grub around > or produce my own installers for. There's generally some configuration > work to do for packages that have been produced without considering > Windows requirements, and ideally this will be fed back to the developers. > > I think you may be oversimplifying a little. Pure Python packages aren't > too problematic, it's mostly the extension modules. Unless a copy of > Visual Studio is available (and we *might* get some cooperation from > Microsoft there) that means resorting to MingW, which isn't an easy > environment to play with (in my occasional experience, anyway). > > There's going to be increasing demand for 64-bit implementations too. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline Steve, We have Visual Studio 2005 at work and my boss is a Python nut, so I could probably use it. I also have academic versions of VS 6 and 2003 (maybe 2005 too...I forget, it might be 2004) at home as well...I think I can use those for open source development, although knowing Microsoft, there's probably something draconian hiding in the EULA somewhere. If someone is willing to give me some guidance, I'll give it a try. Mike From zowtar at gmail.com Wed Sep 5 13:54:12 2007 From: zowtar at gmail.com (zowtar) Date: Wed, 05 Sep 2007 10:54:12 -0700 Subject: python-spidermonkey In-Reply-To: <5k87f6F2icddU1@mid.uni-berlin.de> References: <1189012861.893842.87710@k79g2000hse.googlegroups.com> <5k87f6F2icddU1@mid.uni-berlin.de> Message-ID: <1189014852.804852.254390@k79g2000hse.googlegroups.com> Diez B. Roggisch escreveu: > zowtar schrieb: > > Guys, I am using slackware... js-spidermonkey 1.5 compiled - OK, Pyrex > > installed, but python-spidermonkey don't build... > > > > Screenshot: http://img406.imageshack.us/img406/562/testebp5.png > > > > what is the problem? > > google dead today? > > http://article.gmane.org/gmane.comp.python.wwwsearch.general/1085 > > Might help. > > Diez I need make tests... but I think is working now... thanks a lot! From grue at mail.ru Sun Sep 30 12:09:22 2007 From: grue at mail.ru (Timofei Shatrov) Date: Sun, 30 Sep 2007 16:09:22 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <13frd6vtarbee75@corp.supernews.com> <87lkao8xgk.fsf@web.de> Message-ID: <46ffc8cb.34689260@news.readfreenews.net> On Sun, 30 Sep 2007 08:43:39 +0200, Klaus Schilling tried to confuse everyone with this message: > >that's because it's immoral not to give it all > >which is necessary in a moral culture. >Only an immoral culture may accept non-disclosure > >private property is unethical > I see the light! You really won me over with your preaching. -- |Don't believe this - you're not worthless ,gr---------.ru |It's us against millions and we can't take them all... | ue il | |But we can take them on! | @ma | | (A Wilhelm Scream - The Rip) |______________| From fakeaddress at nowhere.org Mon Sep 24 03:28:09 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 24 Sep 2007 00:28:09 -0700 Subject: Google and Python In-Reply-To: <1i4rfyx.8vuc2j14j596uN%aleax@mac.com> References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> <1i4rfyx.8vuc2j14j596uN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Bryan Olson wrote: [...] >> How does Google use Python? As their scripting-language >> of choice. A fine choice, but just a tiny little piece. >> >> Maybe Alex will disagree with me. In my short time at >> Google, I was uber-nobody. > > YouTube (one of Google's most valuable properties) is essentially > all-Python (except for open-source infrastructure components such as > lighttpd). Also, at Google I'm specifically "Uber Tech Lead, Production > Systems": while I can't discuss details, my main responsibilities relate > to various software projects that are part of our "deep infrastructure", > and our general philosophy there is "Python where we can, C++ where we > must". Good motto. So is most of Google's code base now in Python? About what is the ratio of Python code to C++ code? Of course lines of code is kine of a bogus measure. Of all those cycles Google executes, about what portion are executed by a Python interpreter? > Python is definitely not "just a tiny little piece" nor (by a > long shot) used only for "scripting" tasks; Ah, sorry. I meant the choice of scripting language was a tiny little piece of Google's method of operation. "Scripting language" means languages such as Python, Perl, and Ruby. > if the mutant space-eating > nanovirus should instantly stop the execution of all Python code, the > powerful infrastructure that has been often described as "Google's > secret weapon" would seize up. And the essence of the Google way is to employ a lot of smart programmers to build their own software to run on Google's infrastructure. Choice of language is triva. I think both Python Google are great. What I find ludicrous is the idea that the bits one hears about how Google builds its software make a case for how others should build theirs. Google is kind of secretive, and their ways are very much their own. Google's software is much more Googley than Pythonic. -- --Bryan From steve at REMOVE-THIS-cybersource.com.au Sun Sep 16 08:51:00 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 12:51:00 -0000 Subject: generate list of partially accumulated values References: <1189936564.932553.148800@50g2000hsm.googlegroups.com> Message-ID: <13eq9lkpnlknl2b@corp.supernews.com> On Sun, 16 Sep 2007 09:56:04 +0000, cesco wrote: > Hi, > > I have the following list: > l = [1, 2, 3, 4] > and I'd like to obtain a list like the following: > l_partial_sum = [1, 3, 6, 10] > (that is [1, 1+2, 1+2+3, 1+2+3+4]) > > Is there a simple way to accomplish this? Yes, use a loop. Put it into a function: def partial_sums(L): if not L: return [] ps = [None]*len(L) ps[0] = L[0] for i in xrange(1, len(L)): ps[i] = ps[i-1] + L[i] return ps >>> l = [1, 2, 3, 4] >>> partial_sums(l) [1, 3, 6, 10] Here's a one-liner that give the same result: [sum(l[0:i]) for i in xrange(len(l)+1)][1:] Which is better, the one-liner using a super-fast built-in function written in C, or the multi-line function using just slow Python code? (Hint: I wouldn't be asking the question if the "obvious" answer was right.) Measure, don't guess! >>> import timeit >>> >>> timeit.Timer("partial_sums(l)", ... "from __main__ import partial_sums; l = range(1000)").timeit(1000) 1.3528358936309814 >>> timeit.Timer("[sum(l[0:i]) for i in xrange(len(l)+1)][1:]", ... "l = range(1000)").timeit(1000) 41.276183843612671 The one-liner is thirty times slower than the function. Can you explain why? (Hint: how many times does it add numbers? How many times does it copy parts of the list?) -- Steven. From theller at ctypes.org Thu Sep 13 05:19:11 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 13 Sep 2007 11:19:11 +0200 Subject: Get the complete command line as-is In-Reply-To: <1189647903.978946.38350@r29g2000hsg.googlegroups.com> References: <1189566000.793354.308420@19g2000hsx.googlegroups.com> <1189647903.978946.38350@r29g2000hsg.googlegroups.com> Message-ID: wangzq schrieb: > On Sep 12, 3:20 pm, Laurent Pointal wrote: >> wangzq a ?crit : >> >> > Hello, >> >> > I'm passing command line parameters to my browser, I need to pass the >> > complete command line as-is, for example: >> >> > test.py "abc def" xyz >> >> > If I use ' '.join(sys.argv[1:]), then the double quotes around "abc >> > def" is gone, but I need to pass the complete command line ("abc def" >> > xyz) to the browser, how can I do this? >> >> > I'm on Windows. >> >> As Windows command-line parsing seem to remove some chars, maybe you can >> try to use the GetCommandLine() function from Win32 API (I dont know if >> it is available in pywin32 package - you may need to write a wrapper >> with ctypes). >> >> Seehttp://msdn2.microsoft.com/en-us/library/ms683156.aspx >> >> A+ >> >> Laurent. > > Thank you for the tip. It works: > > import ctypes > > p = ctypes.windll.kernel32.GetCommandLineA() > print ctypes.c_char_p(p).value > Better would be this code: import ctypes ctypes.windll.kernel32.GetCommandLineA.restype = ctypes.c_char_p print ctypes.windll.kernel32.GetCommandLineA() Thomas From arne at vajhoej.dk Fri Sep 14 19:51:14 2007 From: arne at vajhoej.dk (=?ISO-8859-1?Q?Arne_Vajh=F8j?=) Date: Fri, 14 Sep 2007 19:51:14 -0400 Subject: Car-ac-systems In-Reply-To: References: <1189511932.371621.112970@o80g2000hse.googlegroups.com> <1189661753.315182.53630@22g2000hsm.googlegroups.com> Message-ID: <46eb1e4e$0$90264$14726298@news.sunsite.dk> [text reordered from top post to standard newsgroup style] John Timney (MVP) wrote: > wrote in message > news:1189661753.315182.53630 at 22g2000hsm.googlegroups.com... >> On Sep 11, 9:35 am, "John Timney \(MVP\)" >> wrote: >>> How do I control one with C# then! Thats not on your site, clearly not >>> everything I need to know then. Waste of a site! >> C# is just as off topic in comp.lang.java.programmer as car air- >> conditioning systems. The latter, however, have the redeeming >> characteristic that they are not the demonic spawn of evil Microsoft. > ho ho......now thats quite funny! Before you start wondering too much try and make a search in comp.lang.java.programmer for posts by nebulous99 ... Arne From seancron at gmail.com Sat Sep 1 12:05:44 2007 From: seancron at gmail.com (seancron) Date: Sat, 01 Sep 2007 16:05:44 -0000 Subject: nameerror upon calling function Message-ID: <1188662744.345071.123610@57g2000hsv.googlegroups.com> Hi, I have a program that makes a call to a function in a different python script that I wrote. But, when I call the function I get the following error: NameError: global name 'WSDL' is not defined I can't figure out why I'm getting this error since WSDL should be defined. Here are the two scripts: weatherpy.py from xml.dom import minidom from SOAPpy import WSDL from libndfdsoap import ByDaySOAPRequest wsdlfile = 'http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ ndfdXML.wsdl' if __name__ == '__main__': ByDaySOAPRequest(39.0000, -77.0000, 2004-04-27, 7, '12 hourly') libndfdsoap.py def ByDaySOAPRequest(latitude, longitude, startDate, numDays, hrFormat): """Sends a SOAP request using the NDFDgenByDay method and stores the response in a file called weather.xml""" wsdlfile = 'http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ ndfdXML.wsdl' server = WSDL.Proxy(wsdlfile) response = server.NDFDgenByDay(latitude, longitude, startDate, numDays, hrFormat) xml = open('/weather.xml', 'w') xml.write(response) xml.close() return Can somebody please show me how to fix this error? Thanks, -Sean From khemkaamit at gmail.com Tue Sep 25 01:31:14 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 25 Sep 2007 11:01:14 +0530 Subject: sorting a list numbers stored as strings In-Reply-To: <1190633951.3385.23.camel@dot.uniqsys.com> References: <1190632366.863711.100680@y42g2000hsy.googlegroups.com> <1360b7230709240423k47485263pedc6562000ba1597@mail.gmail.com> <1190633951.3385.23.camel@dot.uniqsys.com> Message-ID: <1360b7230709242231m130bc8a0tecda74f66fd20a87@mail.gmail.com> On 9/24/07, Carsten Haese wrote: > On Mon, 2007-09-24 at 16:53 +0530, Amit Khemka wrote: > > On 9/24/07, aine_canby at yahoo.com wrote: > > > > >>> l = ["1", "11", "2", "22"] > > >>> sorted(l, cmp = lambda x, y: cmp(int(x), int(y))) # provide your > > own compare function ! > > >>> l > > ['1', '2', '11', '22'] > > That interpreter session is a work of fiction, since sorted returns the > sorted list instead of sorting the list in place. I am sorry, thanks for pointing out ! What I intended to write was: >>> l = sorted(l, cmp = lambda x, y: cmp(int(x), int(y))) Btw, It was more of a goofed up Reality show ! cheers, -- ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Sep 27 03:30:34 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Sep 2007 09:30:34 +0200 Subject: Using closures and partial functions to eliminate redundant code In-Reply-To: References: Message-ID: <46fb5bf6$0$4748$426a34cc@news.free.fr> Matthew Wilson a ?crit : > I wrote some code to create a user and update a user on a remote box by > sending emails to that remote box. When I was done, I realized that my > create_user function and my update_user function were effectively > identical except for different docstrings and a single different value > inside: > > ### VERSION ONE > > def create_user(username, userpassword, useremail): > "Send an email that will create a user in the remote system." > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject="CREATE", body=email_body) > > > def update_user(username, userpassword, useremail): > "Send an email that will update a user's password in the remote system." > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject="UPDATE", body=email_body) > > ### END (snip) > > Finally, I came up with this approach: > > ### VERSION THREE > > from functools import partial > > def _h(mode, username, userpassword, useremail): > > if mode not in ("create", "update"): > raise ValueError("mode must be create or update!") > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject=mode.upper(), body=email_body) > > # I can't figure out how to set up the docstring on these. > > v3_create_user = partial(_h, mode="create") > v3_update_user = partial(_h, mode="update") > > ### END > > I'm interested to hear how other people deal with really similar code. Depends. > The similarity just bugs me. However, I wonder if using stuff like > closures or partial function application is needlessly showy. Not necessarily, but in this case, it's just overkill IMHO - I'd just have factored out the common code: def _build_email(username, userpassword, useremail): """ builds the email body used by create_uer and update_user """ return """ USERNAME = %s USERPASSWORD = %s USEREMAIL = %s """ % (username, userpassword, useremail) def create_user(username, userpassword, useremail): "Send an email that will create a user in the remote system." send_email(subject="CREATE", body=_build_email(username, userpassword, useremail) ) def update_user(username, userpassword, useremail): "Send an email that will update a user's password in the remote system." send_email(subject="UPDATE", body=_build_email(username, userpassword, useremail) ) Now there are of course cases where either closures and/or partials are the right thing to do. > Also, I hope anyone here can help me figure out how to attach a > meaningful docstring for my version three code. Didn't try, but what about: p = partial(func, arg) p.__doc__ = "yadda yadda" From puredata at 11h11.com Tue Sep 25 23:08:15 2007 From: puredata at 11h11.com (patrick) Date: Tue, 25 Sep 2007 23:08:15 -0400 Subject: jack audio connection kit In-Reply-To: <1190774030.603655.85010@d55g2000hsg.googlegroups.com> References: <1190774030.603655.85010@d55g2000hsg.googlegroups.com> Message-ID: <46F9CD1F.50407@11h11.com> found the perfect solution (for linux at least) : gstreamer! http://pygstdocs.berlios.de/ pat From veronika.lindstrand.kant at glocalnet.net Thu Sep 6 16:06:24 2007 From: veronika.lindstrand.kant at glocalnet.net (Veronika Lindstrand Kant) Date: Thu, 06 Sep 2007 22:06:24 +0200 Subject: Python and CUDO Message-ID: <46E05DC0.7090102@glocalnet.net> Hi! I just wonder if there are any plans for building any support using NIVIDAS CUDO plattform into python? For example when implementing Monte Carlo simulation performance always is an issue so extended numpy/numeric or a math library using the CUSO plattform could be a "cheap" grid approach. I myself implemented a simple "batch grid" for distribute calculations to be executed in parallell supporting a typical pattern as: for x in collect_data(): post(calc(x)) syncronize() generate_report(get_calculations()) So one idea supporting this pattern would be to define some kind of new form of generators which allows independ calculations be executed in parallell and depending on form returns the calculation either in synchronized way (i.e. returned in sequence order) or in a asyncronized order. One other thing: for a long time I worked with a financial system, SunGard FRONT ARENA, which has integrated python into the system in a clever way according to Fredrik Lundh. I suggest that you extend the application list with this system. /Fredrik Kant www.kantconsulting.se From dlwester at comcast.net Mon Sep 24 15:59:52 2007 From: dlwester at comcast.net (Dave Westerman) Date: Mon, 24 Sep 2007 15:59:52 -0400 Subject: execfile and function call Message-ID: I've got a Jython script where I'm doing an execfile() to pull in a small script that contains a function, which I then call. execfile(app_applscript) optionList = createOptionList(applOptions) When I do this at the global level in my main script, it works just fine. However, when I move this code into a function in my main script, then it fails, telling me it can't find the function createOptionList(). Traceback (innermost last): File "", line 459, in ? File "", line 429, in processApplication NameError: createOptionList Does anyone have any idea what I'm doing wrong? I noticed that createOptionList no longer shows up when I do a dir(). Do I somehow have to get that to be a global? How do I do that? From andres.j.new at gmail.com Sun Sep 30 23:10:05 2007 From: andres.j.new at gmail.com (Andres Riofrio) Date: Sun, 30 Sep 2007 20:10:05 -0700 Subject: Fwd: Using fractions instead of floats In-Reply-To: <52c50880709302007g4103c6c6h9b09ee376fa77998@mail.gmail.com> References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <1191206183.441075.167450@57g2000hsv.googlegroups.com> <52c50880709302007g4103c6c6h9b09ee376fa77998@mail.gmail.com> Message-ID: <52c50880709302010n7cbc070fn6223bd94a67542dd@mail.gmail.com> PS: Sorry, George Sakkis, for the double emailing... I forgot to add python-list in the To: field the first time. :) Haha. Ok. Thank you for pointing me to those links :). I hadn't thought of searching for the word 'rational' instead of 'decimal'... >From what I've read, seems that the principal reason for rejecting the PEP is that there was not much need (enthusiasm)... Well, then I have a question: Is there a way to make 5/2 return something other than an integer? I can do: class int(int): def __add__(self, other): pass but that will only work if I do int(5)/int(2)... (setting __builtin__.int=int doesn't work, either) What I'd like is to be able to implement what I put in the proposal, as I don't think it's a really big language change... On 9/30/07, George Sakkis wrote: > On Sep 30, 9:35 pm, andresj wrote: > > I was doing some programming in Python, and the idea came to my mind: using fractions instead of floats when doing 2/5. > > (...) > > I would like to get some feedback on this idea. Has this been posted > > before? If so, was it rejected? and for what? > > Is internet down today ? > > http://pypi.python.org/pypi/clnum/1.2 > http://www.python.org/dev/peps/pep-0239/ From stefan.behnel-n05pAM at web.de Thu Sep 13 11:36:51 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 13 Sep 2007 17:36:51 +0200 Subject: lxml + mod_python: cannot unmarshal code objects in restricted execution mode In-Reply-To: <1189688758.587404.139360@r29g2000hsg.googlegroups.com> References: <1189688758.587404.139360@r29g2000hsg.googlegroups.com> Message-ID: <46E95913.9030507@web.de> Dmitri Fedoruk wrote: > def extApplyXslt(xslt, data, logger ): > try: > strXslt = urllib2.urlopen(xslt).read() > # i have to read the xslt url to the python string > except urllib2.HTTPError, e: > ....... > except urllib2.URLError, e: > ............. > try: > xslt_parser = etree.XMLParser() > xslt_parser.resolvers.add( PrefixResolver("XSLT") ) > > # and now I have to use the string; a more elegant solution, > anyone? Sure, lxml.etree can parse from file-like objects. Just hand in the result of urlopen(). Apart from that, I saw that you found your way to the lxml mailing list, I'll respond over there. Stefan From steven.bethard at gmail.com Tue Sep 25 12:47:48 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Sep 2007 10:47:48 -0600 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190710402.481693.5110@50g2000hsm.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> Message-ID: Mark Summerfield wrote: > PEP: XXX > Title: Sorted Dictionary [snip] > In addition, the keys() method has two optional arguments: > > keys(firstindex : int = None, secondindex : int = None) -> list of keys > > The parameter names aren't nice, but using say "start" and "end" would > be misleading since the intention is for the parameters to work like > they do in range(), e.g. > > sd.keys() # returns a list of all the sorteddict's keys > sd.keys(10) # returns a list of the first 10 keys > sd.keys(19, 35) # returns a list of the 19th-34th keys inclusive You should use the range() names, "start" and "stop": >>> help(range) Help on built-in function range in module __builtin__: range(...) range([start,] stop[, step]) -> list of integers But I also agree that this is probably not necessary given the existence of slicing and itertools.islice(). > Since the sorteddict's data is always kept in key order, indexes > (integer offsets) into the sorteddict make sense. Five additional > methods are proposed to take advantage of this: > > key(index : int) -> value > > item(index : int) -> (key, value) > > value(index : int) -> key > > set_value(index : int, value) > > delete(index : int) > > Items and values can still be accessed using the key, e.g., sd[key], > since all the dict's methods are available. I agree with others that these APIs are really not necessary. Simply call keys(), values() or items() and then use that list if you really want indexing. If you're dealing with a lot of these kind of indexing behaviors, working with the plain list object will be faster anyway. > Examples > > To keep a collection of filenames on a case-insensitive file system in > sorted order, we could use code like this: > > files = collections.sorteddict.sorteddict() The type should probably just be in collections directly. No need for a sub-package. So that would look like:: files = collections.sorteddict() I also strongly support Paul Hankin's proposal for the constructor API:: sorteddict((mapping|sequence|..), cmp=None, key=None, reverse=False) Being able to sort by a key= function would make sorteddict() dramatically more useful. I almost never use the builtin heap() because it doesn't support a key= function and I always need one. I suspect use cases for sorteddict() will be similar. For example:: files = collections.sorteddict(key=lambda s: s.lower()) for name in os.listdir("."): files[name] = ... some calculated value ... Now the file names are in lower-case sorted order, but if you actually retrieve the keys, e.g. through .items(), you'll see the real filename, not the lower-cased ones. STeVe From dstromberglists at gmail.com Tue Sep 25 20:58:56 2007 From: dstromberglists at gmail.com (Dan Stromberg) Date: Tue, 25 Sep 2007 17:58:56 -0700 Subject: Python XML API's that preserve XML comments? Message-ID: Are there any python XML parsing API's that preserve comments - preferrably that come with python 2.5.1? From zzbbaadd at aol.com Mon Sep 10 07:35:37 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 10 Sep 2007 04:35:37 -0700 Subject: Enum class with ToString functionality In-Reply-To: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> Message-ID: <1189424137.007519.272320@y42g2000hsy.googlegroups.com> On Sep 10, 2:28 am, bg... at yahoo.com wrote: > Hi, > > I have the following class - > > class TestOutcomes: > PASSED = 0 > FAILED = 1 > ABORTED = 2 > > plus the following code - > > testResult = TestOutcomes.PASSED > > testResultAsString > if testResult == TestOutcomes.PASSED: > testResultAsString = "Passed" > elif testResult == TestOutcomes.FAILED : > testResultAsString = "Failed" > else: > testResultAsString = "Aborted" > > But it would be much nicer if I had a function to covert to string as > part of the TestOutcomes class. How would I implement this? > > Thanks, > > Barry The equivalent to Java's toString() is __str__() in Python: class TestOutcomes: PASSED = 0 FAILED = 1 ABORTED = 2 def __init__(self,outcome): self.outcome = outcome def __str__(self): if self.outcome == TestOutcomes.PASSED: return "Passed" elif self.outcome == TestOutcomes.FAILED : return "Failed" else: return "Aborted" if __name__ == "__main__": testResult = TestOutcomes(TestOutcomes.ABORTED) print testResult testResult = TestOutcomes(TestOutcomes.FAILED) a = testResult.__str__() print a Aborted Failed From bdesth.quelquechose at free.quelquepart.fr Thu Sep 20 05:43:02 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 20 Sep 2007 11:43:02 +0200 Subject: Lookup values from one table to another based on a value In-Reply-To: <1190315957.295875.34220@n39g2000hsh.googlegroups.com> References: <1190298876.689060.44540@d55g2000hsg.googlegroups.com> <46f2930a$0$9505$426a74cc@news.free.fr> <1190305331.584560.218880@g4g2000hsf.googlegroups.com> <46f2a4e6$0$15456$426a74cc@news.free.fr> <1190315957.295875.34220@n39g2000hsh.googlegroups.com> Message-ID: <46f2d599$0$8933$426a74cc@news.free.fr> koutoo at hotmail.com a ?crit : (snip) > > If I flipped the Table being looked up not to repeat, would that make > things easier to look up a value in? Don't repeat informations. From rrr at ronadam.com Sun Sep 23 19:34:20 2007 From: rrr at ronadam.com (Ron Adam) Date: Sun, 23 Sep 2007 18:34:20 -0500 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <13fdmdmsaasak91@corp.supernews.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <13f8unjjeqs5p97@corp.supernews.com> <13faa66cb1phre1@corp.supernews.com> <13fdmdmsaasak91@corp.supernews.com> Message-ID: <46F6F7FC.1050208@ronadam.com> Scott David Daniels wrote: > Ron Adam wrote: >> Scott David Daniels wrote: >>> Ron Adam wrote: >>>> .... How about this? >>>> def integrate(fn, x1, x2, n=100):... >>> The point was a pedagogic suggestion, ... >> I understood your point. I just found it interesting since I've been >> trying to extend my math (for use with python) skills in this area. > > Ah, sorry. I had realized I wasn't explicit in my first message. Yes, I wasn't trying to correct you. I'm sorry if it came across that way. > Yes, a perfectly fine integration. There's still something about it that bothers me. I think it may be the n=100 rather than delta='.0001', or some other way to specify the minimal error. (Yes, it's a bit off topic.) > You can then (and this is a major jump to get used to): > import functools > > Sine = functools.partial(integrate, math.cos, 0.0, n=100) I haven't played around with .partial yet. I wonder if it could be used in dispatching situations where the function signatures differ? > Similarly, you can define a derivative that will behave fairly well, > all without examining the definition of the function being operated > upon. I'll get around to doing that at some point. ;-) I also have a class that solves equations that takes a function in a similar way. It uses the same method used by HP calculators to solve TVM equations. Cheers, Ron From paddy3118 at googlemail.com Sat Sep 15 02:44:32 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 15 Sep 2007 06:44:32 -0000 Subject: Extended slicing and Ellipsis - where are they used? In-Reply-To: References: <1189699345.436400.233460@g4g2000hsf.googlegroups.com> <1189751869.773724.165040@w3g2000hsg.googlegroups.com> Message-ID: <1189838672.495173.19860@y42g2000hsy.googlegroups.com> On Sep 15, 12:29 am, James Stroud wrote: > Paddy wrote: > > And the ellipses ... ? > > ;) > > py> class Bob(dict): > ... def __getitem__(self, k, *args, **kwargs): > ... if k is Ellipsis: > ... return sorted(self.keys()) > ... else: > ... return dict.__getitem__(self, k, *args, **kwargs) > ... def __setitem__(self, k, *args, **kwargs): > ... if k is Ellipsis: > ... raise KeyError, "Can't make elliptical assignments." > ... else: > ... return dict.__setitem__(self, k, *args, **kwargs) > ... > py> b = Bob(a=1, b=2, c=3, d=15.5) > py> b > {'a': 1, 'b': 2, 'c': 3, 'd': 15.5} > py> for k in b[...]: > print '%s ==> %s' % (k, b[k]) > ... > a ==> 1 > b ==> 2 > c ==> 3 > d ==> 15.5 > py> b[...] = 2 > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > File "", line 9, in __setitem__ > : "Can't make elliptical assignments." Thanks again James. From steve at holdenweb.com Sun Sep 16 15:22:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Sep 2007 15:22:49 -0400 Subject: Try this In-Reply-To: <1189969529.652871.19280@50g2000hsm.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Sep 16, 1:10?pm, Dennis Lee Bieber wrote: >> On Sun, 16 Sep 2007 01:46:34 -0700, GeorgeRXZ >> declaimed the following in comp.lang.python: >> >>> Then Open the Notepad and type the following sentence, and save the >>> file and close the notepad. Now reopen the file and you will find out >>> that, Notepad is not able to save the following text line. >>> Well you are speed >>> This occurs not only with above sentence but any sentence that has >>> 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) >> I tried. I also opened the saved file in SciTE... >> And the text WAS there... >> >> It is Notepad that can not properly render what it, >> itself, saved. > > C:\Documents and Settings\mensanator\My Documents>type huh.txt > Well you are speed > > Yes, file was saved correctly. > But reopening it shows 9 unprintable characters. > If I copy those to a new file (huh1.txt): > > C:\Documents and Settings\mensanator\My Documents>type huh1.txt > ????????? > > But wait...the new file is 20 characters, not 9. > > 09/16/2007 01:44 PM 18 huh.txt > 09/16/2007 01:54 PM 20 huh1.txt > > C:\Documents and Settings\mensanator\My Documents>dump huh.txt > huh.txt: > 00000000 5765 6c6c 2079 6f75 2061 7265 2073 7065 Well you are spe > 00000010 6564 ed > > Here's what it's actually doing: > > C:\Documents and Settings\mensanator\My Documents>dump huh1.txt > huh1.txt: > 00000000 fffe 5765 6c6c 2079 6f75 2061 7265 2073 .~Well you are s > 00000010 7065 6564 peed > > One word: Unicode. The "open" and "save" dialogs allow you to specify an encoding. If you specify Unicode the you will get what you see above. If you specify ANSI you will get the text you entered. By the way, this has precisely what to do with Python? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From mridula.ccpl at gmail.com Sat Sep 29 00:43:53 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Sat, 29 Sep 2007 10:13:53 +0530 Subject: Bug: spurious indentation error Message-ID: <33dffc910709282143y76151e66r2f8641ed2972661a@mail.gmail.com> Hi. Lol, nope, I checked today too, and it happened again. Try running this as a script, not from the prompt - class main(): def __init__(self): rt.geometry("680x600") rt.config(bg="CornSilk") rt.title("my miniscule app") #MENU-------- menu = Menu(rt) rt.config(menu=menu) # create a menu filemenu = Menu(menu), bg="White") #syntax error/ typo in this line. menu.add_cascade(label="Options", menu=filemenu) filemenu.add_command(label="Add New")#, command=callback) filemenu.add_command(label="Edit") filemenu.add_command(label="Delete") filemenu.add_separator() filemenu.add_command(label="Exit") self.dbConnect() self.nowgather(gctr) self.showfixed() self.showrecords() def dbConnect(self): #error gets thrown here as a tab-space indentation error. #connects to database D:/Catalogue.mdb, and gathers all data in a recordset #called rs. Puts this information into individual lists by field name global gmax #setting record count to zero afresh. import win32com.client conn = win32com.client.Dispatch('ADODB.Connection') DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0; DATA SOURCE=D:/Catalogue.mdb;' conn.Open(DSN) rs = win32com.client.Dispatch('ADODB.Recordset') rs_name="MyRecordSet" rs.Cursorlocation = 3 rs.Open('SELECT * FROM Library', conn) gmax = rs.RecordCount Regards, Mridula. -------------------------------------------------------------------------------------------------------- This is probably a bug in your mind, not in the compiler ;-) Without more detail (i.e. the complete code or a sizable and relevant chunk of it, pkus the copied error message) it's impossible to say exactly what was happening. However I am pretty confident that the 2.5.21 compiler will immediately report an unopened closing parenthesis as a syntax error. >>> something = "abc".replace("c"), "d") File "", line 1 something = "abc".replace("c"), "d") ^ SyntaxError: invalid syntax >>> So, what was the problem again? Give us a little more detail, please. regards Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: From wizzardx at gmail.com Wed Sep 12 06:36:21 2007 From: wizzardx at gmail.com (David) Date: Wed, 12 Sep 2007 12:36:21 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <18c1e6480709120334g6f9d7615jaf9826ee9d6951a8@mail.gmail.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <18c1e6480709120334g6f9d7615jaf9826ee9d6951a8@mail.gmail.com> Message-ID: <18c1e6480709120336g715f91crcf7fea06ec04b1f6@mail.gmail.com> On 9/12/07, David wrote: > > Please help if I am missing something -- this looks like a great > > language but I am going to mad trying to read numerical code full of > > 'self.'s breaking up the equations. > > You could try this in your functions: > > s = self > > Then you can use code like this: s.a_dot = s.k(s.a-s.u) > > Another option, if you use the vars a lot in a given function, is to > copy them to local vars. This can also slightly speed up your code > (fewer member lookups). > Also, there is no rule saying you need to use "self", it's just a convention. You can declare your methods like this instead: def foo(s, arg1, arg2): s.a_dot = s.k(s.a-s.u) From steve at holdenweb.com Tue Sep 4 19:11:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Sep 2007 16:11:18 -0700 Subject: parameter list notation In-Reply-To: <1188943564.291412.16000@50g2000hsm.googlegroups.com> References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> <1188882641.899594.212400@22g2000hsm.googlegroups.com> <13drhdial6p58ca@corp.supernews.com> <1188943564.291412.16000@50g2000hsm.googlegroups.com> Message-ID: TheFlyingDutchman wrote: > On Sep 4, 1:53 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 03 Sep 2007 22:10:41 -0700, TheFlyingDutchman wrote: >>> Well I did a search on "Python variable length arguments" and found a >>> hit that seems to explain the *fields parameter: >>> When you declare an argment to start with '*', it takes the argument >>> list into an array. >> No it doesn't. >> >>>>> def test(*args): >> ... import array >> ... assert type(args) is array.array, "Not an array" >> ...>>> test(1, 2, 3) >> >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 3, in test >> AssertionError: Not an array > > Oh, I forgot the context of the discussion! As you are well aware, my > Python fork() (which I am now calling PIEthun 3.01 in beta and PIEthun > 3000 upon release) has made a few changes. Tuples are known as arrays. > Lists are known as uarrays (for updatable array) and the array module > has been renamed to homo_uarray (homogenous_updatable_array was just > too much typing). > > In the future I will be sure to specify the context of my statements - > whether PIEthunic or Pythonic in nature. > > Perhaps you could move further discussions to comp.lang.piethun? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From massonmousson at gmail.com Thu Sep 13 21:05:15 2007 From: massonmousson at gmail.com (Thierry Masson) Date: Thu, 13 Sep 2007 18:05:15 -0700 Subject: Extending Python with C API Message-ID: Hello, I'm trying to use the C API to extend Python. I've looked at various books and web sites (including the docs at python.org) and I can't get any of the samples to work. Below is a very minimalist example that I'm trying to get working and I was wondering if someone could tell me where I'm going wrong. It's probably something very obvious to those familiar with this technique. gtestmodule.c: -------------------- #include "Python.h" int GetInt(int iVal) { return iVal; } char* GetString(void) { return "This is the message"; } PyObject* gtestmodule_GetInt(PyObject* pSelf, PyObject* pArgs) { int x = 0; if (!PyArg_ParseTuple(pArgs, "i", &x)) return NULL; GetInt(x); return PyBuildValue("i", x); } PyObject* gtestmodule_GetString(PyObject* pSelf, PyObject* pArgs) { char* szMsg = GetString(); return PyBuildValue("s", szMsg); } static PyMethodDef gtestmoduleMethods[] = { {"GetInt", gtestmodule_GetInt, METH_VARARGS, "Description goes here"}, {"GetString", gtestmodule_GetString, METH_VARARGS, "Description goes here"}, {NULL, NULL} }; setup.py: ------------ from distutils.core import setup, Extension setup(name = "gtestmodule", version = "1.0", maintainer = "thierry masson", maintainer_email = "blah at blah.com", description = "test module", ext_modules = [Extension("gtestmodule",["gtestmodule.c"])], ) test.py: ---------- import gtestmodule print gtestmodule.GetInt(36); print gtestmodule.GetString(); The setup script builds the library OK, and I've verified that gtestmodule.so is getting created. But when I try to run a test script ( test.py, above) that uses the library, I get this error: Traceback (most recent call last): File "test.py", line 2, in ? import gtestmodule ImportError: ./gtestmodule.so: undefined symbol: PyBuildValue The OS is Red Hat Enterprise Linux ES release 3 (Taroon Update 8), and the Python version is 2.2.3 (rather old, I know, but I don't control the server environment and my sysadmin tells me this is the most recent version of Python officially supported by Red Hat. Can anyone see where I'm going wrong? Thanks! Thierry -------------- next part -------------- An HTML attachment was scrubbed... URL: From p at ulmcnett.com Fri Sep 7 14:47:10 2007 From: p at ulmcnett.com (Paul McNett) Date: Fri, 07 Sep 2007 11:47:10 -0700 Subject: Python and Cron In-Reply-To: References: Message-ID: <46E19CAE.10205@ulmcnett.com> Greg Lindstrom wrote: > This may be more of a Linux question, but I'm hoping some of you may be > able to help me. > > I have a python (2.4) routine running on Gentoo Linux. It creates a > file and, after the file is complete, renames the file using the > os.rename() command. When I run the file from the command line > everything works great, but when I schedule the job to run from the > crontab file, the original file is created and populated, but the rename > fails. I am using full paths for both the original and destination > file, and run the command line version after I 'su' to the production > account (named 'edith'). I am told by my sysadmin that the cron jobs > run as edith as well, so he does not think it is a permission issue (he > points out the original file is being created and populated as > expected...the rename fails) > > Have any of you dealt with anything like this? It really has me > scratching my head. Can you post the Python script? What's the name of the original file, and what are you trying to rename it to? I'm wondering if you are deriving the new name from something, and that thing is failing from within the cronjob for some reason. Perhaps the new name contains a complete path in one of the cases but not in the other... Edith should be getting email (if email routing is set up correctly) if the job is failing or producing output. Specifically, perhaps she's getting Python tracebacks and not telling you... :) -- pkm ~ http://paulmcnett.com From maxim.gavrilov at gmail.com Mon Sep 24 14:26:04 2007 From: maxim.gavrilov at gmail.com (Vircom) Date: Mon, 24 Sep 2007 11:26:04 -0700 Subject: Small changes in side library In-Reply-To: References: <1190509647.227883.226460@d55g2000hsg.googlegroups.com> Message-ID: <1190658364.739221.39030@k79g2000hse.googlegroups.com> On Sep 24, 1:16 am, "Gabriel Genellina" wrote: > En Sat, 22 Sep 2007 22:07:27 -0300, maxim.gavri... at gmail.com > escribi?: > > > > > I have the side library which provides wide set of different > > functions, but I'm going to replace some of them with mine and > > provided such 'modified' library thought my project. > > > The following way works well for my purpose: > > > ------- mylib.py ------- > > import sidelib > > > import os, sys, .... > > > def func(): > > ..... > > sidelib.func = func > > ...... > > ?!?!?!?! > > -------------------------- > > > But this cause to write mylib.sidelib.func() to function call, is it > > any way to 'map' definitions from sidelib to mylib (possible at point > > marked ?!?!?!?!) such that constructions like mylib.func() will be > > provided and client code don't see difference between changed and > > original library in syntax way? > > Your code already works as you like: > import sidelib > sidelib.func() > and you get the modified function. > > You don't have to say mylib.sidelib.func - in fact, mylib.sidelib is the > same module object as sidelib > But you have to ensure that the replacing code (mylib.py) runs *before* > anyone tries to import something from sidelib. > > > One my idea was to do from sidelib import * and then modify globals() > > dictionary, but this isn't good too because mylib imports many other > > modules and they all mapped into it's namespace (like mylib.os, > > mylib.sys). > > As you said, a bad idea. > > -- > Gabriel Genellina Thank you for reply! I make a mistake in my problem description, because I'm going not only use my own functions (it'll be simple import library question), but also using side library many functions (with only a few one replaced by me). For now I'm stay at the following solution: ----- mylib.py ----- import sidelib from sidelib import * _sidelib_set = set(dir(sidelib)) _mylib_set = set(['replacedfunc1', 'replacedfunc2', ....]) # all exports __all__ = list(_sidelib_set.union(_mylib_set)) ....implementations of _mylib_set functions.... -------------------- Seems it's pretty good for my task, mylib seems fully the same as the sidelib one. Thanks for you attention, anyway! From gagsl-py2 at yahoo.com.ar Tue Sep 25 16:40:20 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Sep 2007 17:40:20 -0300 Subject: Python script to optimize XML text References: <496954360709241336i43173947sda5245c2d7477ecb@mail.gmail.com> <46F8B985.7000803@web.de> <496954360709250743t6eec0d51x6d713a97317e6260@mail.gmail.com> Message-ID: En Tue, 25 Sep 2007 11:43:03 -0300, Robert Dailey escribi?: > Thanks for everyone's input. I wanted to learn regular expressions, > however > I'm finding them to be quite evil. I think I've learned that it's always > a > good idea to make regex a very LAST resort. This is my opinion I'm > developing on. In any case, I like the ideas mentioned here concerning > using > the XML parser to do the job for me. Thanks again everyone, I think I'll > be > going with the XML parser to do what I need. So you get by yourself to the truth of this famous quote: Some people, when confronted with a problem, think ?I know, I'll use regular expressions.? Now they have two problems. (Jamie Zawinski) -- Gabriel Genellina From tjreedy at udel.edu Thu Sep 20 14:01:20 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Sep 2007 14:01:20 -0400 Subject: Sets in Python References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com><1190235483.412972.81280@v23g2000prn.googlegroups.com><_cmIi.3452$ZA5.919@nlpi068.nbdc.sbc.com><1190286192.103681.235270@w3g2000hsg.googlegroups.com> <4866bea60709201012x30fc0285j9c07dda2a1991d16@mail.gmail.com> Message-ID: "Chris Mellon" wrote in message news:4866bea60709201012x30fc0285j9c07dda2a1991d16 at mail.gmail.com... | On 9/20/07, Dustan wrote: | > On Sep 19, 10:58 pm, Bryan Olson wrote: | > > Bad news: Python 3000 has no immutable type for byte-strings. | > > The new bytes type cannot serve for dict keys or set members. | > > Many things one would want to hash are unhashable -- for | > > example, the results of the hash functions in hashlib. | > | > Are you serious???? | > | | It's a little Chicken Little. The current version of py3k has no | immutable bytes type, but there's work being done even as we speak to | implement it. To reinforce this comment: CPython3.0 will not be released for at least 9 months. The current 3.0.a1 is openly *experimental*. 3.0.a2 should be released within a few weeks with an invitation for anyone concerned with the final product to experiment with it. GvR's development strategy has been to start small and add what is clearly useful (rather than start large and trim). 3.0 is being trimmed bit. Where too much is trimmed, something can get added back. From eduardo.padoan at gmail.com Thu Sep 13 10:34:37 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Thu, 13 Sep 2007 11:34:37 -0300 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <46e94623$0$30375$9b4e6d93@newsspool4.arcor-online.net> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189666095.727426.135170@o80g2000hse.googlegroups.com> <1189685403.306218.13270@22g2000hsm.googlegroups.com> <13eigagsuk74l55@corp.supernews.com> <46e94623$0$30375$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On 9/13/07, Wildemar Wildenburger wrote: > because I'm trained to interpret the underscore as a synonym for one > space. It's not particularly beautiful, but that is probably a matter of > habituation. And that exact word is probably the reason why I'd still > use self or s (explained by a comment, because I can get very dumb if I > have to). Have you worked with code using gettext functions imported as "_"? When I see a single underscore as a name, i18n comes to mind. -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From fakeaddress at nowhere.org Mon Sep 10 06:09:34 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 10 Sep 2007 03:09:34 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: <13e9iqhmgofasfb@corp.supernews.com> References: <13e9iqhmgofasfb@corp.supernews.com> Message-ID: Dennis Lee Bieber wrote: > The best answer is probably to be found from the definition of > divmod() The divmod() function is one of those little delights that reminds me why I love Python, but I do not think it answers the question here. The definition of divmod() references the '%' operation, and not the other way around. http://docs.python.org/lib/built-in-funcs.html http://docs.python.org/ref/binary.html >>>> divmod(70, 6) > (11, 4) >>>> 6*11 + 4 > 70 >>>> divmod(-70, 6) > (-12, 2) >>>> 6 * -12 + 2 > -70 Also: >>> divmod(70, -6) (-12, -2) >>> -6*-12 + -2 70 >>> divmod(-70, -6) (11, -4) >>> -6*11 + -4 -70 > Or in general terms > > (a, b) = divmod(x, y) > x = y * a + b > IOWs, the definition of modulo, and the definition of integer division, > are linked... Right. Thus given integers x and y, y!=0, Python and C agree: x == (y * (x / y)) + (x % y) The disagreement is how integer division rounds. In C, integer division rounds toward zero. In Python, integer division rounds downward. -- --Bryan From gagsl-py2 at yahoo.com.ar Mon Sep 24 21:43:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Sep 2007 22:43:40 -0300 Subject: execfile and function call References: Message-ID: En Mon, 24 Sep 2007 16:59:52 -0300, Dave Westerman escribi?: > I've got a Jython script where I'm doing an execfile() to pull in a > small script that contains a function, which I then call. > > execfile(app_applscript) > optionList = createOptionList(applOptions) > > When I do this at the global level in my main script, it works just > fine. However, when I move this code into a function in my main script, > then it fails, telling me it can't find the function createOptionList(). > > Traceback (innermost last): > File "", line 459, in ? > File "", line 429, in processApplication > NameError: createOptionList > > Does anyone have any idea what I'm doing wrong? I noticed that > createOptionList no longer shows up when I do a dir(). Do I somehow have > to get that to be a global? How do I do that? To answer your specific question: Use execfile(app_applscript, globals()) instead (see ) But I think it would be better to *import* createOptionList from that module. Using __import__ or imp may help, but the details are a bit different in Jython so I can't help you so much in this regard. -- Gabriel Genellina From k_r_a_j_kumar at yahoo.co.in Wed Sep 19 04:50:43 2007 From: k_r_a_j_kumar at yahoo.co.in (Raj kumar) Date: Wed, 19 Sep 2007 09:50:43 +0100 (BST) Subject: How to know the starting point Message-ID: <96489.19792.qm@web8706.mail.in.yahoo.com> Hi, I need help regarding the starting point in python project, As we can find main() function in java class to know the starting class in java, what is the starting point in python project? How to find the starting point. Thank you --------------------------------- Get the freedom to save as many mails as you wish. Click here to know how. -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Sep 24 08:39:34 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Sep 2007 14:39:34 +0200 Subject: rules from an xml file References: <1190633685.275142.264540@r29g2000hsg.googlegroups.com> <5lpm4dF93534U1@mid.uni-berlin.de> <5lpolvF95s07U4@mid.uni-berlin.de> Message-ID: <5lppg6F90nllU1@mid.uni-berlin.de> Marc 'BlackJack' Rintsch wrote: > On Mon, 24 Sep 2007 13:42:05 +0200, Diez B. Roggisch wrote: > >> jonny wrote: >> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> Something is wrong! >>> >>> >>> ... >>> ... >>> >>> [?] >> [?] >> Just a note: the use of "par_X" as attributes is unfortunate, to say the >> least. It doesn't allow for easy argument swapping, can cause troubles >> because you delete one attribute and miss renaming the others, and in >> general it's not good design to have arbitrary numbers of parameters. > > Quite the same is true for numbers in tag names. If you (the OP) need to > number the rules better use an attribute for the numbers. I meant of course 0 + Diez From deets at nospam.web.de Thu Sep 20 08:50:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 20 Sep 2007 14:50:10 +0200 Subject: I MEANT ONIX.... [it was Re: ONYX] In-Reply-To: <1190291923.310128.156430@22g2000hsm.googlegroups.com> References: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> <46f1726f$0$15276$426a74cc@news.free.fr> <1190282489.824709.29050@r29g2000hsg.googlegroups.com> <1190283378.175422.73290@r29g2000hsg.googlegroups.com> <46f25191$0$29574$426a34cc@news.free.fr> <1190291923.310128.156430@22g2000hsm.googlegroups.com> Message-ID: <5lf8ktF7v7b7U1@mid.uni-berlin.de> korovev76 at gmail.com schrieb: > On 20 Set, 12:55, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >> First question : do you *really* need a validating parser ? >> > that's what they told me ("they" being "da boss")... I mean: i have to > validate and to parse... i guess you can't do it at the same time, can > you? > > >> Second question : did you try to google for >> "+Python +validating +XML +parser" > > I've already googled it, and found pyRXP... but I was looking for > someone/something already experienced with onix... Well, it's XML with a DTD. Not much to see there. Nobody is going to help you generate and/or process it, as the application is _very_ domain-specific and unlikely to have some pre-built support libs. However, using python you should be in an excellent position to create one for yourself - and maybe share, if "da boss" allows it. Diez From steve at REMOVE-THIS-cybersource.com.au Tue Sep 4 17:17:09 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 04 Sep 2007 21:17:09 -0000 Subject: function call References: <1188937059.459609.61850@57g2000hsv.googlegroups.com> Message-ID: <13driql1otk1u7a@corp.supernews.com> On Tue, 04 Sep 2007 13:17:39 -0700, ianar? wrote: > Hey all, > > Is there a way of printing out how a function was called? In other words > if I do the following: > > def someFunction(self): > self.someOtherFunction(var1, var2) > > > I would get something like "someOtherFunction: called by: someFunction, > args are: var1, var2" The obvious way is: def someFunction(self): print "someOtherFunction: called by: someFunction," \ "args are: %s, %s" % (var1, var2) self.someOtherFunction(var1, var2) but that has obvious inconveniences. Perhaps you should look at the Python debugger and profiler? Do they solve the underlying problem you are trying to solve? -- Steven. From jura.grozni at gmail.com Sat Sep 29 14:52:49 2007 From: jura.grozni at gmail.com (azrael) Date: Sat, 29 Sep 2007 18:52:49 -0000 Subject: wxpython combined with vpython Message-ID: <1191091969.393341.286380@57g2000hsv.googlegroups.com> One question. I didn't try it, just one idea Is it possible to put a Vpython window inside a WX frame like it is a part of the wxframe between sizers or anything els From nagle at animats.com Wed Sep 5 11:25:05 2007 From: nagle at animats.com (John Nagle) Date: Wed, 05 Sep 2007 08:25:05 -0700 Subject: FCGI app reloading on every request - solved In-Reply-To: References: <46DCDE59.8060109@animats.com> Message-ID: <46DECA51.8060407@animats.com> Sion Arrowsmith wrote: > John Nagle wrote: > >> Tried putting this in the .htaccess file: >> >> >>SetHandler fcgid-script >>Options ExecCGI >>allow from all >> >> >> >>ErrorDocument 403 "File type not supported." >> >> >> Even with that, a ".foo" file gets executed as a CGI script, >>and so does a ".fcgi" file. It's an Apache configuration problem. > > > I'd look to see if you've got a AllowOverride None set somewhere > unhelpful (probably on the cgi-bin directory, although I note the > default Apache2 config on my machine here does it for the document > root too). Mind you, if you're managing this with a web tool rather > than having access to the Apache config files, it might not be so > straightforward to do. I now know what's wrong; it's a combination of several problems. First, configuring Apache via Plesk has very limited options, and no documentation telling you what it's doing. The actual problem is that Plesk generates, in "/etc/conf/httpd.conf". ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" This makes anything in cgi-bin executable with mod-cgi, regardless of anything set up for any other suffix. For historical reasons, CGI gets better treatment in Apache than other "mod-" components, and apparently ScriptAlias outranks Files and AddHandler. So that's why .fcgi programs were being run as .cgi programs. With the Plesk-created configuration, an executable ".fcgi" file in any web-server-visible directory OTHER than "cgi-bin" will execute with mod_fcgi. So that's how to get around this. Note that this is backwards from the usual CGI configuration, where scripts will execute only from "cgi-bin". This has security implications. If you're using Plesk, you can't change the defaults, because Plesk regenerates the config files when you use the Plesk control panel app. Nor will overrides in .htaccess work; those are disallowed by an "AllowOverride None". So you're stuck with what Plesk gives you. Even on a dedicated server using Plesk. Then there's mod_fcgid, which Plesk configures but has almost no documentation either. If mod_fcgid can't spawn an application process, for any reason, including a simple Python error, the error message is "[warn] mod_fcgid: can't apply process slot for ...". That's all you get in the Apache log. The web user gets "Service Temporarily Unavailable", because mod_fcgid doesn't distinguish internally between "don't have enough resources to spawn a new process" and "new process didn't launch correctly". I had to look at the source code for mod_fcgid to figure out what it meant. (Ruby on Rails people get this message now and then, and they're puzzled by it.) So that's what's going on. This sort of thing is why mod_fcgid, which is actually a good concept, isn't used much. John Nagle From steve at holdenweb.com Thu Sep 27 11:54:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 11:54:30 -0400 Subject: Cross-platform time out decorator In-Reply-To: <1190907553.425261.273400@w3g2000hsg.googlegroups.com> References: <1190802115.585306.250400@o80g2000hse.googlegroups.com> <1190899882.702911.44670@w3g2000hsg.googlegroups.com> <87k5qc18gf.fsf@mulj.homelinux.net> <1190907553.425261.273400@w3g2000hsg.googlegroups.com> Message-ID: Joel wrote: > On Sep 27, 4:36 pm, Hrvoje Niksic wrote: >> Joel writes: >>> I found the solution : >>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440569 >>> describes a solution based on threads. I tested it and it works >>> perfectly. >> Note that, unlike the original alarm code, it doesn't really interrupt >> the timed-out method, it just returns the control back to the caller, >> using an exception to mark that a timeout occurred. The "timed out" >> code is still merrily running in the background. I don't know if it's >> a problem in your case, but it's an important drawback. > > There should be a method to stop the thread though? I've never > programmed thread stuff in python and wasn't able to find how to do > it, would you happen to know how to "kill" the timed out thread? > There is no way to "kill" a thread, other than set a flag and have the thread read it to realise the main thread wants it to stop. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From martin at v.loewis.de Thu Sep 13 02:48:28 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 13 Sep 2007 08:48:28 +0200 Subject: Parallel/Multiprocessing script design question In-Reply-To: References: Message-ID: <46e8dd3d$0$16407$9b622d9e@news.freenet.de> > I tend to ramble, and I am afraid none of you busy experts will bother > reading my long post I think that's a fairly accurate description, and prediction. > I am hoping people > with experience using any of these would chime in with tips. The main thing > I would look for in a toolkit is maturity and no extra dependencies. Plus a > wide user community is always good. > POSH/parallelpython/mpi4py/pyPar/Kamaelia/Twisted I am so confused :( After reading your problem description, I think you need none of these. Parallelization-wise, it seems to be a fairly straight-forward task, with coarse-grained parallelism (which is the easier kind). > 2. The processing involves multiple steps that each input file has to go > through. I am trying to decide between a batch mode design and a pipelined > design for concurrency. Try to avoid synchronization as much as you can if you want a good speed-up. Have long-running tasks that don't need to interact with each other, rather than having frequent synchronization. If you haven't read about Amdahl's law, do so now. >From your description, it seems that having a single process process an entire input file, from the beginning to the end, sounds like the right approach; use the multiple CPUs to process different input files in parallel (IIUC, they can be processed in any order, and simultaneously). > In the batched design, all files will be processed > on one processing step(in parallel) before the next step is started. Why that? If you have N "worker" processes, each one should do the processing at its own rate. I.e. each one does all the steps for a single file in sequence; no need to wait until all processes have completed one step before starting the next one. As for N: don't make it the number of input files. Instead, make it the number of CPUs, or perhaps two times the number of CPUs. The maximum speed-up out of k CPUs is k, so it is pointless (and memory-consuming) to have many-more-than-k worker processes. > In a pipelined design, each file will be taken through all steps to the end. Perhaps this is what I suggested above - I would not call it "pipelined", though, because in pipelining, I would expect that the separate steps of a pipeline run in parallel, each one passing its output to the next step in the pipeline. That allows for a maximum speedup equal to the number of pipeline steps. IIUC, you have many more input documents than pipeline steps, so parallelizing by input data allows for higher speedups. > The subprocess module should allow spawning new processes, > but I am not sure how to get status/error codes back from those? What's wrong with the returncode attribute in subprocess? > I guess I can forget about communicating with those? Assuming all you want to know is whether they succeeded or failed: yes. Just look at the exit status. > I guess I would need some sort of queuing system here, to submit files > to the CPUs properly? No. You don't submit files to CPUs, you submit them to processes (if you "submit" anything at all). The operating system will chose a CPU for you. If you follow the architecture I proposed above (i.e. one Python process processes a file from the beginning to the end), you pass the file to be processed on the command line. If the processing is fairly short (which I assume it is not), you could have a single process process multiple input files, one after another (e.g. process 1 does files 1..400, process 401..800, and so on). > The other way could be to have each individual file run through all the > steps and have multiple such "pipelines" running simultaneously in parallel. Ok. See above - I wouldn't call it piplelined, but this is what you should do. > It feels like this method will lose cache performance because all the code > for all the steps will be loaded at the same time, but I am not sure if I > should be worrying about that. [I assume you mean "CPU cache" here] You should not worry about it, plus I very much doubt that this actually happens. The code for all the steps will *not* be loaded into the cache; that it sits in main memory has no effect whatsoever on cache performance. You can assume that all the code that runs a single step will be in the cache (unless the algorithms are very large). OTOH, the data of a input file will probably not fit in the CPU cache. You should be worried about reducing disk IO, so all processing of a file should run completely in memory. For that, it is better if you run an input file from the beginning to the end - if you would first read all 800 files, decompress them, then likely the output will not fit into the disk cache, so the system will have to read the compressed data from disk in the next step. Regards, Martin From zzbbaadd at aol.com Tue Sep 4 18:06:04 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 04 Sep 2007 15:06:04 -0700 Subject: parameter list notation In-Reply-To: <13drhdial6p58ca@corp.supernews.com> References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> <1188882641.899594.212400@22g2000hsm.googlegroups.com> <13drhdial6p58ca@corp.supernews.com> Message-ID: <1188943564.291412.16000@50g2000hsm.googlegroups.com> On Sep 4, 1:53 pm, Steven D'Aprano wrote: > On Mon, 03 Sep 2007 22:10:41 -0700, TheFlyingDutchman wrote: > > Well I did a search on "Python variable length arguments" and found a > > hit that seems to explain the *fields parameter: > > > When you declare an argment to start with '*', it takes the argument > > list into an array. > > No it doesn't. > > >>> def test(*args): > > ... import array > ... assert type(args) is array.array, "Not an array" > ...>>> test(1, 2, 3) > > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in test > AssertionError: Not an array Oh, I forgot the context of the discussion! As you are well aware, my Python fork() (which I am now calling PIEthun 3.01 in beta and PIEthun 3000 upon release) has made a few changes. Tuples are known as arrays. Lists are known as uarrays (for updatable array) and the array module has been renamed to homo_uarray (homogenous_updatable_array was just too much typing). In the future I will be sure to specify the context of my statements - whether PIEthunic or Pythonic in nature. From kyosohma at gmail.com Mon Sep 10 10:15:40 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 10 Sep 2007 07:15:40 -0700 Subject: wxPython unexpected exit In-Reply-To: <1189272447.892980.282380@r29g2000hsg.googlegroups.com> References: <1189152617.169438.296630@d55g2000hsg.googlegroups.com> <1189172540.784080.231440@22g2000hsm.googlegroups.com> <1189272447.892980.282380@r29g2000hsg.googlegroups.com> Message-ID: <1189433740.882996.15220@57g2000hsv.googlegroups.com> Hi, > Thanks for your help! It seems work! > Another question: I create a progress bar, and on creation, it will be > displayed, > How can I invisualize it when later I no longer need it? I think this is also a good way to use threads. Take a look at the wxPython demo for the ProgressDialog code. Basically, you run it in a loop and communicate with it every so often to tell it your progress. When you're done, you can set some sentinel type value which would kill the dialog. I've never used it, but that's how I understand its usage. As I mentioned, you should consider posting these types of questions to the wxPython group: http://www.wxpython.org/maillist.php Mike From hniksic at xemacs.org Thu Sep 27 10:36:32 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 27 Sep 2007 16:36:32 +0200 Subject: Cross-platform time out decorator References: <1190802115.585306.250400@o80g2000hse.googlegroups.com> <1190899882.702911.44670@w3g2000hsg.googlegroups.com> Message-ID: <87k5qc18gf.fsf@mulj.homelinux.net> Joel writes: > I found the solution : > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440569 > describes a solution based on threads. I tested it and it works > perfectly. Note that, unlike the original alarm code, it doesn't really interrupt the timed-out method, it just returns the control back to the caller, using an exception to mark that a timeout occurred. The "timed out" code is still merrily running in the background. I don't know if it's a problem in your case, but it's an important drawback. From bignose+hates-spam at benfinney.id.au Tue Sep 18 21:46:29 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Sep 2007 11:46:29 +1000 Subject: [ANN] Metatest 0.1.0 References: <87sl5by343.fsf@benfinney.id.au> <46F0633E.7020304@pytex.org> Message-ID: <87d4wfxw96.fsf@benfinney.id.au> [Jonathan, please don't send me copies of messages sent to the discussion thread. I follow comp.lang.python via a non-mail interface, and it's irritating to get unwanted copies of messages via email.] Jonathan Fine writes: > Ben Finney wrote: > > Jonathan Fine writes: > >> plus(2, '', _ex=TypeError) > > > > This second example seems counterintuitive. Is '_ex' part of the > > public interface? If so, why does it follow the convention for > > "not part of the public interface" (i.e. it is named with an > > underscore)? > > [...] > The line > plus(2, '', _ex=TypeError) > causes something to be recorded, and when the test is run the _ex > argument is filtered off, and the remaining arguments passed to the > plus function, as imported from mymod. That's confusing, then, for two reasons: It looks like '_ex' is an argument to the 'plus' function, which otherwise (probably by design) looks exactly like a call to the 'plus' function the programmer is testing. Since this is, instead, an assertion *about* that function, it is misleading to see it as an argument *to* the function. It uses the "leading-underscore" convention which means "this is not part of the public interface, and you'd better know what you're doing if you use this externally". > Finally, if you can think of a better way of saying, in Python, "The > function call plus(2, '') raises a TypeError", please let me know, > and I'll consider using it in the next version of Metatest. I would think an explicit function call that says what it's doing would be better. The unittest module implements this as: self.failUnlessRaises(TypeError, plus, 2, '') or more generally: func = plus func_args = [2, ''] self.failUnlessRaises(TypeError, func, *func_args) which has the benefit of being explicit about what it's doing. -- \ "Sometimes I -- no, I don't." -- Steven Wright | `\ | _o__) | Ben Finney From larry.bates at websafe.com Tue Sep 25 12:23:04 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 25 Sep 2007 11:23:04 -0500 Subject: comparing elements of a list with a string In-Reply-To: <1190734785.439839.303030@50g2000hsm.googlegroups.com> References: <1190734785.439839.303030@50g2000hsm.googlegroups.com> Message-ID: Shriphani wrote: > Hello all, > I have a problem here. I have a list named list_of_files which > contains filenames with their timestamps attached to the name. If I > have a string "fstab", and I want to list out the files in whose names > the word fstab appears should I go about like this : > > def listAllbackups(file): > list_of_files = os.listdir("/home/shriphani/backupdir") > for element in list_of_files: > if element.find(file) != -1: > date = ### > time = #### > return (date, time) > > The major trouble is that the return statement causes it to exit after > attempt one. How do I use the yield statement here? > > Regards, > Shriphani Palakodety > You should take a quick look at glob(). You may be able to use it to make life a lot easier. Here is how you would do it if all your backup files begin with fstab. import glob list_of_backup_files=glob.glob('/home/shriphani/backupdir/glob*') If "fstab" can appear anywhere in the filename, this might not work for you. -Larry From bbxx789_05ss at yahoo.com Fri Sep 7 19:13:13 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 07 Sep 2007 16:13:13 -0700 Subject: why should I learn python In-Reply-To: References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> <13e1e52cfb1u505@corp.supernews.com> Message-ID: <1189206793.284959.264040@19g2000hsx.googlegroups.com> On Sep 6, 9:20 pm, "Gabriel Genellina" wrote: > En Thu, 06 Sep 2007 23:34:10 -0300, Grant Edwards > escribi?: > > > On 2007-09-06, Torsten Bronger wrote: > >> Hall?chen! > > >> Tom Brown writes: > > >>> [...] Python has been by far the easiest to develop in. Some > >>> people might say it is not "real programming" because it is so > >>> easy. > > >> I can't believe this. Have you really heard such a statement? > > > Maybe it's a allusion to that fake Stroustrup interview where > > he supposedly explains that C++ was meant to be a difficult > > language to use as a means to keep more programmers employed at > > higher salaries? > > I always thought the only goal of the C++ standard comittee was to devise > the most intrincate and convoluted rule ever imaginable. > It's like playing AD&D: the basic manual says something, but The Book Of > The Perfect And Sublime Elf says that in this case this other rule > applies, but a warrior Elf can read in The Ultimate And Most Complete > Warrior Companion a totally different rule, but the character's alignment > forbids all the three possibilities... > > -- > Gabriel Genellina Ha, ha, ha! lol. :) From paul.hankin at gmail.com Tue Sep 25 15:02:48 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 25 Sep 2007 19:02:48 -0000 Subject: Script to extract text from PDF files In-Reply-To: References: Message-ID: <1190746968.162359.39890@r29g2000hsg.googlegroups.com> On Sep 25, 6:41 pm, brad wrote: > I have a very crude Python script that extracts text from some (and I > emphasize some) PDF documents. On many PDF docs, I cannot extract text, > but this is because I'm doing something wrong. The PDF spec is large and > complex and there are various ways in which to store and encode text. I > wanted to post here and ask if anyone is interested in helping make the > script better which means it should accurately extract text from most > any pdf file... not just some. > > I know the topic of reading/extracting the text from a PDF document > natively in Python comes up every now and then on comp.lang.python... > I've posted about it in the past myself. After searching for other > solutions, I've resorted to attempting this on my own in my spare time. > Using apps external to Python (pdftotext, etc.) is not really an option > for me. If someone knows of a free native Python app that does this now, > let me know and I'll use that instead! Googling for 'pdf to text python' and following the first link gives http://pybrary.net/pyPdf/ -- Paul Hankin From mbrown at phys.ksu.edu Mon Sep 10 23:15:40 2007 From: mbrown at phys.ksu.edu (yagyala) Date: Mon, 10 Sep 2007 20:15:40 -0700 Subject: pipes Message-ID: <1189480540.812171.285820@r34g2000hsd.googlegroups.com> Hi. I'm rtying to use pipes to communicate between a python GUI and a spawned C++ program. I prefer not to use forking because the app may be run on windows, where forking isn't supported. Roughly what I'm doing is: (r,w) = os.pipe() spawnl(P_WAIT, 'tool.exe', ' ', message, str(w)) close(w) print os.read(r, 1000) In c++ , ... int main(int argc, char** argv) { } From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Sep 10 07:36:17 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 10 Sep 2007 13:36:17 +0200 Subject: less obvious "super" References: <1189417830.645749.226120@d55g2000hsg.googlegroups.com> Message-ID: <5kkohhF49338U1@mid.individual.net> Nagarajan wrote: > class A : > def __init__( self ): > self.x = 0 > > class B ( A ): > def __init__( self, something ): > # Use "super" construct here so that I can "inherit" x of > # A > self.y = something > > How should I use "super" so that I could access the variable "x" > of A in B? Since you're neither using new-style classes (inheriting from object) nor multiple inheritance, better use the classic way: class B(A): def __init__(self, something): A.__init__(self) self.y = something IMHO, you could also benefit from looking at an OO python tutorial since this is a standard approach. Regards, Bj?rn -- BOFH excuse #145: Flat tire on station wagon with tapes. ("Never underestimate the bandwidth of a station wagon full of tapes hurling down the highway" Andrew S. Tannenbaum) From aclarke11 at yahoo.co.uk Wed Sep 12 15:05:06 2007 From: aclarke11 at yahoo.co.uk (Tony) Date: Wed, 12 Sep 2007 12:05:06 -0700 Subject: Tkinter pack difficulty In-Reply-To: <1189617737.700363.187450@g4g2000hsf.googlegroups.com> References: <1189617737.700363.187450@g4g2000hsf.googlegroups.com> Message-ID: <1189623906.451500.111900@d55g2000hsg.googlegroups.com> On Sep 12, 6:22 pm, Simon Forman wrote: > Hi all, > >Snip> Any thoughts or advice? > > Thanks in advance, > ~Simon > This seems to do what you want, the difference is that the expand option is left out top and bottom, also I increased height and put in a width value as well: from Tkinter import * t = Tk() header = Frame(t, bg="black", height=30, width = 10) header.pack(fill=X, side=TOP, anchor=N) body = Frame(t, bg="grey") body.pack(expand=1, fill=BOTH, anchor=CENTER) log = Frame(t, bg="white", height=30, width = 10) log.pack( fill=X, side=BOTTOM, anchor=S) t.mainloop() Ciao Tony From koutoo at hotmail.com Mon Sep 17 11:31:13 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Mon, 17 Sep 2007 08:31:13 -0700 Subject: Use GUI for Python Message-ID: <1190043073.093736.272750@k79g2000hse.googlegroups.com> I am new to python as I have been a VB programmer. I am used to the GUI interface, and was wondering if I had to choose between a GUI for Python, which one should I go with? Thanks. Kou From rrr at ronadam.com Fri Sep 21 03:32:00 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 21 Sep 2007 02:32:00 -0500 Subject: Python 3K or Python 2.9? In-Reply-To: <1190053757.091035.221570@22g2000hsm.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1190013827.107324.111820@w3g2000hsg.googlegroups.com> <1190053757.091035.221570@22g2000hsm.googlegroups.com> Message-ID: <46F37370.9040809@ronadam.com> TheFlyingDutchman wrote: > I am not talking about the way it does it, but rather, the way it > could do it or... could have done it. That requires no knowledge of > how the interpreter currently does it unless I am proposing something > that no interpreter in the world could ever do. Yes, there are a couple of things that could have been changed. But from what I can tell there are a number of reasons why things where chosen to be the way they are. Two of those reasons is to make the core C code smaller and easier to maintain and also to make it easier to understand how things work. Exposing the inner workings as visible python code vs hidden C code helps both of those. Another benefit of exposing more of the class machinery of Pythons objects as python code, is it makes it possible to modify more of how things work directly with python code. A good way to see how this works is studying how descriptors and properties work. http://users.rcn.com/python/download/Descriptor.htm You will find there is much more of python written in python than it may first seem. In some cases the built in classes and modules are written in C, yet they still work as if they are written in Python. So if you can find a way to do things like removing self in python in such a way that it doesn't require adding more to the Core interpreter, then it might be considered. What I've found is as my skills improve, I take more advantage of being able to modify and/or introspect how things work. This allows more choices on how I might solve a particular problem. I also think there a lots of improvements that could be made to other parts of python such as the libraries that would be of much more practical benefit. Regards, Ron From python.list at tim.thechases.com Sun Sep 30 14:22:10 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 30 Sep 2007 13:22:10 -0500 Subject: code for number guessing by computer In-Reply-To: <1191174817.788812.40360@y42g2000hsy.googlegroups.com> References: <1191174817.788812.40360@y42g2000hsy.googlegroups.com> Message-ID: <46FFE952.30302@tim.thechases.com> > hi, please help me,,,,,, a newbie.......send me code for a programme > in which the computer tell u the number that u guessed............ I can think of at least two versions of this: >>> _ = raw_input("Think of an integer greater than 1 and less than 3") >>> print "Your number was 2! This code is teh awesome!" or, if you need to guess an arbitrary number greater than "N", you can use this spiffy code: >>> print "Think of an integer greater than zero and I will guess it" >>> i = 1 >>> while raw_input("Was your number %i?" % i) <> "yes": i += 1 ... >>> print "I guessed your number correctly!" Oh...unless this was a homework problem and you were looking for a standard binary search of a problem-space, in which case, mailing lists don't generally do your homework for you. However, the first solution I provided is *far* better than a boring old binary-search because it solves the problem in O(1) rather than O(log N) which any good math wonk will tell you is a much more efficient algorithm! :) -tkc From dotancohen at gmail.com Sun Sep 9 20:14:58 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 10 Sep 2007 03:14:58 +0300 Subject: =?UTF-8?Q?Re:_Re=C3=A2=C2=AD:_=C3=A2=C2=ACM?= =?UTF-8?Q?odul=C3=A2=C2=AD_(%)_=C3=A2=C2=ACi?= =?UTF-8?Q?n_python_not_like_in_C=C3=A2=C2=AD=3F=C3=A2=C2=AC?= In-Reply-To: References: Message-ID: <880dece00709091714w3d1a9d81l6de0ade3ac44d99d@mail.gmail.com> On 09/09/2007, Roy Smith wrote: > In article , > "Dotan Cohen" wrote: > > > FIrst of all, how is the % symbol (as in 70%6=4) called in English? > > It's called "modulo", but most people pronounce it "mod". > > It's documented at http://docs.python.org/ref/binary.html > Thanks, Roy. But it's hard to find when one doesn't know it's name! Dotan Cohen http://what-is-what.com http://gibberish.co.il -- ?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From steve at holdenweb.com Sat Sep 1 00:17:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Sep 2007 00:17:52 -0400 Subject: Automation and scheduling of FrontPage publishing using Python In-Reply-To: References: <1188517723.279932.299400@x40g2000prg.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In message <1188517723.279932.299400 at x40g2000prg.googlegroups.com>, > andrew.arobert at gmail.com wrote: > >> We have numerous web sites which are currently being manually >> published via Front Page. >> >> Doing one or two sites on an ad-hoc basis was not too bad but we are >> now over 20 or thirty at set times during a business day. > > Let me open the bidding by suggesting that you stop using FrontPage. But that would mean reprogramming the functionality they now implement using FrontPage extensions. Any help with that? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From hall.jeff at gmail.com Sat Sep 29 14:24:53 2007 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Sat, 29 Sep 2007 18:24:53 -0000 Subject: Program inefficiency? In-Reply-To: References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> <1191087234.915654.182370@k79g2000hse.googlegroups.com> Message-ID: <1191090293.017485.225470@y42g2000hsy.googlegroups.com> The search is trying to replace the spaces in our bookmarks (and the links that go to those bookmarks)... The bookmark tag looks like this: and the bookmark tag looks like this some pitfalls I've already run up against... SOMETIMES (but not often) the a and the href (or name) is split across a line... this led me to just drop the ")+') and the corresponding name replace and then the one corner case we ran into of p100= re.compile('(a name=)+(.*)(-)+(.*)(>)+') From jstroud at mbi.ucla.edu Fri Sep 14 21:57:40 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 14 Sep 2007 18:57:40 -0700 Subject: regexp search on infinite string? In-Reply-To: <1189802940.518794.129130@r29g2000hsg.googlegroups.com> References: <1189802940.518794.129130@r29g2000hsg.googlegroups.com> Message-ID: Paddy wrote: > Lets say i have a generator running that generates successive > characters of a 'string' >>From what I know, if I want to do a regexp search for a pattern of > characters then I would have to 'freeze' the generator and pass the > characters so far to re.search. > It is expensive to create successive characters, but caching could be > used for past characters. is it possible to wrap the generator in a > class, possibly inheriting from string, that would allow the regexp > searching of the string but without terminating the generator? In > other words duck typing for the usual string object needed by > re.search? > > - Paddy. > re.search & re.compile checks for str or unicode types explicitly, so you need to turn your data into one of those before using the module. buffer = [] while True: buffer.append(mygerator.next()) m = re.search(pattern, "".join(buffer)) if m: process(m) buffer = [] James From mail at timgolden.me.uk Thu Sep 13 07:18:01 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 13 Sep 2007 12:18:01 +0100 Subject: Python+Expect+Win32 = Not Possible? In-Reply-To: <1189681397.349994.126130@57g2000hsv.googlegroups.com> References: <1189657637.539038.317280@k79g2000hse.googlegroups.com> <1189672955.321701.164050@57g2000hsv.googlegroups.com> <1189681397.349994.126130@57g2000hsv.googlegroups.com> Message-ID: <46E91C69.6030607@timgolden.me.uk> gamename wrote: > On Sep 13, 1:42 am, half.ital... at gmail.com wrote: >> On Sep 12, 9:27 pm, gamename wrote: >> >>> Hi, >>> Is it still the case there is no practical Expect-like module for >>> win32? I know that cygwin can support pexpect, but that isn't an >>> option here --- I have to use a native win32 Python version. >>> Are there alternatives, or is it simply not an option to replicate >>> Expect on win32 with python? >>> All I'm trying to do is start a couple processes, wait for each to say >>> "done" on stdout and then quit (or timeout if something went wrong). >>> TIA, >>> -T >> I had planned on using telnet to do the same thing on windows. I >> don't think I ever proved it, but I'm pretty sure it will work. > > Thanks, Sean. The problem is that telnet is generally disabled on > most hosts nowadays. I'm not sure whether the need you describe above "start a couple [of] processes, wait for each to say 'done' and then quit (or timeout...)" is *all* of your requirements or just an example. And are these processes running on remote machines? Or just locally? Depending on those things, maybe there are other ways to do what you want under Windows? (I've checked back through the archives and I can't find any earlier posts describing the requirement more clearly). TJG From bj_666 at gmx.net Fri Sep 7 02:25:19 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2007 06:25:19 GMT Subject: Using wild character References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> <1189058095.671230.262190@o80g2000hse.googlegroups.com> <5k9pjoF2mrncU1@mid.uni-berlin.de> <1189122511.231602.217710@w3g2000hsg.googlegroups.com> Message-ID: <5kc96fF31i6hU1@mid.uni-berlin.de> On Thu, 06 Sep 2007 16:48:31 -0700, Zentrader wrote: > On Sep 6, 12:47 am, Marc 'BlackJack' Rintsch wrote: >> On Wed, 05 Sep 2007 22:54:55 -0700, TheFlyingDutchman wrote: >> > To do a "*string" wildcard filter use the endswith() function instead >> > of startswith() and to do a *string* type wildcard filter use >> > the find() function > -1. >> >> Maybe better the ``in`` operator for the '*string*' type. `str.find()` >> will go away in the future. > > string.find serves a useful purpose in that it returns the starting > location of the string found, or -1 if not found, so if you wanted to > slice "abdecf" on"c", string.find will tell you where that is. But that position is not needed here and I think:: result = [name for name in names if 'spam' in name] reads more natural than:: result = [name for name in names if name.find('spam') > -1] Ciao, Marc 'BlackJack' Rintsch From m.n.summerfield at googlemail.com Thu Sep 13 02:27:12 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Thu, 13 Sep 2007 06:27:12 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: <7xzlzrtrjn.fsf@ruckus.brouhaha.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> Message-ID: <1189664832.876539.86800@k79g2000hse.googlegroups.com> On 13 Sep, 00:03, Paul Rubin wrote: > Mark Summerfield writes: > > I feel that Python lacks one useful data structure: an ordered > > dictionary. > > Do other Python programmers feel this lack? Is this worth a PEP? > > Yes. It should use a functional data structure. Could you elaborate? Here's my impression of the postings so far: there are 3 categories of response: (A) There is no need for such a thing. (B) It is useful, but so easy to implement that it needn't be in the library. (C) It is worth having an ordered data structure of some kind. Regarding (A) and (B): I remember Python before it had the sets module. "There's no need for sets, you can do them with dicts". Thankfully sets are in the language and I for one use them extensively. For (C) what I had in mind was: An API that is identical to a dict, with the few additional methods/ behaviours listed below: - If an item is inserted it is put in the right place (because the underlying data structure, b*tree, skiplist or whatever is intrinsically ordered by < on the key) - Extra methods key_at(index : int) -> key item_at(index : int) -> (key, value) value_at(index : int) -> value set_value_at(index : int, value) # no return value necessary but maybe key if convenient od[x:y:z] -> list of values ordered by key # can read a slice but not assign a slice and maybe keys_for(fromindex : int, uptobutexcludingindex : int) -> ordered list of keys I've given examples of the use cases I envisage (and that I use in both Python with my own ordered dict and in C++ with the map class) in a previous posting, and I've shown the API I envisage above. I know that some people might prefer ordering by value or the option of case- insensitive ordering, but both these can be achieved using the API above, e.g., od[value.lower()] = value # case-insensitive ordering of list of values And as for duplicates there are two approaches I use: (1) make each string unique as I showed in my previous post, or (2) use a value that itself is a list, dict or set. (As for those who have suggested an ordered data structure that isn't a dict, I don't see a conflict, I'd be happy to see more data structures in the collections module.) Is what I've suggested sufficient (and sufficiently general) for the standard library? If it is not, what should be done, or is there some other approach and API that would better provide the functionality envisaged? From ricardo.turpino at gmail.com Mon Sep 10 16:51:09 2007 From: ricardo.turpino at gmail.com (ricardo.turpino at gmail.com) Date: Mon, 10 Sep 2007 13:51:09 -0700 Subject: Mac OSX sqlite problem. Missing? In-Reply-To: <5klocbF498ruU1@mid.uni-berlin.de> References: <1189455305.994439.107100@r34g2000hsd.googlegroups.com> <5klocbF498ruU1@mid.uni-berlin.de> Message-ID: <1189457469.285055.212670@r29g2000hsg.googlegroups.com> Diez B. Roggisch wrote: > > Are you by any chance using the python 2.3 when issuing that import > statement? > > Diez Unfortunately not :( ibook:~/project1$ python -V Python 2.5 ibook:~/project1$ python Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite Traceback (most recent call last): File "", line 1, in ImportError: No module named sqlite >>> From theller at ctypes.org Fri Sep 7 11:30:53 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 07 Sep 2007 17:30:53 +0200 Subject: debugging program that uses ctypes In-Reply-To: <1189178285.647177.216320@g4g2000hsf.googlegroups.com> References: <1189178285.647177.216320@g4g2000hsf.googlegroups.com> Message-ID: marco_347 at yahoo.it schrieb: > hi all, I have a python program that calls a dll through ctypes > (py2.5). In some (reproducible) > conditions the program crashes with an error in ctypes module. You mean a segfault? > How can I trace down the problem? I have created a debug build of > python but I also use pyodbc > and dateutil libraries in my program and I don't know how to make them > visible to python_d.exe > Am I using the right approach? I would say yes. It seems you are using windows - running debug builds of python on windows start a dialog box that allows to attach the MSVC debugger to the running program. Usually this allows to locate the error fairly quickly. As you have discovered, the problem is that you need to build all the extensions that you use in debug mode otherwise you cannot use them. If you cannot rebuild the extensions you have to reproduce the crash in a script that doesn't use these extensions. Thomas From jstroud at mbi.ucla.edu Sun Sep 16 21:09:12 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 16 Sep 2007 18:09:12 -0700 Subject: adding a static class to another class In-Reply-To: References: Message-ID: Nathan Harmston wrote: > And also preventing more than one Manager instance instantiated at one > time. Forgot to answer this. You want the singleton pattern: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558 James From pdula at cisco.com Mon Sep 24 08:13:38 2007 From: pdula at cisco.com (Piotr Dula (pdula)) Date: Mon, 24 Sep 2007 14:13:38 +0200 Subject: enabling IPv6 in python Message-ID: Hello, How to make python support IPv6? I have IPv6 running on my host (interfaces have ipv6 addresses assigned) I tried to do: ./configure --enable-ipv6 make make install and I didn't get any error. However, IPv6 didn't work. then I tried ./configure --enable-ipv6=yes and I got a lot of parse errors (many pages of errors similar to the ones below) In file included from /root/Piotr/Python-2.5.1/Modules/_tkinter.c:67: /usr/include/tk.h:581: parse error before "Bool" /usr/include/tk.h:583: parse error before "event" /usr/include/tk.h:584: parse error before "root" /usr/include/tk.h:585: parse error before "subwindow" /usr/include/tk.h:586: parse error before "time" /usr/include/tk.h:586: `time' redeclared as different kind of symbol /usr/include/time.h:184: previous declaration of `time' /usr/include/tk.h:591: parse error before "same_screen" /usr/include/tk.h:597: parse error before "Bool" /usr/include/tk.h:599: parse error before "window" /usr/include/tk.h:601: parse error before "XActivateEven How to make it work? Thank you in advance, Piotr -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeroen.hegeman at gmail.com Fri Sep 21 12:34:40 2007 From: jeroen.hegeman at gmail.com (Jeroen Hegeman) Date: Fri, 21 Sep 2007 18:34:40 +0200 Subject: Newbie completely confused Message-ID: <4437CC27-104E-4EE9-80DB-DCF36213B44F@gmail.com> Dear Pythoneers, I'm moderately new to python and it got me completely lost already. I've got a bunch of large (30MB) txt files containing one 'event' per line. I open files after each other, read them line by line and from each line build a 'data structure' of a main class (HugeClass) containing some simple information as well as several instances of some other classes. No problem so far, but I noticed that the first file was always faster than the others, whereas I would expect it to be slower, if anything. Testing with two copies of the same file shows the same behaviour. Below is a (rather large, I'll explain) chunk of code. I ran this in a directory with two test files called 'test_file0.txt' and 'test_file1.txt', each containing 10k lines of the same information as the 'long_line' variable in the code. This shows the following timing (consistently) for the little piece of code that reads all lines from file: ...processing all 2 files found --> 1/2: ./test_file0.txt Now reading ... DEBUG readLines A took 0.093 s ...took 8.85717201233 seconds --> 2/2: ./test_file0.txt Now reading ... DEBUG readLines A took 3.917 s ...took 12.8725550175 seconds So the first time around the file gets read in in ~0.1 seconds, the second time around it needs almost four seconds! As far as I can see this is related to 'something in memory being copied around' since if I replace the 'alternative 1' by the 'alternative 2', basically making sure that my classes are not used, reading time the second time around drops back to normal (= roughly what it is the first pass). I already want to apologise for the size of the code chunk below. I know about 'minimal reproducible examples' and such but I found out that if I commented out the filling (and thus binding) of some of the member variables in the lower-level classes, the problem (sometimes) also disappears. That also points to some magic happening in memory? I probably mucked something up but I'm really lost as to where. Any help would be appreciated. The original problem showed up using Python 2.4.3 under linux (Fedora Core 1). Python 2.3.5 on OS X 10.4.10 (PPC) appears not to show this issue(?). Thanks, Jeroen P.S. Any ideas on optimising the input to the classes would be welcome too ;-) Jeroen Hegeman jeroen DOT hegeman AT gmail DOT com ===================Start of code chunk========================= #!/usr/bin/env python import time import sys import os import gzip import pdb long_line = "1,31905,0,174501,46152419,2117961,143,-1.0000,51,2,-19.9139,42,-19.9140 , 6.6002,0,0,0,46713.1484,2,0.0000,-1,1.4203220606,0.3876158297,147.121017 4561,147.1284120973,-2,0.0000,-1,1.5887237787,-2.4011900425,-319.7776794 434,319.7906836817,4,21,0.0000,-1,-0.5672637224,2.2052443027,-43.2842369 080,43.3440905719,21,0.0000,-1,-0.8540721536,0.0770076364,-22.7033920288 , 22.7195827425,21,0.0000,-1,0.1623233557,0.5845987201,-28.0794525146,28.0 860084170,21,0.0000,-1,0.1943928897,-0.2195242196,-22.0666370392,22.0685 899391,6,0.0000,-1,-40.1810989380,-127.0743789673,-104.9231948853,239.74 36794163,-6,0.0000,-1,43.2013626099,125.0640945435,-67.7339172363,227.17 53587387,24,0.0000,-1,-57.9123306274,-17.3483123779,-71.8334121704,123.4 397648033,-24,0.0000,-1,84.0985488892,54.4542312622,-62.4525032043,144.5 299239704,5,0.0000,-1,17.7312316895,-109.7260665894,-33.0897827148,116.3 039146130,-5,0.0000,-1,-40.8971862793,70.6098632812,-5.2814140320,82.645 4347683,4,0.0000,-1,-6.2859884724,-17.9586020410,-58.9464384913,69.40294 68585,-3,0.0000,-1,-51.6263811588,0.6104701459,-12.8869901896,54.0368221 571,3,0.0000,-1,16.4690684490,48.0271777511,-51.7867884636,74.5327484701 ,-4,0.0000,-1,67.6295298338,6.4269350171,-10.6658525467,69.9971834876,7, 7,1.0345464706e+01,-7.0800781250e+01,-2.0385742187e+01,7.5256346272e +01,1.3148,0.0072,0.0072,1.3148,0.0072,0.0072,1.0255,1.0413,0.0,0.0,0.0, 0.0,-1.0,-4.2383,49.5276,13,0.1537,0.5156,0,0.9982,0.0034,1.0000,7,1,0.9 566,0.0062,1,0,2,1.2736,1,7.8407,1,0,2,1.2736,1,7.8407,0,0,-1.0,-1.0,5,1 ,-2.4047853470e+01,4.0832519531e+01,-3.8452150822e+00,4.7851562559e +01,1.3383,0.0051,0.0051,1.3383,0.0051,0.0051,0.9340,0.9541,0.0,0.0,0.0, 0.0,-1.0,-2.4609,21.3916,7,0.1166,0.5977,0,0.9999,0.0052,1.0000,9,1,0.99 47,0.0063,1,0,2,0.7735,1,74.7937,1,0,2,0.7735,1,74.7937,0,0,-1.0,-1.0,5, 1,-4.4067382812e+01,2.5634796619e+00,-1.1138916016e+01,4.6203614579e +01,1.3533,0.0054,0.0054,1.3533,0.0054,0.0054,1.0486,1.0903,0.0,0.0,0.0, 0.0,-1.0,-3.9648,31.3733,13,0.1767,0.5508,100,0.9977,0.0040,1.0000,9,1,0 . 0000,0.4349,0,0,0,0.0000,0,-1000.0000,0,0,0,0.0000,0,-1000.0000,0,0,-1.0 ,-1.0,0,1,3.7200927734e+01,2.7465817928e+00,-5.5847163200e +00,3.7994386563e +01,1.3634,0.0062,0.0062,1.6488,0.0385,0.0385,0.7141,0.9013,5.3986899118 e+00,6.6766492833e-01,-2.3780213181e-01,5.4460399892e +00,0.5504,-3.1445,0.7776,9,0.1169,0.7734,0,0.9977,0.0040,1.0000,7,1,0.0 000,0.1099,0,0,0,0.0000,0,-1000.0000,0,0,0,0.0000,0,-1000.0000,1,-1,5.38 93,0.5459,4,1,1.2969970703e+01,3.3203125000e+01,-3.7231445312e +01,5.2001951876e +01,1.4414,0.0129,0.0129,1.4414,0.0129,0.0129,0.9019,0.7331,0.0,0.0,0.0, 0.0,-1.0,-10.0195,12.2034,17,0.1922,0.3633,0,0.9774,0.0248,1.0000,6,1,0. 0000,0.3523,0,0,0,0.0000,0,-1000.0000,0,0,0,0.0000,0,-1000.0000,0,0,-1.0 ,-1.0,0,1,-1.6174327135e+00,-7.1411132812e+00,-1.8798828125e +01,2.0202637222e +01,1.7886,0.0352,0.0352,1.7886,0.0352,0.0352,1.8257,1.2368,0.0,0.0,0.0, 0.0,-1.0,-17.3438,45.6714,10,0.1529,0.5625,0,0.9898,0.0094,1.0000,3,1,-1 . 0000,10000.0000,0,0,0,-1.0000,0,-1.0000,0,0,0,-1.0000,0,-1.0000,0,0,-1.0 ,-1.0,-6,0,-5.9204106331e+00,-3.4484868050e+00,-6.5307617187e +00,9.6740722971e +00,1.6782,0.0326,0.0326,1.6782,0.0326,0.0326,1.0000,1.0000,0.0,0.0,0.0, 0.0,-1.0,-9.4727,37.3401,13,0.2711,0.2344,100,0.9861,0.0045,1.0000,3,1,- 1.0000,10000.0000,0,0,0,-1.0000,0,-1.0000,0,0,0,-1.0000,0,-1.0000,0,0,-1 .0,-1.0,-6,0" ######################################################################## ### class SmallClass: def __init__(self): return def input(self, line, c): self.item0 = int(line[c]); c += 1 self.item1 = float(line[c]); c += 1 self.item2 = int(line[c]); c += 1 self.item3 = float(line[c]); c += 1 self.item4 = float(line[c]); c += 1 self.item5 = float(line[c]); c += 1 self.item6 = float(line[c]); c += 1 return c ######################################################################## ### class ModerateClass: def __init__(self): return def __del__(self): pass return def input(self, line, c): self.items = {} self.item0 = float(line[c]); c += 1 unit1 = SmallClass() c = unit1.input(line, c) self.items[len(self.items)] = unit1 unit2 = SmallClass() c = unit2.input(line, c) self.items[len(self.items)] = unit2 units_chunk = [] chunk_size = int(line[c]) c += 1 for i in xrange(chunk_size): unit = SmallClass() c = unit.input(line, c) units_chunk.append(unit) for i in xrange(10): unit = SmallClass() c = unit.input(line, c) return c ######################################################################## ### class LongClass: def __init__(self): return def clear(self): return def input(self, foo, c): self.item0 = float(foo[c]); c += 1 self.item1 = float(foo[c]); c += 1 self.item2 = float(foo[c]); c += 1 self.item3 = float(foo[c]); c += 1 self.item4 = float(foo[c]); c+=1 self.item5 = float(foo[c]); c+=1 self.item6 = float(foo[c]); c+=1 self.item7 = float(foo[c]); c+=1 self.item8 = float(foo[c]); c+=1 self.item9 = float(foo[c]); c+=1 self.item10 = float(foo[c]); c+=1 self.item11 = float(foo[c]); c+=1 self.item12 = float(foo[c]); c += 1 self.item13 = float(foo[c]); c += 1 self.item14 = float(foo[c]); c += 1 self.item15 = float(foo[c]); c += 1 self.item16 = float(foo[c]); c+=1 self.item17 = float(foo[c]); c+=1 self.item18 = float(foo[c]); c+=1 self.item19 = int(foo[c]); c+=1 self.item20 = float(foo[c]); c+=1 self.item21 = float(foo[c]); c+=1 self.item22 = int(foo[c]); c+=1 self.item23 = float(foo[c]); c += 1 self.item24 = float(foo[c]); c += 1 self.item25 = float(foo[c]); c+=1 self.item26 = int(foo[c]); c+=1 self.item27 = bool(int(foo[c])); c+=1 self.item28 = float(foo[c]); c+=1 self.item29 = float(foo[c]); c+=1 self.item30 = (foo[c] == "1"); c += 1 self.item31 = (foo[c] == "1"); c += 1 self.item32 = float(foo[c]); c += 1 self.item33 = float(foo[c]); c += 1 self.item34 = int(foo[c]); c += 1 self.item35 = float(foo[c]); c += 1 self.item36 = (foo[c] == "1"); c+=1 self.item37 = (foo[c] == "1"); c+=1 self.item38 = float(foo[c]); c += 1 self.item39 = float(foo[c]); c += 1 self.item40 = int(foo[c]); c += 1 self.item41 = float(foo[c]); c += 1 self.item42 = (foo[c] == "1"); c+=1 self.item43 = float(foo[c]); c+=1 self.item44 = float(foo[c]); c+=1 self.item45 = float(foo[c]); c += 1 self.item46 = int(foo[c]); c+=1 self.item47 = bool(int(foo[c])); c+=1 return c ######################################################################## ### class HugeClass: def __init__(self,line): self.clear() self.input(line) return def __del__(self): del self.B4v return def clear(self): self.long_classes = {} self.B4v={} return def input(self, line): try: foo = line.strip().split(',') c = 0 self.asciiVersion = float(foo[c]) c += 1 self.item0 = foo[c]; c += 1 self.item1 = (self.item0 != "0") self.item2 = (foo[c] == "1"); c += 1 self.item3=int(foo[c]); c+=1 self.item4=int(foo[c]); c+=1 self.item5=int(foo[c]); c+=1 self.item6=int(foo[c]); c += 1 self.item7=float(foo[c]); c+=1 self.item8 = foo[c]; c += 1 bit_item = int(self.item8) self.item9 = bool(bit_item & 2048) self.item10 = bool(bit_item & 1024) self.item11 = bool(bit_item & 512) self.item12 = bool(bit_item & 256) self.item13 = bool(bit_item & 128) self.item14 = bool(bit_item & 64) self.item15 = bool(bit_item & 32) self.item16 = bool(bit_item & 16) self.item17 = bool(bit_item & 8) self.item18 = bool(bit_item & 4) self.item19 = bool(bit_item & 2) self.item20 = bool(bit_item & 1) self.item21 = int(foo[c]); c+=1 self.item22 = float(foo[c]); c+=1 self.item23 = int(foo[c]); c+=1 self.item24 = float(foo[c]); c+=1 self.item25 = float(foo[c]); c+=1 self.item26 = foo[c]; c+=1 self.item27 = int(foo[c]); c+=1 self.item28 = int(foo[c]); c+=1 self.item29 = ModerateClass() c = self.item29.input(foo, c) self.item30 = int(foo[c]); c+=1 self.item31 = int(foo[c]); c+=1 for i in xrange(self.item31): unit = LongClass() c = unit.input(foo, c) self.long_classes[len(self.long_classes)] = unit assert(c == len(foo)), "ERROR We did not read the whole line!!!" except (ValueError,IndexError), msg: print >> sys.stderr, \ "ERROR Trouble reading line: `%(msg)s'" % vars() self.clear() return return ######################################################################## ### def readLines(f): DATA = [] f.seek(0) time_a = time.time() for i in f: DATA.append(i) time_b = time.time() time_spent_reading = time_b - time_a print "DEBUG readLines took %.3f s" % time_spent_reading return DATA ######################################################################## ### def ReadClasses(filename): print 'Now reading ...' built_classes = {} # Read lines from file in_file = open(filename, 'r') LINES = readLines(in_file) in_file.close() # and interpret them. for i in LINES: ## This is alternative 1. built_classes[len(built_classes)] = HugeClass(long_line) ## The next line is alternative 2. ## built_classes[len(built_classes)] = long_line del LINES return ######################################################################## ### def ProcessList(): input_files = ["./test_file0.txt", "./test_file0.txt"] # Loop over all files that we found. nfiles = len(input_files) file_index = 0 for i in input_files: print "--> %i/%i: %s" % (file_index+1, nfiles, i) ReadClasses(i) file_index += 1 return ######################################################################## ### if __name__ == "__main__": ProcessList() sys.exit(0) ######################################################################## ### From mrkafk at gmail.com Sun Sep 30 09:53:14 2007 From: mrkafk at gmail.com (mrkafk at gmail.com) Date: Sun, 30 Sep 2007 06:53:14 -0700 Subject: s.split() on multiple separators Message-ID: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> Hello everyone, OK, so I want to split a string c into words using several different separators from a list (dels). I can do this the following C-like way: >>> c=' abcde abc cba fdsa bcd '.split() >>> dels='ce ' >>> for j in dels: cp=[] for i in xrange(0,len(c)-1): cp.extend(c[i].split(j)) c=cp >>> c ['ab', 'd', '', 'ab', '', ''] But. Surely there is a more Pythonic way to do this? I cannot do this: >>> for i in dels: c=[x.split(i) for x in c] because x.split(i) is a list. From george.sakkis at gmail.com Sun Sep 23 01:34:01 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Sep 2007 05:34:01 -0000 Subject: Factory function with keyword arguments In-Reply-To: <13fbl9ertj5es12@corp.supernews.com> References: <13fbl9ertj5es12@corp.supernews.com> Message-ID: <1190525641.226153.100060@22g2000hsm.googlegroups.com> On Sep 22, 10:53 pm, Steven D'Aprano wrote: > I'm writing a factory function that needs to use keywords in the produced > function, not the factory. Here's a toy example: > > def factory(flag): > def foo(obj, arg): > if flag: > # use the spam keyword to method() > return obj.method(spam=arg) > else: > # use the ham keyword > return obj.method(ham=arg) > return foo > > Problem: the test of which keyword to use is done every time the produced > function is called, instead of once, in the factory. > > I thought of doing this: > > def factory(flag): > if flag: kw = 'spam' > else: kw = 'ham' > def foo(obj, arg): > kwargs = dict([(kw, arg)]) > return obj.method(**kwargs) > return foo > > Is this the best way of doing this? Are there any alternative methods > that aren't risky, slow or obfuscated? Unless I'm missing something, the obvious way is to move the flag check outside the function and have two definitions of foo: def factory(flag): if flag: # use the spam keyword to method() def foo(obj, arg): return obj.method(spam=arg) else: # use the ham keyword def foo(obj, arg): return obj.method(ham=arg) return foo Now if foo is more than a line or two and the only difference the flag makes is the keyword argument, you can either factor the common part out in another function called by foo or (if performance is crucial) create foo dynamically through exec: def factory(flag): kw = flag and 'spam' or 'ham' exec '''def foo(obj, arg): return obj.method(%s=arg)''' % kw return foo George From ricaraoz at gmail.com Sat Sep 1 23:05:21 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 00:05:21 -0300 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1i3rxit.1750ghi14bbcm3N%aleax@mac.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <1i3rxit.1750ghi14bbcm3N%aleax@mac.com> Message-ID: <46DA2871.5030406@bigfoot.com> Alex Martelli wrote: > Ricardo Ar?oz wrote: > ... >> We should remember that the level >> of security of a 'System' is the same as the level of security of it's >> weakest component, > > Not true (not even for security, much less for reliability which is > what's being discussed here). > > It's easy to see how this assertion of yours is totally wrong in many > ways... > > Example 1: a toy system made up of subsystem A (which has a probability > of 90% of working right) whose output feeds into subsystem B (which has > a probability of 80% of working right). A's failures and B's faliures > are statistically independent (no common-mode failures, &c). > > The ``level of goodness'' (probability of working right) of the weakest > component, B, is 80%; but the whole system has a ``level of goodness'' > (probability of working right) of just 72%, since BOTH subsystems must > work right for the whole system to do so. 72 != 80 and thus your > assertion is false. > > More generally: subsystems "in series" with independent failures can > produce a system that's weaker than its weakest component. > > > Example 2: another toy system made up of subsystems A1, A2 and A3, each > trying to transform the same input supplied to all of them into a 1 bit > result; each of these systems works right 80% of the time, statistically > independently (no common-mode failures, &c). The three subsystems' > results are reconciled by a simple majority-voting component M which > emits as the system's result the bit value that's given by two out of > three of the Ai subsystems (or, of course, the value given unanimously > by all) and has extremely high reliability thanks to its utter > simplicity (say 99.9%, high enough that we can ignore M's contribution > to system failures in a first-order analysis). > > The whole system will fail when all Ai fail together (probability > 0.2**3) or when 2 out of them fail while the hird one is working > (probability 3*0.8*0.2**2): > >>>> 0.2**3+3*0.2**2*0.8 > 0.10400000000000004 > > So, the system as a whole has a "level of goodness" (probability of > working right) of almost 90% -- again different from the "weakest > component" (each of the three Ai's), in this case higher. > > More generally: subsystems "in parallel" (arranged so as to be able to > survive the failure of some subset) with indipendent failures can > produce a system that's stronger than its weakest component. > > > Even in the field of security, which (changing the subject...) you > specifically refer to, similar considerations apply. If your assertion > was correct, then removing one component would never WEAKEN a system's > security -- it might increase it if it was the weakest, otherwise it > would leave it intact. And yet, a strong and sound tradition in > security is to require MULTIPLE components to be all satisfied e.g. for > access to secret information: e.g. the one wanting access must prove > their identity (say by retinal scan), possess a physical token (say a > key) AND know a certain secret (say a password). Do you really think > that, e.g., removing the need for the retinal scan would make the > system's security *STRONGER*...? It would clearly weaken it, as a > would-be breaker would now need only to purloin the key and trick the > secret password out of the individual knowing it, without the further > problem of falsifying a retinal scan successfully. Again, such security > systems exist and are traditional exactly because they're STRONGER than > their weakest component! > > > So, the implication accompanying your assertion, that strenghtening a > component that's not the weakest one is useless, is also false. It may > indeed have extremely low returns on investment, depending on system's > structure and exact circumstances, but then again, it may not; nothing > can be inferred about this ROI issue from the consideration in question. > > > Alex You win the argument, and thanks you prove my point. You typically concerned yourself with the technical part of the matter, yet you completely ignored the point I was trying to make. That is that in real world applications formally proving the application is not only an enormous resource waster but it also pays very little if at all. I think most cases will fall under point (1) of your post, and as so many other not formally proven subsystems are at work at the same time there will be hardly any gain in doing it. Point (2) of your post would be my preferred solution, and what is usually done in hardware. In the third part of your post, regarding security, I think you went off the road. The weakest component would not be one of the requisites of access, the weakest component I was referring to would be an actual APPLICATION, e.g. an ftp server. In that case, if you have several applications running your security will be the security of the weakest of them. From mail at timgolden.me.uk Fri Sep 7 10:15:46 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Sep 2007 15:15:46 +0100 Subject: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute In-Reply-To: <1189173455.525144.326300@y42g2000hsy.googlegroups.com> References: <1189173455.525144.326300@y42g2000hsy.googlegroups.com> Message-ID: <46E15D12.2010309@timgolden.me.uk> cjt22 at bath.ac.uk wrote: > Hi there > > I am fairly new to Python and have not really used regular expressions > before (I think this might be needed for my query) and wondered if you > could help > > I have a step class and store in a list step instances > A step instance contains variables: name, startTime etc and startTime > is stored as a string %H:%M:%S > > What I would like to do is to be able to sort this list of objects > based on the startTime object so that the first item in the list is > the object with the earliest Start time and last item is the object > with the last Start time. > > I belive my key has to be = strpTime(step.sTime, "%H:%M:%S") > But don't know how to create the comparison funciton. You're going to get a *lot* of answers on this one! To start the ball rolling... import random class Step: def __init__ (self, name, startTime): self.name = name self.startTime = startTime def __cmp__ (self, other): return cmp (self.startTime, other.startTime) def __str__ (self): return str (self.startTime) __repr__ = __str__ steps = [Step (h, "%02d:00:00" % h) for h in range (10)] random.shuffle (steps) print "Shuffled:", steps steps.sort () print "Sorted:", steps In this case, I've given the class a ordering-semantic based on its startTime attribute. Obviously, this only makes sense if you *always* want your class to sort this way, rather than in this one instance. To do it on a per-sort basis, you *could* create simple per-sort equivalent: def compare_by_startTime (one, other): return cmp (one.startTime, other.startTime) steps.sort (cmp=compare_by_startTime) or, in the case you're asking about, you could use the operator module's attrgetter function to do what you want: import operator steps.sort (key=operator.attrgetter ("startTime")) TJG From zentraders at gmail.com Tue Sep 4 11:38:08 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 04 Sep 2007 08:38:08 -0700 Subject: Tkinter(2) In-Reply-To: <1188913329.457394.94220@g4g2000hsf.googlegroups.com> References: <1188913329.457394.94220@g4g2000hsf.googlegroups.com> Message-ID: <1188920288.143141.321940@y42g2000hsy.googlegroups.com> On Sep 4, 6:42 am, vijayca wrote: > my python installation is:Active python 2.5.1 > i am using Red Hat Linux > i have the Tkinter module installed but any simple script produces an > error.... > > script: > from Tkinter import Label > widget = Label(None, text='Hello GUI world!') > widget.pack() > widget.mainloop() > > error: > Traceback (most recent call last): > File "guy.py", line 2, in > widget = Label(None, text='Hello GUI world!') > File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ > INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 2464, in __init__ > Widget.__init__(self, master, 'label', cnf, kw) > File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ > INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1923, in __init__ > BaseWidget._setup(self, master, cnf) > File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ > INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1898, in _setup > _default_root = Tk() > File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ > INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1636, in __init__ > self.tk = _tkinter.create(screenName, baseName, className, > interactive, wantobjects, useTk, sync, use) > _tkinter.TclError: no display name and no $DISPLAY environment > variable > > please help me.... > i hate those error messages... > vijay See this example http://www.pythonware.com/library/tkinter/introduction/hello-tkinter.htm#AEN50 http://www.python-eggs.org/?row=2 From gary.thrapp at navy.mil Wed Sep 12 17:40:30 2007 From: gary.thrapp at navy.mil (grt) Date: Wed, 12 Sep 2007 14:40:30 -0700 Subject: Search path for python script Message-ID: <1189633230.265179.58780@19g2000hsx.googlegroups.com> I'm new to python, running it under cygwin. This must be easy but I haven't figured it out. I'm trying to run a script by typing: python test.py where test.py is in a directory I've added to PYTHONPATH, but test.py is not found. Perhaps PYTHONPATH only applies to modules imported within a script. I didn't notice an option to python to search the standard path, like Perl -S. How is this done? From python at cx.hu Wed Sep 5 21:08:30 2007 From: python at cx.hu (Ferenczi Viktor) Date: Thu, 6 Sep 2007 03:08:30 +0200 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? In-Reply-To: <87ejhc8z23.fsf@wilson.homeunix.com> References: <46DEFD2E.5050205@sbcglobal.net> <87ejhc8z23.fsf@wilson.homeunix.com> Message-ID: <200709060308.30192.python@cx.hu> > > Properties are very useful, since ordinary attribute access can be > > transparently replaced with properties if the developer needs to > > add code when it's set or needs to calculate it's value whenever > > it is read. > > I totally agree. I like to use properties. However, Python already > has properties. Their syntax is quite nice in my opinion, and > rather explicit, too. Their only flaw is that they are not > "virtual" (in C++ speak). In other words, you can't pass a "self" > parameter to them. Thanks for your comment. I'm going to elaborate on this issue. - Viktor From ptmcg at austin.rr.com Sun Sep 16 11:38:19 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 16 Sep 2007 08:38:19 -0700 Subject: Cannot formulate regex In-Reply-To: References: Message-ID: <1189957099.952690.275320@n39g2000hsh.googlegroups.com> On Sep 16, 10:18 am, "Dotan Cohen" wrote: > I'd like to filter spam from a certain company. Here are examples of > strings found in their spam: > Mega Dik > Mega D1k > MegaDik > Mega. Dik > M eg ad ik > M E _G_A_D_ IK > M_E_G. ADI. K > > I figured that this regex would match all but the second example, yet > it matches none: > |[^a-z]m[^a-z]e[^a-z]g[^a-z]a[^a-z]d[^a-z]i[^a-z]k[^a-z]|i > > What would be the regex that matches "megadik" regardless of whatever > characters are sprinkled throughout? > > Thanks in advance. > > Dotan Or you could try using "MegaRegex"! I do and my girlfriend can't stop talking about it! :) -- Paul From joel.schaerer at gmail.com Thu Sep 27 11:39:13 2007 From: joel.schaerer at gmail.com (Joel) Date: Thu, 27 Sep 2007 08:39:13 -0700 Subject: Cross-platform time out decorator In-Reply-To: <87k5qc18gf.fsf@mulj.homelinux.net> References: <1190802115.585306.250400@o80g2000hse.googlegroups.com> <1190899882.702911.44670@w3g2000hsg.googlegroups.com> <87k5qc18gf.fsf@mulj.homelinux.net> Message-ID: <1190907553.425261.273400@w3g2000hsg.googlegroups.com> On Sep 27, 4:36 pm, Hrvoje Niksic wrote: > Joel writes: > > I found the solution : > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440569 > > describes a solution based on threads. I tested it and it works > > perfectly. > > Note that, unlike the original alarm code, it doesn't really interrupt > the timed-out method, it just returns the control back to the caller, > using an exception to mark that a timeout occurred. The "timed out" > code is still merrily running in the background. I don't know if it's > a problem in your case, but it's an important drawback. There should be a method to stop the thread though? I've never programmed thread stuff in python and wasn't able to find how to do it, would you happen to know how to "kill" the timed out thread? From lorestar at gmail.com Tue Sep 18 17:06:43 2007 From: lorestar at gmail.com (Lorenzo Stella) Date: Tue, 18 Sep 2007 14:06:43 -0700 Subject: can Python be useful as functional? In-Reply-To: <13f00gv3gl3n43d@corp.supernews.com> References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> <13f00gv3gl3n43d@corp.supernews.com> Message-ID: <1190149603.682088.44510@y42g2000hsy.googlegroups.com> On 18 Set, 18:51, Grant Edwards wrote: > Perhaps Lorenzo Stella is referring to Python's lack of > tail-recursion optimization? There are languages that > guarantee unlimited tail-recursion with a limited stack. That's it. Rustom Mody: your implementation lacks exactly where mine does. Try listing the first 2000 primes... That's what I meant: I cannot in general (with Python) get such list just by defining *what* it is, I have to express *how* to get it (describing an algorithm). "What" or "How": that is the question. Steve Holden wrote: > You just don't like the specific limit that Python imposes. So increase > it with sys.setrecursionlimit(). That is obviously not the answer to my question. From exarkun at divmod.com Fri Sep 21 14:23:54 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 21 Sep 2007 14:23:54 -0400 Subject: Parameterize formatting string In-Reply-To: <18c1e6480709211116v1c830409q306605e414102272@mail.gmail.com> Message-ID: <20070921182354.8162.1602536699.divmod.quotient.12381@ohm> On Fri, 21 Sep 2007 20:16:29 +0200, David wrote: >On 9/21/07, cyril giraudon wrote: >> Hello, >> >> I 'd like to know if a std::setw() equivalent function exists in >> python ? >> >> i thought of something like : >> >> a = 16 >> "%ai" % 12 >> >> But it is not correct. >> >> Any Idea ? > >("%i" % 12).rjust(a) > >Or, more ugly: > >"%%%di" % a % 12 > >The first % (after quotes) builds this string: "%16i". >Then the second % operation converts that string to ' 12' > Or '%*i' % (a, 12) Jean-Paul From paul.nospam at rudin.co.uk Tue Sep 25 05:41:58 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Tue, 25 Sep 2007 10:41:58 +0100 Subject: obtaining multiple values from a function. References: <1190708155.683502.93040@r29g2000hsg.googlegroups.com> <87sl53m90t.fsf@benfinney.id.au> Message-ID: <87zlzbrsih.fsf@rudin.co.uk> Ben Finney writes: > > If, instead, it makes sense for the results to be iterated over, you > can write a function that yields results one at a time, without > necessarily knowing in advance what the entire set will be:: > > >>> def fib(max_result): Going off on a tangent a bit, but I was idly considering the absence of itertools.ireduce the other day. A problem is that reduce gives a single result, so it's not clear what ireduce would do (perhaps why it's not there). One obvious candidate would be to give the whole sequence of partial reductions. I'm not sure if this would be generally useful, but it would give a succinct way to do the Fibonacci sequence: itertools.ireduce(operator.add, itertools.count()) From shankarjee at gmail.com Wed Sep 19 12:49:50 2007 From: shankarjee at gmail.com (Shankarjee Krishnamoorthi) Date: Wed, 19 Sep 2007 11:49:50 -0500 Subject: Embedding a executable inside Python Script Message-ID: Hi I have a python routine which calls an executable file created by someone else (I dont have the source code. All I have is an exe file). I do # My Python Code output = os.system('other_executable.exe') # Rest of my program. I need to give this routine to others to use it. I have a exe made with py2exe for my Python routine. The issue I am running into is this. All the exes (mycode.exe and other_executable.exe) are placed in a Network drive(Say I:) so that people can access it. When the user calls this from a Local Drice(Say C:) The output is like this C:> I:\mycode.exe input_file other_executable_file.exe is not found..... Is there any way where I can circumvent this. Thanks Shankarjee From jeroen.hegeman at gmail.com Mon Sep 24 11:50:57 2007 From: jeroen.hegeman at gmail.com (Jeroen Hegeman) Date: Mon, 24 Sep 2007 17:50:57 +0200 Subject: Newbie completely confused In-Reply-To: References: Message-ID: Thanks for the comments, > > (First, I had to add timing code to ReadClasses: the code you posted > doesn't include them, and only shows timings for ReadLines.) > > Your program uses quite a bit of memory. I guess it gets harder and > harder to allocate the required amounts of memory. Well, I guess there could be something in that, but why is there a significant increase after the first time? And after that, single- trip time pretty much flattens out. No more obvious increases. > > If I change this line in ReadClasses: > > built_classes[len(built_classes)] = HugeClass(long_line) > > to > > dummy = HugeClass(long_line) > > then both times the files are read and your data structures are built, > but after each run the data structure is freed. The result is that > both > runs are equally fast. Isnt't the 'del LINES' supposed to achieve the same thing? And really, reading 30MB files should not be such a problem, right? (I'm also running with 1GB of RAM.) > I'm not sure how to speed things up here... you're doing much > processing > on a lot of small chunks of data. I have a number of observations and > possible improvements though, and some might even speed things up a > bit. Cool thanks, let's go over them. > > You read the files, but don't use the contents; instead you use > long_line over and over. I suppose you do that because this is a test, > not your actual code? Yeah ;-) (Do I notice a lack of trust in the responses I get? Should I not mention 'newbie'?) Let's get a couple of things out of the way: - I do know about meaningful variable names and case-conventions, but ... First of all I also have to live with inherited code (I don't like people shouting in their code either), and secondly (all the itemx) most of these members normally _have_ descriptive names but I'm not supposed to copy-paste the original code to any newsgroups. - I also know that a plain 'return' in python does not do anything but I happen to like them. Same holds for the sys.exit() call. - The __init__ methods normally actually do something: they initialise some member variables to meaningful values (by calling the clear() method, actually). - The __clear__ method normally brings objects back into a well- defined 'empty' state. - The __del__ methods are actually needed in this case (well, in the _real_ code anyway). The python code loads a module written in C++ and some of the member variables actually point to C++ objects created dynamically, so one actually has to call their destructors before unbinding the python var. I tried to get things down to as small as possible, but when I found out that the size of the classes seems to contribute to the issue (removing enough member variables will bring you to a point where all of a sudden the speed increases a factor ten, there seems to be some breakpoint depending on the size of the classes) I could not simply remove all members but had to give them funky names. I kept the main structure of things, though, to see if that would solicit comments. (And it did...) > > > In a number of cases, you use a dict like this: > > built_classes = {} > for i in LINES: > built_classes[len(built_classes)] = ... > > So you're using the indices 0, 1, 2, ... as the keys. That's not what > dictionaries are made for; lists are much better for that: > > built_classes = [] > for i in LINES: > built_classes.append(...) Yeah, I inherited that part... > > Your readLines() function reads a whole file into memory. If you're > working with large files, that's not such a good idea. It's better to > load one line at a time into memory and work on that. I would even > completely remove readLines() and restructure ReadClasses() like this: Actually, part of what I removed was the real reason why readLines() is there at all: it reads files in blocks of (at most) some_number lines, and keeps track of the line offset in the file. I kept this structure hoping that someone would point out something obvious like some internal buffer going out of scope or whatever. All right, thanks for the tips. I guess the issue itself is still open, though. Cheers, Jeroen Jeroen Hegeman jeroen DOT hegeman AT gmail DOT com WARNING: This message may contain classified information. Immediately burn this message after reading. From mail at microcorp.co.za Sat Sep 1 04:18:03 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 1 Sep 2007 10:18:03 +0200 Subject: Non-Blocking IO References: <1188614575.647228.248640@k79g2000hse.googlegroups.com> Message-ID: <01f501c7ec71$4cce5a40$03000080@hendrik> "mp" wrote: > Calling try3() yields the error: > File "./test.py", line 54, in try3 > print os.read(fout.fileno(),256) > OSError: [Errno 35] Resource temporarily unavailable This means there is no data available- its actually working! - Hendrik From gagsl-py2 at yahoo.com.ar Mon Sep 17 15:20:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Sep 2007 16:20:19 -0300 Subject: Reading text files where last line has no EOL References: <1190027021.235110.286450@g4g2000hsf.googlegroups.com> <1190030558.568678.77370@y42g2000hsy.googlegroups.com> Message-ID: En Mon, 17 Sep 2007 09:02:38 -0300, BlueBird escribi?: > Oooooooops. It was a stupid bug in my script: textLine[:- > int(textLine[-1]=='\n')] is not what I want (the real code was not a > one-liner)! The documentation made me think that something wrong was > going on with python but I should have known better. If that expression is supposed to remove the trailing newline, I suggest using textLine = textLine.rstrip('\n') -- Gabriel Genellina From lycka at carmen.se Fri Sep 28 04:49:51 2007 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 28 Sep 2007 10:49:51 +0200 Subject: A question on python performance. In-Reply-To: References: Message-ID: Joe Goldthwaite wrote: > I didn't know about the getattr function. I tried to search for that > type of function but not knowing how to word the search request, > I couldn't find it. You should really read through chapter 2 (Built-in Objects) of the library reference. All that stuff is core Python functionality that you should be aware of. Reading chapter 3 (Built-in Types) is also a really good idea. A lot of the rest is good too, but there is really no excuse for not knowing the contents of those chapters. ;) It's just a few pages, and very useful to know. Read them now! From mauro.tiz at gmail.com Wed Sep 26 04:16:02 2007 From: mauro.tiz at gmail.com (mauro) Date: Wed, 26 Sep 2007 01:16:02 -0700 Subject: Python class method as an argument of a function in a C extension Message-ID: <1190794562.037602.317840@22g2000hsm.googlegroups.com> Hi all, I am trying to wrap some C code using SWIG (win32, mingw). I am new to SWIG and to the Python/C API so what I am doing is looking at the examples and trying to fit them to my needs, but I cannot find any complete demo example of a C function taking as an argument a Python function defined by the user. What I am trying to do is to pass a class method as an argument of a function defined in a C extension: # file: runme.py import myCExtensionModule class MyClass: def __init__(self): self.myCounter = 0 self.myVar = 0 def myMethod(self, myArg): self.myCounter += 1 return self.myVar + myArg def runMe(self): myCExtensionModule.aCFunction(self.myMethod, 10) x = MyClass() x.runMe() # end of runme.py Can anybody give me an hint (or some link) on how to define 'aCFunction' and how to call 'self.myMethod' in the C source code? Thank you very much for any kind of help! From steve at holdenweb.com Tue Sep 4 01:56:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Sep 2007 22:56:17 -0700 Subject: So what exactly is a complex number? In-Reply-To: <7xk5r7dm53.fsf@ruckus.brouhaha.com> References: <7xk5r7dm53.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: >> but the reals aren't. Clearly you *can* take the square root of all >> real numbers, since a real number *is* also a complex number with a >> zero imaginary component. They are mathematically equal and equivalent. > > Ehhh, I let it slide before but since the above has been said a few > times I thought I better mention that it's mathematically a bit bogus. > We could say there is an embedding of the real numbers in the complex > numbers (i.e. the set of complex numbers with Im z = 0). But the > usual mathematical definition of the reals (as a set in set theory) is > a different set from the complex numbers, not a subset. Also, for > example, the derivative of a complex valued function means something > considerably stronger than the derivative of a real valued function. > The real valued function > > f(x) = { exp(-1/x**2, if x != 0, > { 0, if x = 0 > > for real x is infinitely differentiable at x=0 and all the derivatives > are 0, which makes it sound like there's a Taylor series that > converges to 0 everywhere in some neighborhood of x=0, which is > obviously wrong since the function itself is nonzero when x!=0. The > discrepancy is because viewed as a complex valued function f(z), f is > not differentiable at z=0 even once. > > It's pretty normal for a real function f to have a first derivative at > x, but no second derivative at x. That can't happen with complex > functions. If f'(z) exists for some z, then f is analytic at z which > means that all of f's derivatives exist at z and there is some > neighborhood of z in which the Taylor series centered at z converges. Much as I'd like to argue with that I can't, dammit :-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From f.guerrieri at gmail.com Wed Sep 5 07:07:56 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Wed, 5 Sep 2007 13:07:56 +0200 Subject: Looping through File Question In-Reply-To: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> References: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> Message-ID: <79b79e730709050407m7b13a19eh72f8638ccfa65e81@mail.gmail.com> On 9/5/07, planetmatt wrote: > > I am a Python beginner. I am trying to loop through a CSV file which > I can do. What I want to change though is for the loop to start at > row 2 in the file thus excluding column headers. > > At present I am using this statement to initiate a loop though the > records: > > for line in f.readlines(): > > How do I start this at row 2? > you can simply call (and maybe throw away) f.readline() a single time before looping. If the lenght of the first line is fixed, you can also use f.seek to start reading from the second row. francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Mon Sep 24 15:57:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Sep 2007 15:57:55 -0400 Subject: SOAPpy Error In-Reply-To: <46F7BEE1.300@gmail.com> References: <46F7867F.3090607@gmail.com> <46F7BEE1.300@gmail.com> Message-ID: linuxprog wrote: > linuxprog a ?crit : [obscure soappy question] [...] >> wha's wrong ? >> >> Thanks >> > still no answer !? Four hours, and the Intarweb hasn't come up with the answer to your question?!?!?!?!?!?!?! I'd ask Al Gore for your money back if I were you ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Sep 13 18:20:55 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 14 Sep 2007 00:20:55 +0200 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <5ksoaoF5am8cU1@mid.individual.net> <1189701793.466307.93210@g4g2000hsf.googlegroups.com> <5ktfjqF5ctrvU2@mid.individual.net> <46e98fd8$0$27757$426a34cc@news.free.fr> Message-ID: <5ktre7F5ig0vU1@mid.individual.net> Bruno Desthuilliers wrote: > Bjoern Schliessmann a ?crit : >> Why don't you make a preprocessor which accepts method >> declarations without "self" and fixes them? > > The problem being that there's no such thing as a "method > declaration" in Python Yep, there are only definitions. I'm sorry. > - only functions being attributes of a class... What, IYHO, is the difference between a method and a function? > (ok, I know, you meant "functions declared within a class > statement"). I think that those functions _are_ special ones since the compiler is able to make "method(instance, a, b)" out of "instance.method(a, b)". So IMHO, "method definition" makes sense. Regards, Bj?rn -- BOFH excuse #144: Too few computrons available. From paul.nospam at rudin.co.uk Fri Sep 7 12:44:12 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 07 Sep 2007 17:44:12 +0100 Subject: Organizing Code - Packages References: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> <46e17143$0$6189$426a74cc@news.free.fr> <1189183088.922537.18290@r34g2000hsd.googlegroups.com> Message-ID: <87r6laa0ir.fsf@rudin.co.uk> xkenneth writes: >> Ah, yes, a couple of things: >> - avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens > > Yes but i find it hard to edit classes easily when I have more than > one class per file. Why? From rrr at ronadam.com Sun Sep 23 04:13:11 2007 From: rrr at ronadam.com (Ron Adam) Date: Sun, 23 Sep 2007 03:13:11 -0500 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <13faa66cb1phre1@corp.supernews.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <13f8unjjeqs5p97@corp.supernews.com> <13faa66cb1phre1@corp.supernews.com> Message-ID: Scott David Daniels wrote: > Ron Adam wrote: >> >> Scott David Daniels wrote: >>> Cristian wrote: >>>> On Sep 21, 3:44 pm, Ron Adam wrote: >>>> >>>>> I think key may be to discuss names and name binding with your friend. >>> Here's an idea: >>> >>> import math >>> >>> def sin_integral(start, finish, dx): ... >>> def cos_integral(start, finish, dx): ... >>> generalize and separate the integration technique from the >>> function it integrates. >> How about this? >> It's based on the apple basic program example in How to Enjoy Calculus. >> Ron >> >> import math >> def integrate(fn, x1, x2, n=100):... >> def fn(x): ... >> print "Area of fn:", integrate(fn, 0, 2) >> print "Area of cos fn:", integrate(math.cos, 1, 2) > > The point was a pedagogic suggestion, i.e. I understood your point. I just found it interesting since I've been trying to extend my math (for use with python) skills in this area. >"Try taking your > friend along this path." I wasn't trying to do a particularly > good job integrating, simply trying to show how you could > motivate first-class functions by showing a "useful" and > "fun" (at least to an engineer) function that cries out > for higher order functions. In my experience engineers > often want a "reason its useful" before engaging with an > idea. I'll bet that after a few such experiences he'll see > how passing around functions and (later) making functions from > from functions is a great tool to have in his toolbox. Once > he sees that, there will be no problem. Yes, I agree. Another useful thing I've found is to store functions in a dictionary and call them (dispatching) based on some data value. Ron From larry.bates at websafe.com Wed Sep 12 13:18:50 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 12 Sep 2007 12:18:50 -0500 Subject: Get the complete command line as-is In-Reply-To: <1189566000.793354.308420@19g2000hsx.googlegroups.com> References: <1189566000.793354.308420@19g2000hsx.googlegroups.com> Message-ID: wangzq wrote: > Hello, > > I'm passing command line parameters to my browser, I need to pass the > complete command line as-is, for example: > > test.py "abc def" xyz > > If I use ' '.join(sys.argv[1:]), then the double quotes around "abc > def" is gone, but I need to pass the complete command line ("abc def" > xyz) to the browser, how can I do this? > > I'm on Windows. > > Thanks. > Question: If you don't want to parse this as a command line, why don't you read it as data via raw input or from some configuration file? something like: python program (pgm.py): cmdline=raw_input("enter your parameters") external file (cmd.txt): "abc def" xyz python pgm.py < cmd.txt -Larry From max at alcyone.com Sat Sep 22 17:17:12 2007 From: max at alcyone.com (Erik Max Francis) Date: Sat, 22 Sep 2007 14:17:12 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190454275.282176.90830@k79g2000hse.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> <1190454275.282176.90830@k79g2000hse.googlegroups.com> Message-ID: Kay Schluehr wrote: > I checked out Io once and I disliked it. I expected Io's prototype OO > being just a more flexible variant of class based OO but Io couples a > prototype very closely to its offspring. When A produces B and A.f is > modified after production of B also B.f is modified. A controls the > state of B during the whole lifetime of B. I think parents shall not > do this, not in real life and also not in programming language > semantics. It sounds like you're talking about some language other than Io, or didn't delve deeply enough into it, since Io makes no such requirements. The attribute and method (not made distinct in Io; they're called "slots") is much the same as with Python; the current instance is checked for the object, then its parents, then _its_ parents, and so on. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis No man quite believes in any other man. -- H.L. Mencken From mail at timgolden.me.uk Thu Sep 13 05:25:38 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 13 Sep 2007 10:25:38 +0100 Subject: Get the complete command line as-is In-Reply-To: References: <1189566000.793354.308420@19g2000hsx.googlegroups.com> <1189647903.978946.38350@r29g2000hsg.googlegroups.com> Message-ID: <46E90212.1080502@timgolden.me.uk> Thomas Heller wrote: > Better would be this code: > > import ctypes > ctypes.windll.kernel32.GetCommandLineA.restype = ctypes.c_char_p > print ctypes.windll.kernel32.GetCommandLineA() Or you could use pywin32: import win32api print win32api.GetCommandLine () TJG From steve at holdenweb.com Wed Sep 5 19:49:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 05 Sep 2007 16:49:33 -0700 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? In-Reply-To: <200709060128.03248.python@cx.hu> References: <46DEFD2E.5050205@sbcglobal.net> <1189024274.627827.285050@o80g2000hse.googlegroups.com> <200709060128.03248.python@cx.hu> Message-ID: Ferenczi Viktor wrote: > Hello, > >>> from property_support import hasProperties, Property >>> >>> @hasProperties >>> class Sphere(object): >>> def setRadius(self, value): >>> ... some setter implementation ... >>> radius=Property(default=1.0, set=setRadius, type=(int, float)) >>> color=Property(default='black', allowNone=True) >>> >>> This is a cleaner syntax if you need automatic default setter/getter >>> implementations with type checking, default values, etc > >> I really distaste this "etc." in your description. In the end you >> promote endless lists of command line parameters to configure every >> possible function. I also doubt that the solution is more clean but >> arbitray instead. > > Py3K does not enforce any particular use of the class decorator function. This > was only an example. > >> My own guess why properties are not promoted with more emphasis is >> that they lead to cargo cult programming i.e. everyone starts to use >> property syntax even when usual attributes are sufficient. So the >> syntax might even be intentionally ugly. > > AFAIK there is no such a thing as "intentionally ugly" in the Python language. > I've never read this sentence before in manuals, tutorials, etc. > Perhaps not, but ... http://mail.python.org/pipermail/python-dev/2005-September/056846.html regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From ldo at geek-central.gen.new_zealand Thu Sep 6 22:52:33 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 07 Sep 2007 14:52:33 +1200 Subject: Checking if elements are empty References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> Message-ID: In message , Chris Mellon wrote: > On 9/5/07, Steve Holden wrote: >> Doran, Harold wrote: > >> > >> > Is there a way to check if the first element of y is null? >> > >> >> len(y[0]) == 0 >> >> would be the obvious way, assuming "null" means "the null string". >> > > Better spelled as > > if y[0]: Not a good idea. From larry.bates at websafe.com Mon Sep 17 10:54:00 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 17 Sep 2007 09:54:00 -0500 Subject: "once" assigment in Python In-Reply-To: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> References: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> Message-ID: <1uSdnaFGwMuICHPbnZ2dnUVZ_tijnZ2d@comcast.com> Lorenzo Di Gregorio wrote: > Hello, > > I've been using Python for some DES simulations because we don't need > full C speed and it's so much faster for writing models. During > coding I find it handy to assign a variable *unless it has been > already assigned*: I've found that this is often referred to as "once" > assigment. > > The best I could come up with in Python is: > > try: > variable > except NameError: > variable = method() > > I wonder if sombody has a solution (trick, whatever ...) which looks > more compact in coding. Something like: > > once(variable, method) > > doesn't work, but it would be perfect. Of course I can preprocess the > Python code but an all-Python solution would be more handy. > > Any suggestions? > > Thx in advance, > Lorenzo > IMHO variables like what you describe are really data not program variables. You might consider putting variables like these in a dictionary and then check to see if the keys exist before assignment: var_dict={} # # See if 'varname' initialized, if not it needs to be # if 'varname' not in var_dict: var_dict[varname]=somevalue -Larry From tjreedy at udel.edu Fri Sep 28 21:55:35 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Sep 2007 21:55:35 -0400 Subject: cute use of lambda References: <1190945901.551940.165240@k79g2000hse.googlegroups.com> Message-ID: "Simon Forman" wrote in message news:1190945901.551940.165240 at k79g2000hse.googlegroups.com... | class FakeQueue(list): | put = list.append | get = lambda self: self.pop(0) Sorry, to me this is a foolish use of lambda as it is exactly the same as def get(self): self.pop(0) except that in the latter, the resulting function object gets a proper internal name instead of '', therefore giving a more informative traceback in case of an exception. tjr From nagle at animats.com Fri Sep 28 11:53:55 2007 From: nagle at animats.com (John Nagle) Date: Fri, 28 Sep 2007 15:53:55 GMT Subject: Python 3.0 migration plans? In-Reply-To: <1i555ag.9ez4uvf4583jN%aleax@mac.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <%q0Li.725$ih1.539@nlpi068.nbdc.sbc.com> <1i555ag.9ez4uvf4583jN%aleax@mac.com> Message-ID: Alex Martelli wrote: > John Nagle wrote: > >> TheFlyingDutchman wrote: >>> It seems that Python 3 is more significant for what it removes than >>> what it adds. >>> >>> What are the additions that people find the most compelling? >> I'd rather see Python 2.5 finished, so it just works. > > And I'd rather see peace on Earth and goodwill among men than _either_ > Python 3 or your cherished "finished" 2.5 -- the comparison and implied > tradeoff make about as much sense as yours. Insofar as Python has an organization, it's not adequately managing extension modules. Each extension module has its own infrastructure, with its own build procedures, its own bug list, and its own maintainers. There's not even an archive. Unlike CPAN, Cheese Shop is just a directory of URLs. Take a look at how Perl does it. Here are the instructions on how to contribute to CPAN: http://www.cpan.org/modules/04pause.html There's a way to get your module into the system, a standardized format, build, and installation procedure, and an archive which is mirrored. There's a common bug reporting system. Modules abandoned by their original developers are not lost, and can be "adopted" by someone else. Python doesn't have any of this. And that's far more of a problem than Python 3.x. John Nagle From robert.kern at gmail.com Thu Sep 20 14:08:00 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 20 Sep 2007 13:08:00 -0500 Subject: distutils, extensions, and missing headers In-Reply-To: <1190297193.864613.13890@i13g2000prf.googlegroups.com> References: <1190268535.052437.226240@v23g2000prn.googlegroups.com> <1190297193.864613.13890@i13g2000prf.googlegroups.com> Message-ID: Gary Jefferson wrote: > On Sep 20, 1:22 am, Robert Kern wrote: >> Use the "headers" keyword to setup() to list the header files you want installed. > > I've tried "headers=['header1.h', 'header2.h']" in setup() as well > as in Extension(), and neither seem to get the files into the bdist or > bdist_rpm tarball. Am I doing it wrong? I can't seem to find any > examples that use this via google. You might need an accurate relative path. I'm assuming that you don't actually keep header1.h and header2.h in the top-level directory next to the setup.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 carsten at uniqsys.com Fri Sep 7 09:07:49 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 07 Sep 2007 09:07:49 -0400 Subject: How to convert None to null value In-Reply-To: References: Message-ID: <1189170469.3367.25.camel@dot.uniqsys.com> On Fri, 2007-09-07 at 11:19 +0200, pradeep kumar wrote: > Hi , > > i am trying to insert records from one table to another table in > postgres sql using the the following code > > posConn.query("insert into > usr(usr_id,usr_name,usr_passwd,grp_cde,usr_type,usr_chk_till_val, \ > > usr_active,usr_daily_auth,usr_lst_login,usr_lst_logout,usr_shift_id,usr_role_level) values \ > ('%s','%s','%s',%s,%i,%d,'%s',%i,%i,%i,%i,%i)" > %(row[0],row[1],row[2],row[3],row[4],row[5], \ > row[7],row[8],row[10],row[11],row[12],row[14]) ) > > here row[4] column is having null value so python consides it as None > but will insert into the table it inserts as None not null value > > please help how to convert None to null value If you were using a DB-API compliant module, you should use parameter binding instead of building query strings by hand: http://informixdb.blogspot.com/2007/07/filling-in-blanks.html However, nothing in DB-API has a .query method, so either you're using a module that's not conforming to DB-API, or you're using some kind of wrapper around a DB-API module. In any case, you should try to find out how to do parameter binding with whatever it is you're using. If it doesn't have a parameter binding mechanism, you should throw it away and replace it with a DB-API complaint module. HTH, -- Carsten Haese http://informixdb.sourceforge.net From aleax at mac.com Sun Sep 2 14:46:50 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 2 Sep 2007 11:46:50 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188742231.470668.29910@g4g2000hsf.googlegroups.com> <1i3t4ha.1r0xx7414w0taxN%aleax@mac.com> <1188754943.512850.158320@y42g2000hsy.googlegroups.com> Message-ID: <1i3t9p0.16643k010dbwtnN%aleax@mac.com> Mark Dickinson wrote: > On Sep 2, 12:55 pm, al... at mac.com (Alex Martelli) wrote: > > Mark Dickinson wrote: > > > Well, for one thing, you're creating half a million xrange objects in > > > the course of the search. All the C code has > > > to do is increment a few integers. > > > > I don't think the creation of xrange objects is a meaningful part of > > Python's execution time here. Consider: > > [...] > > Agreed---I just came to the same conclusion after doing some tests. > So maybe it's the billion or so integer objects being created that > dominate the running time? (Not sure how many integer objects > actually are created here: doesn't Python cache *some* small > integers?) Yep, some, say -5 to 100 or thereabouts; it also caches on a free-list all the "empty" integer-objects it ever has (rather than returning the memory for the system), so I don't think there's much optimization to be had on that score either. Alex From pydecker at gmail.com Wed Sep 12 21:42:06 2007 From: pydecker at gmail.com (Peter Decker) Date: Wed, 12 Sep 2007 21:42:06 -0400 Subject: Python 3K or Python 2.9? In-Reply-To: <87sl5j5r34.fsf@benfinney.id.au> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> Message-ID: On 9/12/07, Ben Finney wrote: > TheFlyingDutchman writes: > > > I am talking about how an author describes in English the "this" > > pointer/reference in their book on programming C++ or Java. > > > > I don't think you will find them saying that under the covers "this" > > was passed to the method (if in fact it is). They just say that it > > refers to the current object inside that object's method. > > In other words, it's magic, and the behaviour has to be explained so > the reader knows where the undeclared 'this' comes from. > > How is that preferable to the magic of "instance is passed as the > first argument to a method"? So everything that isn't passed explicitly is "magic"? I suppose __builtin__ counts as magic, too? Define 'self' as a keyword, and its usage becomes no more magical than 'def' or 'break'. -- # p.d. From bjorn.kempen at gmail.com Sun Sep 16 06:02:59 2007 From: bjorn.kempen at gmail.com (buffi) Date: Sun, 16 Sep 2007 10:02:59 -0000 Subject: generate list of partially accumulated values In-Reply-To: <1189936564.932553.148800@50g2000hsm.googlegroups.com> References: <1189936564.932553.148800@50g2000hsm.googlegroups.com> Message-ID: <1189936979.276166.103080@w3g2000hsg.googlegroups.com> On Sep 16, 11:56 am, cesco wrote: > Hi, > > I have the following list: > l = [1, 2, 3, 4] > and I'd like to obtain a list like the following: > l_partial_sum = [1, 3, 6, 10] (that is [1, 1+2, 1+2+3, 1+2+3+4]) > > Is there a simple way to accomplish this? > > I came up with the following solution but it seems a bit too > elaborated for the task: > l_partial_sum = [reduce(lambda x,y:x+y, sub_l) for sub_l in [l[:i+1] > for i in range(len(l))]] > > Any help will be appreciated. > > Thanks > Francesco >>> l = [1, 2, 3, 4] >>> [sum(l[:x+1]) for x in xrange(len(l))] [1, 3, 6, 10] - Bj?rn Kemp?n From duncan.booth at invalid.invalid Thu Sep 27 13:06:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Sep 2007 17:06:30 GMT Subject: True of False References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> <5m254hFatlbuU2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > In [268]: 'c' in a == True > Out[268]: False > > In [269]: ('c' in a) == True > Out[269]: True > > In [270]: 'c' in (a == True) > ----------------------------------------------------------------------- > ---- > Traceback (most recent call >last) > > /home/bj/ in () > >: argument of type 'bool' is not iterable > > > What's going on there? See http://docs.python.org/ref/comparisons.html > Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent > to x < y and y <= z, except that y is evaluated only once (but in both > cases z is not evaluated at all when x < y is found to be false). In exactly the same way: 'c' in a == True is equivalent to: 'c' in a and a == True which is False. From hniksic at xemacs.org Tue Sep 18 11:41:46 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 18 Sep 2007 17:41:46 +0200 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> Message-ID: <87abrkhtfp.fsf@mulj.homelinux.net> Bruno Desthuilliers writes: > If a class X is in the MRO of call Y, then X is a superclass of Y. I > agree that the documentation for super is somewhat misleading (and > obviously wrong), but it still *give access to* (at least one of) > the superclass(es). I believe the confusion comes from different assumptions about what "superclasses" refers to. super() iterates over superclasses of the *instance* in use, but an individual call to super does not necessarily invoke the superclass of the *implementation* of the method. For example, given a random class: class X(Y): def foo(self): super(X, self).foo() ...there is in fact no guarantee that super() calls a superclass of X. However, it is certainly guaranteed that it will call a superclass of type(self). Pre-2.2 Python used a simpler scheme where the superclass was always called, but it caused problems with diamond inheritance where some methods would be called either twice or not at all. (This is explained in http://www.python.org/download/releases/2.2.3/descrintro/ in some detail.) From vriolk at gmail.com Mon Sep 24 12:19:08 2007 From: vriolk at gmail.com (coldpizza) Date: Mon, 24 Sep 2007 09:19:08 -0700 Subject: database persistence with mysql, sqlite In-Reply-To: References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> Message-ID: <1190650748.590245.221490@n39g2000hsh.googlegroups.com> On Sep 24, 7:23 am, Lawrence D'Oliveiro wrote: > In message <1190502677.970811.181... at 22g2000hsm.googlegroups.com>, coldpizza > wrote: > > > So far, with mysql I use 'SELECT * FROM TABLE LIMIT L1, L2' where L1 > > and L2 define the range for the 'Next' and 'Previous' commands. I > > have to run the query every time a click a 'Next/Prev' link. But I am > > not sure that this is the best and most efficient way. > Try it first, then see what happens. Remember, premature optimization is the > root of all (programming) evil. It turned out that the method above ('SELECT * FROM TABLE LIMIT L1, L2') works ok both with mysql and sqlite3, therefore I have decided to stick with it until I find something better. With Sqlite3 you are supposed to use LIMIT 10 OFFSET NN, but it also apparently supports the mysql syntax (LIMIT NN, 10) for compatibility reasons. From python at hope.cz Sat Sep 29 16:03:14 2007 From: python at hope.cz (Johny) Date: Sat, 29 Sep 2007 13:03:14 -0700 Subject: How to unload a module after I've imported it. Message-ID: <1191096194.002683.16240@50g2000hsm.googlegroups.com> Is it possible to unload a module after I've imported it. I have the main program from which I import several smaller programs. Some of these uses timeoutsocket module. But one of the smaller program can not work with the timeoutsocket module, so I must unload the timeoutsocket module, execute the program and then reload timeoutsocket module. So, s it possible to unload a module after I've imported it.. Thanks L. From ematus at gmail.com Fri Sep 21 22:41:18 2007 From: ematus at gmail.com (Eduardo Matus) Date: Fri, 21 Sep 2007 22:41:18 -0400 Subject: Gobject Message-ID: <984ad6a0709211941g5bcffc7te9aa35bdef7eac83@mail.gmail.com> hi all... I'm trying to get a event when a pipe of a process is no longer receiving data, in this case a EOF... the process start with no problems... but... the gobject_io_add_watch does not trigger the test method when the file in mplayer has finish... any ideas?? Thks :) the codes is this (the relevant part): import gobject, sys,os def play(self,opciones ,target): mpc = "mplayer -slave -quiet \"" + target + "\" 2>/dev/null" self.pin, self.pout = os.popen2(mpc) #open pipe self.startEofHandler() def startEofHandler(self): self.eofHandler = gobject.io_add_watch(self.pout, gobject.IO_HUP, self.test) def test(self,source,condition): print 'Something happend!!' print source -------------- next part -------------- An HTML attachment was scrubbed... URL: From pistacchio at gmail.com Fri Sep 7 04:07:03 2007 From: pistacchio at gmail.com (gu) Date: Fri, 07 Sep 2007 10:07:03 +0200 Subject: unexpected behavior: did i create a pointer? Message-ID: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> hi to all! after two days debugging my code, i've come to the point that the problem was caused by an unexpected behaviour of python. or by lack of some information about the program, of course! i've stripped down the code to reproduce the problem: a = {} for x in range(10): for y in range(10): a[x,y] = "0" copyOfA = a def functionA(x,y): print a[x,y], copyOfA[x,y] = "*" print a[x,y],copyOfA[x,y] for x in range(10): for y in range(10): functionA(x,y) now, in the second "for" cycle and in functionA() i only 'touch' copyOfA (altering it). as i don't touch the variable "a", i expect it not to be affected by any change, but copyOfA acts like a pointer to a and altering copyOfA's values result in altering the values of "a", so the result that i expect is: 0 0 * 0 0 * 0 0 * 0 0 * [..] but i get: 0 * * 0 * * 0 * * 0 * * [..] what's going on? thanks in advance. From info at egenix.com Wed Sep 12 11:23:19 2007 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Wed, 12 Sep 2007 17:23:19 +0200 Subject: ANN: eGenix mxODBC and mxODBC Zope DA on 64-bit FreeBSD Message-ID: <46E80467.2030100@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC Database Interface eGenix.com mxODBC Zope Database Adapter for 64-bit FreeBSD This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-on-FreeBSD-amd64-GA.html ________________________________________________________________________ eGenix mxODBC Distribution The eGenix mxODBC Distribution is a Python database interface add-on distribution for our eGenix mx Base Distribution. It comes with mxODBC, our universal ODBC database interface for Python. Customers who have purchased licenses for other platforms and wish to move their installation to FreeBSD 64-bit, can do so without having to buy a new license. The licenses will continue to work on the 64-bit platform. Users of mxODBC 2.0 will have to purchase new licenses from our online shop in order to upgrade to mxODBC 3.0. You can request 30-day evaluation licenses on the product page. Downloads --------- Please visit the eGenix mxODBC Distribution page for downloads, instructions on installation and documentation of the packages. http://www.egenix.com/products/python/mxODBC/ Note that in order to use the eGenix mxODBC Distribution you need to install the eGenix mx Base Distribution first. ________________________________________________________________________ eGenix mxODBC Zope DA eGenix mxODBC Zope DA is our database interface for Zope and Plone. It is based on the mxODBC interface. Customers who have purchased licenses for other platforms and wish to move their installation to FreeBSD 64-bit, can do so without having to buy a new license. The licenses will continue to work on the 64-bit platform. You can request 30-day evaluation licenses on the product page. Downloads --------- Please visit the eGenix mxODBC Zope DA product page for downloads, instructions on installation and documentation of the packages. http://www.egenix.com/products/zope/mxODBCZopeDA/ ________________________________________________________________________ More Information For more information on our products, licensing and download instructions, please write to sales at egenix.com. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 12 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2007-08-22: Released mxODBC 3.0.1 http://python.egenix.com/ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From kar1107 at gmail.com Tue Sep 4 19:05:38 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 04 Sep 2007 23:05:38 -0000 Subject: how can I find out the process ids with a process name In-Reply-To: <1188761187.522146.192380@y42g2000hsy.googlegroups.com> References: <1188761187.522146.192380@y42g2000hsy.googlegroups.com> Message-ID: <1188947138.904266.256440@r34g2000hsd.googlegroups.com> On Sep 2, 12:26 pm, herman wrote: > Hi, > > I would like to find out all the process id with the process name > 'emacs'. > > In the shell, i can do this: > > $ ps -ef |grep emacs > root 20731 8690 0 12:37 pts/2 00:00:09 emacs-snapshot-gtk > root 25649 25357 0 13:55 pts/9 00:00:05 emacs-snapshot-gtk rtp.c > root 26319 23926 0 14:06 pts/7 00:00:04 emacs-snapshot-gtk > stressTestVideo.py > root 26985 1 0 14:15 ? 00:00:01 /usr/bin/emacs-snapshot- > gtk > root 27472 21066 0 14:23 pts/5 00:00:00 grep emacs > > and I can see the process id is 20731, 25649, etc, etc. > > But now I would like to do the programmically in my python script. > I know I can use ' os.system(cmd)' to execute the command 'ps -ef | > grep emacs', but how > can I pipe the output of my 'ps -ef | grep emacs' to my python script > and then run a regression expression with it to get the process Ids? > Try commands module; it's simple to just get the output. subprocess module is a newer way to doing things. But commands.getoutput() is lot simpler for simple shell like tasks. >>> import commands >>> commands.getoutput("ps -ef | grep emacs | awk '{print $2}'") '21739\n15937\n15287\n5097\n14797\n31777\n8779\n2973\n5413\n13024\n13026' >>> Your script can then use the output as its input. Karthik > Thank you. From charles.fox at gmail.com Wed Sep 12 10:43:51 2007 From: charles.fox at gmail.com (Charles Fox) Date: Wed, 12 Sep 2007 07:43:51 -0700 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <46e7f450$0$12305$426a74cc@news.free.fr> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> Message-ID: <1189608231.151112.147550@y42g2000hsy.googlegroups.com> Thanks guys -- yeah these two stategies (short s.varname; and explicit rescoping, a=self.a etc) are more or less what I was using. That's still kind of annoying though. The s.varname approach still makes numerical code much harder to read. I had a nasty bug with the boilerplate approach when forgetting to reassign some of the variables back to members (self.a=a). And that's a lot of boilerplate you need -- I thought the python way was to minimize redundant code? (Ditching header files and curley brackets was a main reason for me coming here). I see the argument for making self explicit -- what would be wrong with just .a instead of self.a though? That's still explicit but much easier to read. (I think I've seen that somewhere else, is it C#?) From xkenneth at gmail.com Fri Sep 7 11:06:36 2007 From: xkenneth at gmail.com (xkenneth) Date: Fri, 07 Sep 2007 15:06:36 -0000 Subject: Organizing Code - Packages Message-ID: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> All, I apologize if this is a commonly asked question, but I didn't find anything that answered my question while searching. So what I have right now is a few packages that contain some commonly used functions and another package that contains all of my custom error classes. I want these error classes available to me in all of the other packages in my library. Currently to achieve this at the top of every module file I have the line "from My.Library.Errors import *", my problem with this is that it manages to import the Errors into every scope that they are used. I'm still pretty new to Python, and my approachs are probably very rooted in C/C++ (I've had the hardest time getting over not being able to overload functions), but am I doing this correctly? Also, are there any good tutorials/examples out there of how to organize your python code into packges? Thanks for all the help! Regards, Ken From zzbbaadd at aol.com Fri Sep 21 00:22:23 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 20 Sep 2007 21:22:23 -0700 Subject: newb: BeautifulSoup In-Reply-To: <1190343890.375836.78630@r29g2000hsg.googlegroups.com> References: <1190343890.375836.78630@r29g2000hsg.googlegroups.com> Message-ID: <1190348543.472684.243840@50g2000hsm.googlegroups.com> On Sep 20, 8:04 pm, crybaby wrote: > I need to traverse a html page with big table that has many row and > columns. For example, how to go 35th td tag and do regex to retireve > the content. After that is done, you move down to 15th td tag from > 35th tag (35+15) and do regex to retrieve the content? Make the file an xhtml file (valid xml) if it isn't already and then you can use software written to process XML files: http://pyxml.sourceforge.net/topics/ From garyjefferson123 at yahoo.com Fri Sep 21 00:43:54 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: Fri, 21 Sep 2007 04:43:54 -0000 Subject: calling extension's autoconf/make from distutils Message-ID: <1190349834.894931.128050@q3g2000prf.googlegroups.com> I've got a python extension that comes with its own standard autoconf/ automake system, and I can "python setup.py build" just fine with it as long as I have previously done "./configure" in that directory. However, 'python setup.py bdist_rpm' can't hope to have done './ configure' first, as it untars and tries to build the extension there. Is there a hook for bdist_rpm (and friends) that will allow me to insert a './configure' in the build process, sometime before it tries to build the extension? Thanks, Gary From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 7 03:49:29 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 07 Sep 2007 09:49:29 +0200 Subject: startswith( prefix[, start[, end]]) Query In-Reply-To: References: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> <46e00d7e$0$16413$426a74cc@news.free.fr> <1189145398.081080.59580@r34g2000hsd.googlegroups.com> Message-ID: <46e10284$0$439$426a34cc@news.free.fr> Steve Holden a ?crit : > TheFlyingDutchman wrote: >>> Else, you could as well write your own testing function: >>> >>> def str_starts_with(astring, *prefixes): >>> startswith = astring.startswith >>> for prefix in prefixes: >>> if startswith(prefix): >>> return true >>> return false >>> >> >> What is the reason for >> startswith = astring.startswith >> startswith(prefix) >> >> instead of >> astring.startswith(prefix) >> > It's an optimization: the assigment creates a "bound method" (i.e. a > method associated with a specific string instance) and avoids having to > look up the startswith method of astring for each iteration of the inner > loop. > > Probably not really necessary, though, and they do say that premature > optimization is the root of all evil ... I wouldn't call this one "premature" optimization, since it doesn't change the algorithm, doesn't introduce (much) complication, and is proven to really save on lookup time. Now I do agree that unless you have quite a lot of prefixes to test, it might not be that necessary in this particular case... From travelingwebs1 at gmail.com Wed Sep 26 13:59:06 2007 From: travelingwebs1 at gmail.com (travelingwebs1 at gmail.com) Date: Wed, 26 Sep 2007 17:59:06 -0000 Subject: Travel USA Message-ID: <1190829546.266446.246520@g4g2000hsf.googlegroups.com> http://world-traveling-destinations.blogspot.com/ From BjornSteinarFjeldPettersen at gmail.com Thu Sep 20 04:01:56 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Thu, 20 Sep 2007 08:01:56 -0000 Subject: Sets in Python In-Reply-To: <1190274620.912027.322880@50g2000hsm.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <13f3m15igkstq2e@corp.supernews.com> <1190260923.243865.312190@z24g2000prh.googlegroups.com> <1190274620.912027.322880@50g2000hsm.googlegroups.com> Message-ID: <1190275316.223732.191340@22g2000hsm.googlegroups.com> On Sep 20, 9:50 am, thebjorn wrote: it's bad form to reply to myself, I know, but > def __iter__(self): > for k in super(mdict,self).__iter__(): > yield eval(k) should probably be def __iter__(self): return (eval(k) for k in super(mdict,self).__iter__()) I'm still getting used to the power of generator expressions :-) -- bjorn From robert.kern at gmail.com Sat Sep 22 03:03:47 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 22 Sep 2007 02:03:47 -0500 Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <46f49740$0$32514$4c368faf@roadrunner.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> Message-ID: Carl Banks wrote: > Anyone with me here? (I know the deadline for P3 PEPs has passed; this > is just talk.) I'm not. :-) We use them in numpy. The bitwise operations on int and float arrays aren't all that useful, but they are very useful for bool arrays. We can't use the "and"/"or"/"not" keywords since they can't be overloaded, but they bitwise operators fill the need fairly well. We've had logical_and()/logical_or()/logical_not() functions since forever, too, and they're a pain in the ass. -- 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 bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 18 12:31:39 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 18:31:39 +0200 Subject: Using pseudonyms (was Re: Python 3K or Python 2.9?) In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46ef893c$0$21882$426a34cc@news.free.fr> Message-ID: <46effd63$0$16044$426a74cc@news.free.fr> Aahz a ?crit : > In article , > Steve Holden wrote: >> Aahz wrote: >>> In article <46ef893c$0$21882$426a34cc at news.free.fr>, >>> Bruno Desthuilliers wrote: >>>> Aahz a ?crit : >>>>> In article <46ee2d9d$0$26213$426a74cc at news.free.fr>, >>>>> Bruno Desthuilliers wrote: >>>>>> But what, given that I'm an AOL user still thinking it's kewl to hide >>>>>> behind a pseudo, what else would you expect ? >>>>> What exactly is a "pseudo", pray tell? >>>> Sorry : a pseudonym (a nickname). >>> You apparently missed the thrust of my sarcasm. You can't tell what is >>> or is not a pseudonym online. For all I know, "Bruno Desthulliers" is a >>> pseudonym. While I recognize that there is some social advantage to >>> linking consistent identifiers with people, I have I think understandable >>> irritation with people who insist that names follow certain patterns. >>> >>> (For those joining only recently, my full legal name is "Aahz", which I >>> changed from my former name precisely because of attitudes like Bruno's.) For the record, I usually don't give a damn about what name/nickname/whatever peoples use. >> ... coupled with a certain bloody-mindedness that forces you to rub >> people's noses in your ability to choose to do so? ;-) > > While there's certainly some truth to that, it is also the case that I > have seen people like Bruno take exception to some people's born names. > After all, there are people whose parents chose to name them "Moon Unit". But then adding the lastname (ie 'Zappa') could clear the possible confusion !-) From r-w at iinet.net.au Mon Sep 17 06:52:14 2007 From: r-w at iinet.net.au (Ross Wilson) Date: Mon, 17 Sep 2007 20:52:14 +1000 Subject: generating list of sub lists In-Reply-To: <1189931217.415065.102820@w3g2000hsg.googlegroups.com> References: <1189931217.415065.102820@w3g2000hsg.googlegroups.com> Message-ID: <46ee5c5e$0$32487$5a62ac22@per-qv1-newsreader-01.iinet.net.au> cesco wrote: > Hi, > > is there a one-liner to accomplish the following task? >>From the list > l = ['string1', 'string2', 'string3'] > generate the list of lists > l = [['string1'], ['string1', 'string2'], ['string1', 'string2', > 'string3']] > > Any help would be appreciated. > > Thanks > Francesco > l = [l, l] Ross From Shawn at Milochik.com Wed Sep 19 13:13:24 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 19 Sep 2007 13:13:24 -0400 Subject: [Tutor] Finding prime numbers In-Reply-To: <1190219929.7991.28.camel@apprentice-laptop> References: <1190218927.7991.25.camel@apprentice-laptop> <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> <1190219929.7991.28.camel@apprentice-laptop> Message-ID: <2dc0c81b0709191013k181d1a74m76a08cecadb005c4@mail.gmail.com> Here's my attempt: #!/usr/bin/env python import math for x in range(3,1000,2): isPrime = True for y in range(3,(math.sqrt(x) + 1)): if x % y == 0: isPrime = False break if isPrime: print "%d is prime." % x Notes: This doesn't bother with even numbers at all, and uses the square root function of "math." Any improvements anyone? From idzwan.nizam at gmail.com Wed Sep 12 09:47:58 2007 From: idzwan.nizam at gmail.com (idzwan.nizam at gmail.com) Date: Wed, 12 Sep 2007 06:47:58 -0700 Subject: library to launch program in linux In-Reply-To: <13e0itfgm0ida1c@corp.supernews.com> References: <1189103678.484278.321650@r34g2000hsd.googlegroups.com> <13e0itfgm0ida1c@corp.supernews.com> Message-ID: <1189604878.304602.104410@k79g2000hse.googlegroups.com> On Sep 7, 2:49 am, Grant Edwards wrote: > On 2007-09-06, idzwan.ni... at gmail.com wrote: > > > I'm a new user. What library should I use so that I canlaunch > >programin linux using python? Thank you in advance. > > subprocess > > -- > Grant Edwards grante Yow! Hello, GORRY-O!! > at I'm a GENIUS from HARVARD!! > visi.com can you please show me the sample code using subprocess library. I would like user to have few option, program they could run. say, firefox and x chat. thank you From s.mientki at id.umcn.nl Tue Sep 25 06:37:37 2007 From: s.mientki at id.umcn.nl (stef) Date: Tue, 25 Sep 2007 12:37:37 +0200 Subject: ANN: PyPE 2.8.7 In-Reply-To: References: Message-ID: Josiah Carlson wrote: > === What is PyPE? === > PyPE (Python Programmers' Editor) was written in order to offer a > lightweight but powerful editor for those who think emacs is too much > and idle is too little. Syntax highlighting is included out of the box, > as is multiple open documents via tabs. > > sounds very good, so now I want to try it ... ... the windows ansi zip file is corrupted :-( ... the unicode version crashes :-( This is what the log file tells: Traceback (most recent call last): File "pype.py", line 110, in ? File "zipextimporter.pyc", line 78, in load_module File "configuration.pyc", line 149, in ? Exception: Unable to create config directory: 'G:\\.pype' I don't have a G-drive ;-) cheers, Stef Mientki From zzbbaadd at aol.com Tue Sep 11 07:20:10 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 11 Sep 2007 04:20:10 -0700 Subject: cpython list __str__ method for floats In-Reply-To: <13ectngf3aeqrb0@corp.supernews.com> References: <13ectngf3aeqrb0@corp.supernews.com> Message-ID: <1189509610.649272.44040@g4g2000hsf.googlegroups.com> On Sep 11, 4:07 am, "[david]" wrote: > returns poorly formatted values: > > >>>str(13.3) > '13.3' > >>>str([13.3]) > '[13.300000000000001]' > > [david] There is some difference in the way repr() and str() convert floats to strings: >>> a = 13.3 >>> print str(a) 13.3 >>> print repr(a) 13.300000000000001 >>> a 13.300000000000001 >>> a.__str__() '13.3' >>> a.__repr__() '13.300000000000001' >>> From Summercoolness at gmail.com Sat Sep 15 08:36:02 2007 From: Summercoolness at gmail.com (Summercool) Date: Sat, 15 Sep 2007 12:36:02 -0000 Subject: how to join array of integers? Message-ID: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> i think in Ruby, if you have an array (or list) of integers foo = [1, 2, 3] you can use foo.join(",") to join them into a string "1,2,3" in Python... is the method to use ",".join() ? but then it must take a list of strings... not integers... any fast method? From korovev76 at gmail.com Thu Sep 20 06:16:18 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Thu, 20 Sep 2007 03:16:18 -0700 Subject: I MEANT ONIX.... [it was Re: ONYX] In-Reply-To: <1190282489.824709.29050@r29g2000hsg.googlegroups.com> References: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> <46f1726f$0$15276$426a74cc@news.free.fr> <1190282489.824709.29050@r29g2000hsg.googlegroups.com> Message-ID: <1190283378.175422.73290@r29g2000hsg.googlegroups.com> i'm such a lame... i meant onix... not onyx... http://xml.coverpages.org/onix.html the questions remain the same ones... thanx On 20 Set, 12:01, korove... at gmail.com wrote: > On 19 Set, 21:02, Bruno Desthuilliers > > wrote: > > > I don't know what's "onyx-style" xml, > > i'm not used to xml, so for meonyxis just a mess...http://www.onyx.com/Products/xml.asp > > > but if it's xml, any xml parser > > will parse it, and any validating parser should be able to validate it > > given the correct DTD. > > For example?where do I find a good validating parser? > > thanx again From bryanjugglercryptographer at yahoo.com Mon Sep 17 16:29:27 2007 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Mon, 17 Sep 2007 13:29:27 -0700 Subject: Saving parameters between Python applications? In-Reply-To: References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> Message-ID: <1190060967.696332.113190@n39g2000hsh.googlegroups.com> On Sep 17, 6:39 am, Laurent Pointal > May use simple file in known place: > $HOME/.myprefs > $HOME/.conf/myprefs > > Or host specific configuration API: > WindowsRegistry HKEY_CURRENT_USER\Software\MySociety\MyApp\myprefs > > See os.getenv, and _winreg Windows specific module. > See also standard ConfigParser module Also, os.path offers expanduser(). The following is reasonably portable: import os user_home_dir = os.path.expanduser("~") -- --Bryan From jstroud at mbi.ucla.edu Sun Sep 16 21:04:58 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 16 Sep 2007 18:04:58 -0700 Subject: adding a static class to another class In-Reply-To: References: Message-ID: Nathan Harmston wrote: > HI, > > I m trying to start an api in a similar way to the djangic way of > Class.objects.all(). Ie objects is a "Manager" class. > > So: > > class Foo(object): > def __init__(self): > self.test = "NEE" > > class Manager(object): > def __init__(self): > pass > def all(self): > return "COCONUTS" > > Because of how some of the code is set up I cant use > metaclasses........so I try to use a decorator: > > def addto(instance): > def decorator(f): > import new > f = new.instancemethod(f, instance, instance.__class__) > setattr(instance, "objects", f) > return f > return decorator > > class Manager(object): > @addto(Foo) > def __init__(self): > ............. > > however this only binds the init method to the Foo.objects, so not > what I want. If I try using classmethod...then it just says the > Foo.objects doesnt exist. > > Does anyone have any ideas how I can accomplish this using decorators? > And also preventing more than one Manager instance instantiated at one > time. > > Many Thanks in advance, > > Nathan What you are trying to do is a little obscure to me, but I think you want want to rebind Foo.objects to a new manager every time you instantiate a Manager? This will do it: class Foo(object): def __init__(self): self.test = "NEE" class Manager(object): def __init__(self): pass def all(self): return "COCONUTS" def addto(cls): def decorator(f): def _f(self, *args, **kwargs): cls.objects = self f(self, *args, **kwargs) return _f return decorator class Manager(object): @addto(Foo) def __init__(self): pass Example: py> class Foo(object): ... def __init__(self): ... self.test = "NEE" ... py> class Manager(object): ... def __init__(self): ... pass ... def all(self): ... return "COCONUTS" ... py> def addto(cls): ... def decorator(f): ... def _f(self, *args, **kwargs): ... cls.objects = self ... f(self, *args, **kwargs) ... return _f ... return decorator ... py> class Manager(object): ... @addto(Foo) ... def __init__(self): ... pass ... py> hasattr(Foo, 'objects') False py> m = Manager() py> print m <__main__.Manager object at 0x121b870> py> print Foo.objects <__main__.Manager object at 0x121b870> py> n = Manager() py> print n <__main__.Manager object at 0x121b250> py> print Foo.objects <__main__.Manager object at 0x121b250> If you just want the class Foo to have the class Manager as its objects, just do this: Foo.objects = Manager But I don't think that's what you want. I'm not familiar with django, so if I haven't hit it, please elaborate. James From bdesth.quelquechose at free.quelquepart.fr Thu Sep 13 15:39:34 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 13 Sep 2007 21:39:34 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <46e98e01$0$30383$9b4e6d93@newsspool4.arcor-online.net> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> <5ktfb5F5ctrvU1@mid.individual.net> <46e98e01$0$30383$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <46e9921e$0$26251$426a74cc@news.free.fr> Wildemar Wildenburger a ?crit : > Bjoern Schliessmann wrote: > >>> No, but the point being made is that it would be better IN >>> THIS CASE. >> >> >> It wouldn't. IMHO, rewriting the code to two or three lines would be >> better. >> > > Well I think Charles' Point about making the equations look like the > ones in the paper(s) is a pretty good one. That is a special case in > that the code becomes clearer when it conformes to the standards of the > domain it is referring to; it is not meant to be understood by itself > but rather in conjunction with documents that motivate it. > > Or in short: Breaking it into n>1 lines would make it more readable but > would break the connection with the form given in the papers. (Yes, of > course you can refer to the eq. in a comment but believe me: if you're > used to seeing a certain (form of) equation, your mind will trip over > any variation. That is best avoided.) OTHO, simple math-illeterate programmers like me will have hard time maintaining such a code. Also and FWIW, it's not always possible to make a direct translation of a mathematic formula|algorithm in Python, and even when it is, it's not always the best thing to do wrt/ perfs (I recently had such a case, and after a pythonic rewrite the code was about 75% shorter, 50% faster, and 200% more readable for average joe programmer). > ... my 2 sents, anyway ... May I add my 2 cents - or should I send them ?-) From david at asdf.asdf Thu Sep 6 22:03:26 2007 From: david at asdf.asdf (bambam) Date: Fri, 7 Sep 2007 12:03:26 +1000 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com><13dv4uqqb806ff0@corp.supernews.com> <13dvvgk96amhhec@corp.supernews.com> Message-ID: <13e1cbetihma1d6@corp.supernews.com> Hi Steven. Looking at your code, why are you naming the value __all__? It looks like a built-in variable? Unless there is an automatic way to correctly get the function list, I will probably be better off giving the lines sequence numbers, and generating the function list from that. Steve. "Steven D'Aprano" wrote in message news:13dvvgk96amhhec at corp.supernews.com... > On Thu, 06 Sep 2007 15:44:57 +1000, > "bambam" wrote in message > news:13dsvqrqivtf092 at corp.supernews.com... > > Try something like this: define a module holding the device functions. > > # module script > > __all__ = [a0010, a002, a0030, a0040, a0050] > ... # module test1 import script class Test1(pl_test.Pl_test) """ADC calibration and Battery Voltage calibration""" def run(self,devlist): for line in script.__all__: for self.dev in devlist if self.dev.active and not self.dev.failed try line(self) except Exception,e: print e self.dev.active=False print "The following devices passed:" for dev in devlist if dev.active and not dev.failed print dev print "The following devices need to be re-tested" for dev in devlist if not dev.active print dev print "The remaining devices failed" for dev in delist if dev.active and dev.failed print dev > -- > Steven. > From bj_666 at gmx.net Wed Sep 19 02:34:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Sep 2007 06:34:18 GMT Subject: Deserializing specific objects from a file References: <1190156558.313252.31000@y27g2000pre.googlegroups.com> Message-ID: <5lbu7aF78tegU1@mid.uni-berlin.de> On Tue, 18 Sep 2007 16:02:38 -0700, Aaron J. M. wrote: > There are many objects that I want be able to move in and out of > memory at runtime; namely the game levels. I only want one level in > memory at a time, so I want to be able to unpickle specific Level > objects as the player moves between levels. I would prefer my > serialized objects to reside in one file. > > I haven't come across references that say how to do something like > what I'm describing. Does anyone here know what techniques I have to > employ here? Take a look at the `shelve`-Module. Another option might be pickling to individual files and store them in a ZIP archive. Ciao, Marc 'BlackJack' Rintsch From akhavr at kds.com.ua Sat Sep 22 10:25:32 2007 From: akhavr at kds.com.ua (Andrey Khavryuchenko) Date: Sat, 22 Sep 2007 17:25:32 +0300 Subject: Who can develop the following Python script into working application ? References: <1190334828.210230.293980@50g2000hsm.googlegroups.com> <1190372423.768184.60080@19g2000hsx.googlegroups.com> <5lho31F84jgjU1@mid.uni-berlin.de> <1190419744.390216.19040@w3g2000hsg.googlegroups.com> <5lk9e0F8leeeU1@mid.uni-berlin.de> Message-ID: DBR> And as you said yourself: DBR> """ DBR> Frankly speaking I would prefer to pay for your kind assistance DBR> as it may take me to much time to learn some Python and understand the DBR> following script. DBR> """ DBR> Now, again: http://www.guru.com/ There you can get devlopers for DBR> money. So what again is your problem? Actually, I am a python (and django) developer, looking for a contract, owning Nokia 770 and contacted original poster with no response. -- Andrey V Khavryuchenko http://a.khavr.com/ Chytach - unflood your feeds http://www.chytach.com/ Software Development Company http://www.kds.com.ua/ From ladaan at iptel.org Wed Sep 26 18:14:49 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Thu, 27 Sep 2007 00:14:49 +0200 Subject: ~ bit-wise unary operator Message-ID: <46FAD9D9.1000503@iptel.org> Hello, why ~ bit-wise unary operator returns -(x+1) and not bit inversion of the given integer? example: a = 7978 a = ~a python returns -7979 but I need to get back 57557 as in C language. which is also in binary 0001111100101010 and inverted 1110000011010101 Is here any other operator or do I have to write it on my own? Thank you, Lada From meesters at uni-mainz.de Tue Sep 25 04:19:19 2007 From: meesters at uni-mainz.de (Christian Meesters) Date: Tue, 25 Sep 2007 10:19:19 +0200 Subject: strange behavious of the logging module? References: <1190643051.084144.230220@o80g2000hse.googlegroups.com> <1190672978.233964.232900@g4g2000hsf.googlegroups.com> Message-ID: Peter Otten wrote: > Vinay Sajip wrote: > >> This is a known bug, and not specifically related to logging, though >> it sometimes manifests itself via logging: >> >> http://bugs.python.org/issue1180193 > > Yup, thanks for looking into it. > > Peter Thanks Vinay, but I am curious how issue 1180193 is related to the "bug" Peter and me described: I do not have any *.pyc file around. As I kept changing the file during development I used to call the program directly using a link in my PATH. Hence no *.pyc file got created at all. However, does anybody know a suggestion for a work-around? Christian From wizzardx at gmail.com Thu Sep 20 17:44:27 2007 From: wizzardx at gmail.com (David) Date: Thu, 20 Sep 2007 23:44:27 +0200 Subject: re question In-Reply-To: References: Message-ID: <18c1e6480709201444w5820f86flfa77c103d76570c7@mail.gmail.com> On 9/19/07, Dan Bar Dov wrote: > I'm trying to construct a regular expression to match valid IP address, > without leading zeroes (i.e > 1.2.3.4, 254.10.0.0, but not 324.1.1.1, nor 010.10.10.1) > > This is what I come up with, and it does not work. > > r'(^[12]?\d{0,2}\.){3,3}[12]?\d{0,2}' > > What am I doing wrong? > Any common knowledge IP matching RE? http://www.regular-expressions.info/examples.html ? From steve at holdenweb.com Fri Sep 28 13:57:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 13:57:57 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191000394.828693.285210@k79g2000hse.googlegroups.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> <1190997769.002795.59450@57g2000hsv.googlegroups.com> <5m4qc2Fbbk19U1@mid.uni-berlin.de> <1191000394.828693.285210@k79g2000hse.googlegroups.com> Message-ID: <46FD40A5.8030504@holdenweb.com> TheFlyingDutchman wrote: > On Sep 28, 10:01 am, Marc 'BlackJack' Rintsch wrote: >> On Fri, 28 Sep 2007 09:42:49 -0700, TheFlyingDutchman wrote: >>> Which of the common languages have higher order functions and what is >>> the syntax? >> C, C++, Pascal, Perl, PHP, Ruby have them. And of course the functional >> languages, most notably Lisp and Scheme as you asked for common languages. >> >> Don't know if C#'s delegates qualify. >> >> Ciao, >> Marc 'BlackJack' Rintsch > > What is the syntax of a higher order function in C, C++ and Pascal? > This is like listening to a four-year-old torment its parents with incessant questions. Do you *have* to ask every question that pops into your mind? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From jcarlson at uci.edu Tue Sep 25 06:20:21 2007 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 25 Sep 2007 03:20:21 -0700 Subject: ANN: PyPE 2.8.7 Message-ID: <20070925031950.8542.JCARLSON@uci.edu> === What is PyPE? === PyPE (Python Programmers' Editor) was written in order to offer a lightweight but powerful editor for those who think emacs is too much and idle is too little. Syntax highlighting is included out of the box, as is multiple open documents via tabs. Beyond the basic functionality, PyPE offers an expandable source tree, filesystem browser, draggable document list, todo list, filterable function list, find and replace bars (no dialog to find or replace simple strings), recordable and programmable macros, spell checker, reconfigurable menu hotkeys, triggers, find in files, external process shells, and much more. === More Information === If you would like more information about PyPE, including screenshots, where to download the source or windows binaries, bug tracker, contact information, or a somewhat complete listing of PyPE's features, visit PyPE's home on the web: http://pype.sf.net/index.shtml If you have any questions about PyPE, please contact me, Josiah Carlson, aka the author of PyPE, at jcarlson at uci.edu (remember to include "PyPE" in the subject). PyPE 2.8.7 includes the following changes and bugfixes since release 2.8.5: #-------------------------------- PyPE 2.8.7 --------------------------------- (fixed) some bugs related to the parsers module movement. (fixed) ordering of user profile path discovery to not break when confronted with insane 'HOME' environment variable on Windows (will use USERPROFILE or HOMEDRIVE/HOMEPATH first). (fixed) unrepr mechansim can now handle negative value storage for disabled realtime options, etc. #-------------------------------- PyPE 2.8.6 --------------------------------- (fixed) a bug with "Wrap Try/Except" as per emailed bug report from Ian York. (added) ability to choose what port PyPE will listen on via --port= . (fixed) workspaces in wxPython 2.8+, patch thanks to Craig Mahaney. (added) explicit exclude dirs for find in files, patch thanks to Craig Mahaney. (added) paste and down mechanism to paste and move the cursor down, patch thanks to Craig Mahaney. (added) delete right mechanism to delete everything from the cursor to the end of the line, patch thanks to Craig Mahaney. (added) delete line mechanism to delete the current line, patch thanks to Craig Mahaney. (added) paste rectangle command for rectangular pasting, patch thanks to Craig Mahaney. (fixed) support for alternate background colors thanks to bug report from Craig Mahaney. (added) macro support to Craig Mahaney's added functionality. (added) implementation for regular expression replacements, possibly to be integrated as part of a 'replace in all open documents' in the future. (added) automatic spellcheck for text and tex documents of up to 200,000 byes in size. Will only spellcheck if the user has enabled "check syntax" in the "Realtime Options". (fixed) issue when trying to save language settings when cursor position is not to be saved. (added) support for \chapter section delimiter in *tex files. (fixed) issue that prevented the highest level source listing from being sorted in the Name and Line sorted source trees. (changed) rather than reading and executing a file for configuration loading, we now use a variant of the 'unrepr()' mechanism with support for True/False. (changed) find/replace bar now uses variant of 'unrepr()' rather than the compiler module directly. (changed) moved parsers.py to plugins and stopped using import * to get its contents. From christophertidy at hotmail.com Mon Sep 3 12:13:28 2007 From: christophertidy at hotmail.com (christophertidy at hotmail.com) Date: Mon, 03 Sep 2007 16:13:28 -0000 Subject: TypeError: 'module object is not callable' In-Reply-To: <5k2cjmF1r2aiU1@mid.uni-berlin.de> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> Message-ID: <1188836008.656284.76160@o80g2000hse.googlegroups.com> > > The others spottet the error I missed. But I can offer something else: > > http://dirtsimple.org/2004/12/python-is-not-java.html > > It's a worthy read for someone coming from Java, needing time to adjust. > > Diez- Hide quoted text - > > - Show quoted text - That deffinately was a useful read, thanks. Thankyou to everyone who sorted these problems for me, I have progressed very well with this python program throughout the day now. I have another little question before I finish today: I am currently struggling to use a global variable in my static functions. I'll explain further Within my main.py file I have class Main(object): stepStore = StepStore() @staticmethod def createDepSteps(): .... stepStore.addStep([bol7, pre5]) ....... @staticmethod def processSteps(): for step in stepStore.stepList[:]: ...... Main.createDepSteps() Main.processSteps() Trying this approach I am getting a error saying with the processSteps() method, stepStore is undefined To solve this problem I am currently passing in the processSteps() parameter a stepStore instance created within createDepSteps() but there is surely a way stepStore can be a global attribute which can be accessed from both methods? Any help would be much appreciated again Cheers Chris From ricaraoz at gmail.com Sat Sep 1 08:51:26 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Sep 2007 09:51:26 -0300 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <026201c7ec75$07d6e0c0$03000080@hendrik> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com><-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com><1188364909.397692.209170@q4g2000prc.googlegroups.com><1188367108.393207.241970@g4g2000hsf.googlegroups.com><1188369928.755777.142690@i38g2000prf.googlegroups.com><46d75191$0$401$426a74cc@news.free.fr><1188518054.298017.90610@x35g2000prf.googlegroups.com><46d76595$0$4013$426a74cc@news.free.fr><1188523589.736146.263510@l22g2000prc.googlegroups.com><1i3o9kr.2gmni61g62moaN%aleax@mac.com><7xwsvcc9yz.fsf@ruckus.brouhaha.com><1i3p8lm.19738kn1q0gkouN%aleax@mac.com><1188587846.687895.69240@q5g2000prf.googlegroups.com><38rmq4-cq.ln1@strongwill.g2ctech> <46d903db$0$19580$4c368faf@roadrunner.com> <026201c7ec75$07d6e0c0$03000080@hendrik> Message-ID: <46D9604E.6060708@bigfoot.com> Hendrik van Rooyen wrote: > "Carl Banks" wrote: > >> This is starting to sound silly, people. Critical is a relative term, >> and one project's critical may be anothers mundane. Sure a flaw in your >> flagship product is a critical problem *for your company*, but are you >> really trying to say that the criticalness of a bad web search is even >> comparable to the most important systems on airplanes, nuclear reactors, >> dams, and so on? Come on. > > This really intrigues me - how do you program a dam? - and why is it > critical? > > Most dams just hold water back. > > Dam design software - well yes that I would agree is critical. > Is that what you mean? > > - Hendrik > Yup! He was referring to that Damn design software. Just as almost everyone has at one time or another. ;c) From pavlovevidence at gmail.com Sat Sep 29 02:19:37 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Sep 2007 02:19:37 -0400 Subject: Python 3.0 migration plans? References: Message-ID: <46fdfbf2$0$24308$4c368faf@roadrunner.com> On Fri, 28 Sep 2007 09:56:48 -0400, Stephan Deibel wrote: > Ian Dickinson wrote: >> Never would look like a good time scale to me given that a lot of the >> stuff I use is being ripped out!!!! > > Has any one actually converted any real code or significant bits of code > using the 3.0 converter (in the sandbox somewhere), and if so what kinds > of things actually failed? Well, since the converter is designed to convert 2.6 and above, and since there isn't much Python 2.6 code out there yet, I'd say nothing significant. :) Anyways, it is not designed to convert arbitrary code that's lying around: it's designed to convert a supported subset of Python 2.6+ into Python 3.0. You'd have to write "transitional Python" to use the tool. Carl Banks From cmr.Pent at gmail.com Wed Sep 12 05:10:09 2007 From: cmr.Pent at gmail.com (cmr.Pent at gmail.com) Date: Wed, 12 Sep 2007 02:10:09 -0700 Subject: need scsh in a wikip article In-Reply-To: <1189568488.932657.129510@o80g2000hse.googlegroups.com> References: <1189563310.268611.4550@r34g2000hsd.googlegroups.com> <1189568488.932657.129510@o80g2000hse.googlegroups.com> Message-ID: <1189588209.836060.46920@50g2000hsm.googlegroups.com> > someone please add scsh there. Why can't YOU add scsh or I am missing something?? Andrey From http Thu Sep 27 05:24:33 2007 From: http (Paul Rubin) Date: 27 Sep 2007 02:24:33 -0700 Subject: sorteddict PEP proposal [started off as orderedict] References: <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <1190805297.182232.116830@50g2000hsm.googlegroups.com> <1190815180.945099.248670@n39g2000hsh.googlegroups.com> <1190816657.574437.80980@g4g2000hsf.googlegroups.com> <1190820026.299569.110250@n39g2000hsh.googlegroups.com> <1190846656.770087.173230@19g2000hsx.googlegroups.com> <1190880801.795820.275070@50g2000hsm.googlegroups.com> Message-ID: <7xzlz8ea0e.fsf@ruckus.brouhaha.com> Duncan Booth writes: > Ok, your choice, just be aware that by using such a restrictive license you > will dissuade a lot of people from using your code. You've prevented your > module being used in any existing projects with Python license, GPL v2, or > probably any license other than GPL v3. GPL2 projects seem to be migrating nicely to GPL3 so GPL2 shouldn't be too much of a problem. Since one of the Python license's goals is to allow re-use in proprietary programs, and the GPL family's main goal is the exact opposite, I'd say if someone chooses a GPL, then preventing the code from being used in a Python-licensed project was part of the intention and not an undesired consequence. While Python itself is unlikely to switch to a new license in order to import GPL code, other projects can and have done exactly that. From jcd at sdf.lonestar.org Fri Sep 21 15:29:50 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Fri, 21 Sep 2007 15:29:50 -0400 Subject: RE Help In-Reply-To: <1190401551.706792.178450@22g2000hsm.googlegroups.com> References: <1190399985.324448.242610@d55g2000hsg.googlegroups.com> <1190401551.706792.178450@22g2000hsm.googlegroups.com> Message-ID: <20070921192950.GB12479@sdf.lonestar.org> On Fri, Sep 21, 2007 at 12:05:51PM -0700, chris.monsanto at gmail.com wrote regarding Re: RE Help: > > > > > x = re.compile('START(.*)END', re.DOTALL) > > You'll want to use a non-greedy match: > > x = re.compile(r"START(.*?)END", re.DOTALL) > > Otherwise the . will match END as well. The . will only consume END if there is another END to match later on in the string. And then it's a question of desired fuctionality. If the given string is: "abcdSTARTefgENDxyzENDhijk" do you want to match "STARTefgEND" (in which case you need a non-greedy match r".*?" )? or do you want to match "STARTefgENDxyzEND" (in which case you need a greedy match: r".*" )? Cheers, Cliff From piyushj at cse.iitk.ac.in Thu Sep 27 09:07:09 2007 From: piyushj at cse.iitk.ac.in (Piyush Jain) Date: Thu, 27 Sep 2007 18:37:09 +0530 Subject: making run time changes.. Message-ID: <000001c80107$4f9ff120$eedfd360$@iitk.ac.in> Hi, I am new(almost) to python. I wish to making a server in which I can make changes at run time. For example , add a method to a class/attribute to object etc. by sending it messages. Can anyone help me with what features to look into and how to go about it. Are there any similar projects? Regards, Piyush -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Tue Sep 25 22:19:00 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 26 Sep 2007 14:19:00 +1200 Subject: Script to extract text from PDF files References: <1190746968.162359.39890@r29g2000hsg.googlegroups.com> <1190747931.415834.75670@n39g2000hsh.googlegroups.com> Message-ID: In message <1190747931.415834.75670 at n39g2000hsh.googlegroups.com>, byte8bits at gmail.com wrote: > On Sep 25, 3:02 pm, Paul Hankin wrote: > >> Googling for 'pdf to text python' and following the first link >> giveshttp://pybrary.net/pyPdf/ > > Doesn't work that well... This is inherent in the nature of PDF: it's a page-description language, not a document-interchange language. Each text-drawing command can put a block of text anywhere on the page, so you have no idea, just from parsing the PDF content, how to join these blocks up into lines, paragraphs, columns etc. From carsten at uniqsys.com Mon Sep 24 07:39:11 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Sep 2007 07:39:11 -0400 Subject: sorting a list numbers stored as strings In-Reply-To: <1360b7230709240423k47485263pedc6562000ba1597@mail.gmail.com> References: <1190632366.863711.100680@y42g2000hsy.googlegroups.com> <1360b7230709240423k47485263pedc6562000ba1597@mail.gmail.com> Message-ID: <1190633951.3385.23.camel@dot.uniqsys.com> On Mon, 2007-09-24 at 16:53 +0530, Amit Khemka wrote: > On 9/24/07, aine_canby at yahoo.com wrote: > > hi, > > > > I have the following list - > > > > ["1", "11", "2", "22"] > > > > how do I sort it like this - > > > > ["1", "2", "11", "22"] > > > > Hi, > > >>> l = ["1", "11", "2", "22"] > >>> sorted(l, cmp = lambda x, y: cmp(int(x), int(y))) # provide your > own compare function ! > >>> l > ['1', '2', '11', '22'] That interpreter session is a work of fiction, since sorted returns the sorted list instead of sorting the list in place. Also, it's better (i.e. more readable and likely faster) to use a sort key function instead of a comparison function whenever possible. In this case, the sort key function is particularly trivial: >>> l = ["1", "11", "2", "22"] >>> sorted(l, key=int) ['1', '2', '11', '22'] -- Carsten Haese http://informixdb.sourceforge.net From zzbbaadd at aol.com Thu Sep 20 02:17:36 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 19 Sep 2007 23:17:36 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> Message-ID: <1190269056.975115.217050@22g2000hsm.googlegroups.com> 2 On Sep 19, 5:08 pm, "Terry Reedy" wrote: > "Terry Reedy" wrote in message > > > This assumes that comparing versions of 1.5 is still relevant. As far as I > know, his patch has not been maintained to apply against current Python. > This tells me that no one to date really wants to dump the GIL at the cost > of half Python's speed. Of course not. The point of dumping the GIL is to > use multiprocessors to get more speed! So with two cores and extra > overhead, Stein-patched 1.5 would not even break even. Is the only point in getting rid of the GIL to allow multi-threaded applications? Can't multiple threads also provide a performance boost versus multiple processes on a single-core machine? > > So now this question for you: "CPython 2.5 runs too slow in 2007: true or > false?" Ugh, I guess I have to agree with Steven D'Aprano - it depends. > > If you answer false, then there is no need for GIL removal. OK, I can see that. > If you answer true, then cutting its speed for 90+% of people is bad. OK, have to agree. Sounds like it could be a good candidate for a fork. One question - is it a computer science maxim that an interpreter that implements multi-threading will always be slower when running single threaded apps? > > And another question: why should such people spend time they do not have to > make Python worse for themselves? I can't make an argument for someone doing something for free that they don't have the time for. Ditto for doing something for free that they don't want to do. But it does seem that if they give a reason for why it's the wrong thing to do, it's fair to make a counter-argument. Although I agree with Steven D'Aprano's theme in that it should be a cordial rebuttal and not a demand. From sjmachin at lexicon.net Sat Sep 15 08:51:20 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Sep 2007 05:51:20 -0700 Subject: how to join array of integers? In-Reply-To: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> Message-ID: <1189860680.729191.13290@g4g2000hsf.googlegroups.com> On Sep 15, 10:36 pm, Summercool wrote: > i think in Ruby, if you have an array (or list) of integers > > foo = [1, 2, 3] > > you can use foo.join(",") to join them into a string "1,2,3" > > in Python... is the method to use ",".join() ? but then it must take > a list of strings... not integers... > > any fast method? >>> foo = [1,2,3] >>> ",".join(str(x) for x in foo) '1,2,3' >>> ",".join(map(str, foo)) '1,2,3' >>> If you are going to write several such results to a file, consider using the csv module. HTH, John From bkline at rksystems.com Sun Sep 16 01:47:36 2007 From: bkline at rksystems.com (Bob Kline) Date: Sun, 16 Sep 2007 01:47:36 -0400 Subject: Un(der)documented bits of cgi.py Message-ID: I'm trying to detect and intelligently deal with problems created when a user of a Python CGI page uploads a file and then gets impatient and clicks on some other button or the browser's cancel button (or even closes the page). If the file is large enough, and the user is impatient enough, this can result in the FieldStorage.file object getting some, but not all of the bytes from the user's file, with no documented means of detecting that this has happened. Poking around in the code for cgi.py in the standard library, it appears that there is an undocumented 'done' attribute which might be useful here (it seems as if it might get set to -1 when this condition is encountered), but of course one is reluctant to leave behind software which relies on undocumented behavior of packages, since those bits have a way of disappearing in the middle of the night, suddenly breaking one's software. Can anyone think of a good reason why it would not be desirable to expose a publicly documented means of detecting the condition described above? Cheers and thanks! Bob Kline From kyosohma at gmail.com Tue Sep 18 15:36:52 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 18 Sep 2007 19:36:52 -0000 Subject: Tutorial or Example (or Tutorial) of Using Canvas to Produce a Plot In-Reply-To: References: <13evohih7rkd030@corp.supernews.com> Message-ID: <1190144212.073532.95830@d55g2000hsg.googlegroups.com> On Sep 18, 12:23 pm, "W. Watson" wrote: > What would be appropriate? What are the choices? I'm pretty new to Python, > but am familiar with the XWindow widget set. I think it is available under > Python, but if there's a more suitable choice, that's fine. I would think > Tkinter would be the simplest choice. Yes, Tkinter would be preferable. It > seems to be the GUI of choice. > > Grant Edwards wrote: > > On 2007-09-18, W. Watson wrote: > > >> I'm looking for an example with canvas that produces, say, a > >> complete x-y plot of some data. > > > With what widget set? > > -- > Wayne Watson (Nevada City, CA) > > Web Page: I've heard a lot about drawing with the wxPython widget set as well. Some examples: http://wiki.wxpython.org/RecipesImagesAndGraphics Mike From m.n.summerfield at googlemail.com Wed Sep 26 11:40:39 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Wed, 26 Sep 2007 15:40:39 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190820026.299569.110250@n39g2000hsh.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <1190805297.182232.116830@50g2000hsm.googlegroups.com> <1190815180.945099.248670@n39g2000hsh.googlegroups.com> <1190816657.574437.80980@g4g2000hsf.googlegroups.com> <1190820026.299569.110250@n39g2000hsh.googlegroups.com> Message-ID: <1190821239.051614.301070@19g2000hsx.googlegroups.com> On 26 Sep, 16:20, Paul Hankin wrote: > On Sep 26, 3:24 pm, Mark Summerfield > wrote: > > > On 26 Sep, 14:59, Paul Hankin wrote: > > > > On Sep 26, 2:46 pm, Duncan Booth wrote: > > > > > Paul Hankin wrote: > > > > > More flexibly, keep a set of inserted keys that haven't yet been > > > > > included in the sorted list, and a set of deleted keys that haven't > > > > > yet been removed from the sorted list. The cache is invalid if either > > > > > of these sets are empty - and to make it valid you can choose what to > > > > > do based on the sizes of the two sets (and the sorted list). For > > > > > instance, if there's just been one insertion you're probably better > > > > > doing an insertion rather than a full resort. Of course, there's a few > > > > > nasty cases here but it's always possible to just throw away the > > > > > sorted list and reconstruct it from the dict keys when things get too > > > > > hairy (eg, the user deletes a key that's in the inserted-but-not-yet- > > > > > sorted set). > > > > > Yes that sounds good. Did you mean 'The cache is invalid if either of > > > > these sets is not empty'? > > > > Yes :) > > > > > If you delete a key which is in the inserted set you can simply delete > > > > it from the inserted set. > > > > No, in case it was already in the sorted list before the insert. You > > > have to remove it from the inserted set AND add it to the deleted set. > > > > -- > > > Paul Hankin > > > So should Duncan's > > > def __removekey(self, key): > > if key in self.__addkeys: > > del self.__addkeys[key] > > else: > > self.__delkeys.add(key) > > > be changed to: > > > def __removekey(self, key): > > if key in self.__addkeys: > > del self.__addkeys[key] > > self.__delkeys.add(key) > > Yes, and the same in __addkey: if it's in __delkeys it should be > removed from there, and added to __addkeys. There's an invariant: any > key is in at most one of __addkeys and __delkeys. OK, I have changed both: def __addkey(self, key): if key in self.__delkeys: del self.__delkeys[key] self.__addkeys.add(key) def __removekey(self, key): if key in self.__addkeys: del self.__addkeys[key] self.__delkeys.add(key) > > (BTW I'm happy to put up a new version on PyPI, but I'm v. conscious > > of the fact that the key ideas and code have come from you and Duncan, > > so if either of you would like to adopt it, I will gladly step aside. > > I just want a sorteddict in Python, and I don't mind who does it:-) > > Speaking for myself, I'm happy to have helped out, but you should > carry on. OK, I will if Duncan doesn't want it:-) > -- > Paul Hankin From zzbbaadd at aol.com Mon Sep 10 02:20:11 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Sun, 09 Sep 2007 23:20:11 -0700 Subject: Python syntax wart In-Reply-To: References: Message-ID: <1189405211.875217.176620@57g2000hsv.googlegroups.com> It may be that a language that doesn't have a statement terminator (which can be end-of-line) needs a statement continuation symbol. (Excluding languages like Lisp that have parentheses everywhere). From carsten at uniqsys.com Thu Sep 20 08:55:15 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 20 Sep 2007 08:55:15 -0400 Subject: AIX - Python - db2.py In-Reply-To: <6702B04331BCF8408F9FE92AFC5349B7E442@INBLRCLUMS0201.in.tesco.org> References: <6702B04331BCF8408F9FE92AFC5349B7E442@INBLRCLUMS0201.in.tesco.org> Message-ID: <1190292915.3392.10.camel@dot.uniqsys.com> On Thu, 2007-09-20 at 16:05 +0530, Shilavantar, Praveen wrote: > Hi, > > I am getting the following error while installing PyDB2 package on > AIX machine. > So can anybody give me the requirements list and a procedure to > install PyDb2 package on AIX. > > > xn75 at ti057:/home/xn75/PyDB2-1.1.0> python setup.py install > Your DB2 root is: > WARNING: it seems that you did not install 'Application Development > Kit'. > Compilation may fail That warning message seems to be fairly clear about the requirements. Have you installed the DB2 Application Development Client? -- Carsten Haese http://informixdb.sourceforge.net From jbuturff at gmail.com Mon Sep 24 20:49:11 2007 From: jbuturff at gmail.com (Horse) Date: Mon, 24 Sep 2007 17:49:11 -0700 Subject: shutil.copy2 error In-Reply-To: <1190673284.509807.110830@57g2000hsv.googlegroups.com> References: <1190644477.380312.261840@d55g2000hsg.googlegroups.com> <1190673284.509807.110830@57g2000hsv.googlegroups.com> Message-ID: <1190681351.841370.100150@19g2000hsx.googlegroups.com> On Sep 24, 6:34 pm, Karthik Gurusamy wrote: > On Sep 24, 7:34 am, Horse wrote: > > > > > I've written a python script that copies a nightly Oracle backup file > > to another server. Every couple days, the script fails with this > > error message: > > > Error copying Q:/Oradata/GISPROD/Backups/3UISN35R_1_1 to s:/gisprod/ > > backups/3UISN35R_1_1 > > [Errno 22] Invalid argument > > > Here's the code for the function I'm running. The path names are all > > correct, and it works *most of the time*. It only fails about once or > > twice a week. Anyone know where I can get more info on this "errno 22 > > invalid argument"? > > > def CopyNewFiles(SOURCE_DIR, DEST_DIR): > > global STATUS > > try: > > os.chdir(SOURCE_DIR) > > for x in os.listdir(SOURCE_DIR): > > int_time = os.stat(x)[stat.ST_CTIME] > > str_time = time.ctime(int_time) > > if datetime.date.fromtimestamp(int_time + 0.00) > > > YESTERDAY: > > try: > > DEST_FILE = os.path.join(DEST_DIR, x) > > logfile.write(" Copying " + SOURCE_DIR + x + " > > to " + DEST_FILE + "\n") > > logfile.flush() > > if not os.path.isfile(DEST_FILE): > > shutil.copy2(x, DEST_FILE) > > I'm not sure of the error; but one possibility is that the source- > directory contents may be modified by some other process, while you > are looping here copying one-by-one the files. > > So a file 'x' could be present at the time you enter loop, but gone by > the time you try the shutil.copy2. Again this is just a guess... > > Yet another possibility is 'x' is not a regular file (say in unix it > could be a named pipe).. you can try adding a check for x (like > os.path.isfile(x)) and copy only regular files. > > Karthik > Thanks for the ideas, I will look into if there is anything else using these files (maybe a system level backup they hadn't told me about??). Otherwise, these files are perfectly valid, I can go back on the ones that error and manually copy them by hand to the destination folder. I should've mentioned earlier, but this is running on a windows 2000 system, and the destination folder is a samba share on a Linux server. From bignose+hates-spam at benfinney.id.au Wed Sep 5 23:08:05 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 06 Sep 2007 13:08:05 +1000 Subject: Give List to Format String - How To References: <1189046828.313284.235210@o80g2000hse.googlegroups.com> Message-ID: <874pi87ap6.fsf@benfinney.id.au> "gregpinero at gmail.com" writes: > I might just be being dumb tonight, but why doesn't this work: Congratulations for finding the answer quickly, and thank you for letting us know the answer. In future, if you want to ask "why doesn't this work", please show us all three of: the example code, the actual behaviour, and the expected behaviour. "Doesn't work" is not a substitute for the last two. -- \ "Most people, I think, don't even know what a rootkit is, so | `\ why should they care about it?" -- Thomas Hesse, Sony BMG, 2006 | _o__) | Ben Finney From gagsl-py2 at yahoo.com.ar Tue Sep 18 08:50:41 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Sep 2007 09:50:41 -0300 Subject: super, apply, or __init__ when subclassing? References: <1190100791.740269.62880@k79g2000hse.googlegroups.com> Message-ID: En Tue, 18 Sep 2007 04:33:11 -0300, exhuma.twn escribi?: > This is something that keeps confusing me. If you read examples of > code on the web, you keep on seeing these three calls (super, apply > and __init__) to reference the super-class. This looks to me as it is > somehow personal preference. But this would conflict with the "There > one way to do it" mind-set. > > So, knowing that in python there is one thing to do something, these > three different calls must *do* domething different. But what exactly > *is* the difference? There are a few typos in your examples. If you write them this way: > ------------ Exampel 1: ----------------------------- > > class B(A): > def __init__(self, *args): > A.__init__(self, *args) > > ------------ Exampel 2: ----------------------------- > > class B(A): > def __init__(self, *args): > apply( A.__init__, (self,) + args) > > ------------ Exampel 3: ----------------------------- > > class B(A): > def __init__(self, *args): > super(B,self).__init__(*args) then 2 is exactly the same as 1 but using a deprecated function. And 3 is the same as 1 only when there is single inheritance involved (and you are using new-style classes). But see the thread "super() doesn't get superclass" -- Gabriel Genellina From carsten at uniqsys.com Fri Sep 7 15:15:25 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 07 Sep 2007 15:15:25 -0400 Subject: How to convert None to null value In-Reply-To: <13e38g6poh2jre3@corp.supernews.com> References: <13e38g6poh2jre3@corp.supernews.com> Message-ID: <1189192525.3367.97.camel@dot.uniqsys.com> On Fri, 2007-09-07 at 12:10 -0700, Dennis Lee Bieber wrote: > On Fri, 07 Sep 2007 09:07:49 -0400, Carsten Haese > declaimed the following in comp.lang.python: > > > > doesn't have a parameter binding mechanism, you should throw it away and > > replace it with a DB-API complaint module. > > > I hadn't realized the DB-API defined a "complaint" module Yeah, I noticed the typo a minute too late. Dyslexics of the world, untie! ;-) -- Carsten Haese http://informixdb.sourceforge.net From zzbbaadd at aol.com Tue Sep 4 22:14:16 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 04 Sep 2007 19:14:16 -0700 Subject: parameter list notation In-Reply-To: References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> <1188882641.899594.212400@22g2000hsm.googlegroups.com> <13drhdial6p58ca@corp.supernews.com> <1188943564.291412.16000@50g2000hsm.googlegroups.com> Message-ID: <1188958456.208622.44640@57g2000hsv.googlegroups.com> > > Perhaps you could move further discussions to comp.lang.piethun? > Fair enough. Will contain PIEthun discussion to the PIEthun mailing list and the aforementioned newsgroup once it is established. It suddenly dawned on me while rereading my defense of my use of the term "array" .... that I wasn't the person who used array. That came from here and was probably written by someone who has a lot of experiences in languages other than Python: http://snippets.dzone.com/posts/show/1713 From pixellee at 163.com Sat Sep 15 20:43:40 2007 From: pixellee at 163.com (pixellee at 163.com) Date: Sat, 15 Sep 2007 17:43:40 -0700 Subject: Latest software here!!!!! In-Reply-To: <1189882311.391961.125720@r29g2000hsg.googlegroups.com> References: <1189882311.391961.125720@r29g2000hsg.googlegroups.com> Message-ID: <1189903420.991772.288850@k79g2000hse.googlegroups.com> On 9 16 , 2 51 , freesoftwarew... at gmail.com wrote: > http://freesoftwareupgrades.blogspot.com/ what From steve at holdenweb.com Sun Sep 16 19:23:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Sep 2007 19:23:11 -0400 Subject: Needless copying in iterations? In-Reply-To: <13ercljcg60mq99@corp.supernews.com> References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> <13epv3fnb6bak15@corp.supernews.com> <13ercljcg60mq99@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sun, 16 Sep 2007 11:49:15 -0400, Steve Holden wrote: > >>> It seems to me that the "consenting adults" philosophy of Python >>> doesn't extend to the compiler, and perhaps it should. Maybe Python >>> could optimize common cases, and if developers wanted to do wacky >>> things, let them turn optimization off on a module-by-module basis. >>> >>> Or even function-by-function. Wouldn't it be nice to have decorators >>> that could optimize the functions they decorated? >>> >> No, it would be disastrous, > > Disastrous, as in thousands dead, panic in the street, martial law > declared? I'm sure your program in important, but is it really *that* > important? :-) > To me, naturally. I don't expect you to be quite so engaged :-) > >> unless you could manage to implement a >> mechanism that *told* you when the optimizations were playing havoc with >> your program's execution. > > How about "the test suite passes when I turn optimization off, but fails > when I turn optimization on"? How is that any different from "the test > suite passes when I use StringIO, but not if I use cStringIO"? > Well, firstly it appears to mandate test-driven development. While this is a meritorious approach, it seems a rather draconian approach to language implementation. > > >> The problem is that debugging only works if you can assume a >> deterministic environment. If you are going to put funky optimizations >> in that break determinism in "little-used" corner cases, then debugging >> the situations when the optimizations *do* affect program execution will >> be a complete pain. > > Right, so we're back to the "any pixel is as likely as any other pixel" > example from Joel On Software I mentioned earlier. To prevent some > hypothetical developer doing some wacky thing from having to work harder > to debug some weird corner case, *everybody else* has to miss out on > optimizations that could lead to significantly better performance. > > You might think that's a good trade-off. I don't. > Well I have always gone by the principle "First, make it work. Then (if it doesn't work fast enough) make it work faster". Correctness is the first requirement. But it's naive to assume, even in a test-driven environment, that testing can be complete enough to trigger every possible pathology of a compiler that is no longer deterministic. If you want to ask for that kind of trouble then feel free to go ahead, but I fear you will have to proceed without me. > >>>>> for item in alist[1:5]: >>>>> alist.append(item) # side-effects DON'T matter >>>> The compiler doesn't know that, at the time of invocation, >>>> 'alist.append' doesn't have side effects that matter. >>> It might if it knows what type alist is, and how long it is (as Marc >>> Rintsch points out). That's why I used "alist" in my example rather >>> than "an_arbitrary_sequence". >>> >> But alist doesn't *have* a type, and static program analysis would have >> to be extensive to determine that it could only ever be of a specific >> type. > > Of course alist has a type. Python is a strongly-typed language, not > untyped. > No, alist is a name. It's the objects that names refer to that have types. This is not a fatuous point, and I am well aware that Python is a strongly-typed language. It as, however, also a late-binding language, and it's precisely this aspect of its dynamism which confounds the solution you suggest. > And I don't believe I specifically mentioned that static program analysis > was the only optimization possible. But even if it was... > > I can *hand optimize* a function that I write, yes? I might *choose* to > say to myself, "Screw duck typing, in *my* program function foo will only > ever be called with an honest-to-god built-in list argument, I'm going to > optimize it for that case". We're all consenting adults here, right? > > Well, what's the difference between me hand optimizing the function, and > calling a built-in decorator that does it for me? Why is it okay for me > to shoot myself in the foot, but not for me to tell the compiler to shoot > me in the foot? > I'm nit sure what you are saying here. Are you implying that you want to include type declarations, or somehow impose them by the use of decorators? I'm quite happy to allow you to shoot yourself in the foot, because you are a consenting adult. However, it's also the responsibility of consenting adults to make sure their behavior doesn't harm the uninvolved, and I'm not convinced your approach wouldn't harm beginner unaware if its significance. > >>> Because of its very nature, optimizing Python is hard. Even something >>> as simple as tail-call recursion optimization is verboten, because >>> Guido considers good stack traces more important than preventing stack >>> overflows in the first place: >>> >>> http://www.tratt.net/laurie/tech_articles/articles/ > tail_call_optimization >> And who's to say he's wrong, especially since Python is intended to be >> an environment that's friendly to beginners. > > I'm not saying he's *wrong*, I'm saying he's making trade-offs I would > like to see relaxed. > Aah, right. Tough. :-) > But in the specific case of recursion... have you seen the exception you > get when the recursion limit is hit? By default, you get 1000 lines of ' > File "foo", line 2, in function_name' followed by "RuntimeError: maximum > recursion depth exceeded". Maybe I'm missing something there, but I don't > see how that's much of a help in debugging. > That assumes a single recursive function. If there are a set of four or six mutually recursive functions the collapsing the traceback by tail-call optimization makes the situation impossible to debug in any straightforward way. > >>> Anyway, I'm not really complaining. I like Python, I'm grateful for the >>> work the Python-dev people have already done, and I'm in no position to >>> volunteer to write an optimizing compiler. And it may be that, >>> regardless of how smart you make the compiler, Python simply can't be >>> optimized because of design decisions made back in 1990-whatever when >>> Guido first started his grand plan. >>> >> There is some of that. The environment is so dynamic that even something >> as innocuous as attribute lookup can actually involve properties (for >> example) reading a relational database! I'm not saying that optimization >> under these circumstances is possible, but that it's much more difficult >> than is easily anticipated, and that the benefits to be gained might be >> less than you would think. > > I'm mostly objecting to people who say that Python's compiler "can't" be > optimized, which is not true. As I mentioned, there's already a peephole > optimizer. There are runtime optimizations possible. Psycho could become > a built-in, if the right people wanted it to become a built-in. Etc. With > a few million in funding, Python could become as heavily optimized as > Common Lisp. > You seem to be unaware that there are organizations with a very large financial stake in Python's success. Given that they aren't providing this funding, who do you imagine will? The PyPy project, to my mind one of the most meritorious projects to emerge form the infrastructure in the last few years, is the result of "a few million in funding", and it shows far more promise for speed-related optimization than CPython ever will, IMHO. But there is currently a hiatus in their funding and I am unsure where they are planning to go from here. > Of course, whether that would still be the Python we know *now* is > another question. But then, with decorators and generator expressions and > iterators, Python 2.6 is not precisely the same as the Python we knew > back in 1997, is it? > No. Perhaps what you seek is RPython. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From chris.monsanto at gmail.com Wed Sep 26 14:41:53 2007 From: chris.monsanto at gmail.com (chris.monsanto at gmail.com) Date: Wed, 26 Sep 2007 11:41:53 -0700 Subject: A question on python performance. In-Reply-To: References: Message-ID: <1190832113.527114.94230@d55g2000hsg.googlegroups.com> On Sep 26, 2:26 pm, "Joe Goldthwaite" wrote: > Hi everyone, > > I'm a developer who's been using python for a couple of years. I wrote a > fairly large application using it but I was learning the language at the > same time so it most of the code kind of sucks. > > I've learned a lot since then and I've been going through my code trying to > organize it better and make better use of Python's features. I'm still not > an expert by any definition but I'm slowly getting better. > > I've been working on a trend class that takes twelve monthly numbers and > returns a period to date, quarter to date, year to date and quarterly year > to date numbers for a specific period. This worked but I ended up with a lot > of code like this; > > def getValue(trend, param, per): > if param == 'Ptd': > return trend.Ptd(per) > elif param == 'Qtd': > return trend.Qtd(per) > elif param == 'Ytd': > return trend.Ytd(per) > elif param == 'YtdQ': > return trend.YtdQ(per) > > The code gets kind of wordy so I started trying to figure out how to call > them dynamically since the param type is the same as the method the > retrieves it. I came up with this; > > def getValue(trend, param, per): > return trend.__class__.__dict__[param](trend, per) > > That worked but it seems like the above line would have to do lots more > object look ups at runtime so I didn't think it would be very efficient. I > thought maybe I could add a caller method to the trend class and I came up > with this; > > class trend: > ... > ... > ... > def caller(self, param, *args): > return self.__class__.__dict__[param](self, *args) > > This simplified the getValue function to this; > > def getValue(trend, param, per): > return trend.caller(param, per) > > Out of curiosity, I thought I'd do some benchmarking and see which one > performs the best. I executed three multiple times; > > loop one. Time=11.71 seconds; > trend.Ptd(per) > trend.Qtd(per) > trend.Ytd(per) > trend.YtdQ(per) > > loop two. 12.107 seconds; > trend.__class__.__dict__['Ptd'](trend, per) > trend.__class__.__dict__['Qtd'](trend, per) > trend.__class__.__dict__['Ytd'](trend, per) > trend.__class__.__dict__['YtdQ'](trend, per) > > loop three. 17.085 seconds; > trend.caller('Ptd', per) > trend.caller('Qtd', per) > trend.caller('Ytd', per) > trend.caller('YtdQ', per) > > The first surprise was how close the first and second loops were. I would > have thought the first loop would be much faster. The second surprise was > how much slower the third loop was. I know it has an extra call in there > but other than that, it's doing basically the same thing as loop two. Is > there that much overhead in making a class method call? > > Can anyone explain the differences? Makes perfect sense to me! Think about it: method 1: looks up the method directly from the object (fastest) method 2: looks up __class__, then looks up __dict__, then gets the element from __dict__ method 3: looks up caller, looks up __class__, looks up __dict__, gets element from __dict__ To get the element directly from the object (method 1), Python has to internally check __class__.__dict__[element], which shows why method 1 and method 2 are nearly the same speed. The last version has to look up caller in addition to the process described by method 2. The best way to do what you are doing: getattr(self, param)(self, *args) From zentraders at gmail.com Fri Sep 7 15:26:46 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 07 Sep 2007 12:26:46 -0700 Subject: How to determine the bool between the strings and ints? In-Reply-To: <5kdjmcF31i6hU7@mid.uni-berlin.de> References: <1189182688.290480.102350@o80g2000hse.googlegroups.com> <5kdjmcF31i6hU7@mid.uni-berlin.de> Message-ID: <1189193206.466633.148610@r34g2000hsd.googlegroups.com> On Sep 7, 11:30 am, Marc 'BlackJack' Rintsch wrote: > On Fri, 07 Sep 2007 18:49:12 +0200, Jorgen Bodde wrote: > > As for why caring if they are bools or not, I write True and False to > > the properties, the internal mechanism works like this so I need to > > make that distinction. > > Really? Can't you just apply the `int()` function? > > In [52]: map(int, [1, 0, True, False]) > Out[52]: [1, 0, 1, 0] > > Ciao, > Marc 'BlackJack' Rintsch Blackjack's solution would take care of the problem, so this is just for general info. Looks like a "feature" of isinstance() is to consider both True and 1 as booleans, but type() distinguishes between the two. >>> x=True ... if type(x) == type(1): ... print "int" ... else: ... print "not int" ... not int if type(x) == type(True): ... print "bool" ... bool From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Sep 12 18:53:41 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 13 Sep 2007 00:53:41 +0200 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> Message-ID: <5kr8vlF53m8gU3@mid.individual.net> TheFlyingDutchman wrote: > In C++ and Java I don't believe "this" is ever referred to as an > implicit function parameter. Oh yes, it is. All methods use it as a base address into instances. Implicitly though. > It is a (sometimes necessary) way to reference the object inside > one if it's methods. Also, I always like to use it explicitly. There's nothing worse than to read others' source and not know if it's a global they access or not. > If it is in fact a real parameter in the underlying compiled-code > implementation, that knowledge hurts more than it helps. To which language are you referring here, Python or C++? No matter what, I still don't really understand why it hurted. Regards, Bj?rn -- BOFH excuse #296: The hardware bus needs a new token. From afriere at yahoo.co.uk Tue Sep 25 22:33:50 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 25 Sep 2007 19:33:50 -0700 Subject: jack audio connection kit In-Reply-To: References: Message-ID: <1190774030.603655.85010@d55g2000hsg.googlegroups.com> On Sep 26, 4:44 am, patrick wrote: > hello everyone, > > is there a way to make python output audio in jack:http://jackaudio.org/ > > jack is the best audio solution for linux, mac and lately windows. i > found 1 project called pyjack, but the author remove the software from > his website. > > that would be neat! > pat I suggest you email andy [at] a2hd [dot] com and ask him what happened to PyJack. From aboudouvas at panafonet.gr Mon Sep 3 05:03:00 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 03 Sep 2007 02:03:00 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <1188803759.498517.198900@g4g2000hsf.googlegroups.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1188803759.498517.198900@g4g2000hsf.googlegroups.com> Message-ID: <1188810180.119298.140840@22g2000hsm.googlegroups.com> On Sep 3, 9:15 am, Michele Simionato wrote: > On Sep 3, 2:21 am, llothar wrote: > > My personal opinion (and I am not the only one in the Python > community) is that > if you want to scale the way to go is to use processes, not threads, > so removing the GIL would be a waste of effort anyway. > Look at the 'processing' module in PyPI. > > Michele Simionato I second that. You may also look here, http://www.parallelpython.com/ I tested it and work as expected. You can see all your processing- cores work nicely and balanced. From sergio.correia at gmail.com Wed Sep 26 17:50:42 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 26 Sep 2007 16:50:42 -0500 Subject: Simple threading example freezes IDLE? In-Reply-To: <1190218626.334442.255450@57g2000hsv.googlegroups.com> References: <1190218626.334442.255450@57g2000hsv.googlegroups.com> Message-ID: I think the -print- command, as used in IDLE, is not thread-safe. I was bitten by an issue like that today, and the problem ended up being the -print- command I used. On the cmd line, it works per-fect-ly.. but IDLE seems to be the culprit. A possible answer seems to be to write a wrapper for print that makes it thread safe (with the help of a lock. On 9/19/07, writser at gmail.com wrote: > hey all, > > For my study I'm writing a simple threaded webcrawler and I am trying > to do this in python. But somehow, using threads causes IDLE to crash > on Windows XP (with the latest python distribution 2.5.1). Even a > simple example such as this: > > import thread, time > > def doSomething(): > print "something" > > for i in range(2): > thread.start_new(doSomething, ()) > > causes IDLE to freeze when I type it in the interpreter. Using the > python command line everything works just fine. Using IDLE on Debian > linux also does not cause anything to crash. What am I overlooking? > > regards, Writser Cleveringa > > -- > http://mail.python.org/mailman/listinfo/python-list > From paul.hankin at gmail.com Thu Sep 20 18:26:29 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 20 Sep 2007 22:26:29 -0000 Subject: about __str__ In-Reply-To: References: Message-ID: <1190327189.852581.170580@57g2000hsv.googlegroups.com> On Sep 20, 10:08 pm, Konstantinos Pachopoulos wrote: > > The __str__ method of "list" doesn't seem to call the __str__ method of > the objects.... > ie, __str__ is not equicalent to the Java toString() method... Anyway, > how can i fix this? For whatever reason, __str__ of list calls repr rather than str on its elements. You can fix your code by adding __repr__ in your class: Class CmterIDCmts: def __init__ ... def __str__ ... __repr__ = __str__ -- Paul Hankin From bjourne at gmail.com Mon Sep 10 19:16:37 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 11 Sep 2007 01:16:37 +0200 Subject: [ANN] GtkImageView 1.5.0 and PyGtkImageView 1.0.0 -- Image viewer widget for GTK Message-ID: <740c3aec0709101616k10b57e89yd4af5ed1947e6ef4@mail.gmail.com> I'm pleased to finally announce GtkImageView 1.5.0. I'm even more pleased to ALSO announce PyGtkImageView 1.0.0: Description ----------- GtkImageView is a simple image viewer widget for GTK+. Similar to the image viewer panes in gThumb or Eye of Gnome. It makes writing image viewing and editing applications easy. Among its features are: * Mouse and keyboard zooming. * Scrolling and dragging. * Adjustable interpolation. * Fullscreen mode. * GIF animation support. * Ability to make selections. * Extensible using a tool system. PyGtkImageView is the Python bindings for the same thing. GtkImageView Download --------------------- Subversion: svn co http://publicsvn.bjourne.webfactional.com/gtkimageview Tarball: http://trac.bjourne.webfactional.com/attachment/wiki/WikiStart/gtkimageview-1.5.0.tar.gz API doc: http://trac.bjourne.webfactional.com/chrome/common/gtkimageview-docs/ PyGtkImageView Download ----------------------- Subversion: svn co http://publicsvn.bjourne.webfactional.com/pygtkimageview Tarball: http://trac.bjourne.webfactional.com/attachment/wiki/WikiStart/pygtkimageview-1.0.0.tar.gz API doc: http://trac.bjourne.webfactional.com/chrome/common/pygtkimageview-docs/ PDF: http://trac.bjourne.webfactional.com/attachment/wiki/WikiStart/pygtkimageview-1.0.0-api.pdf Project website: http://trac.bjourne.webfactional.com Examples -------- Here is the canonical example for using the widget:: #include #include ... GtkWidget *view = gtk_image_view_new (); GtkWidget *scroll = gtk_image_scroll_win_new (GTK_IMAGE_VIEW (view)); /* Where "box" is a GtkBox already part of your layout. */ gtk_box_pack_start (GTK_BOX (box), scroll, TRUE, TRUE, 0); GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file ("someimage.png", NULL); gtk_image_view_set_pixbuf (GTK_IMAGE_VIEW (view), pixbuf, TRUE); Same thing using PyGtkImageView:: import gtk import gtk.gdk import gtkimageview view = gtkimageview.ImageView() scroll = gtkimageview.ImageScrollWin(view) # Where "box" is a gtk.Box already part of your layout. box.pack_start(scroll) pixbuf = gtk.gdk.pixbuf_new_from_file("someimage.png") view.set_pixbuf(pixbuf) Future ------ * Perl bindings. * Gtk# bindings. * Haskell bindings. -- mvh Bj?rn From wesbrooks at gmail.com Wed Sep 5 06:26:24 2007 From: wesbrooks at gmail.com (Wesley Brooks) Date: Wed, 5 Sep 2007 11:26:24 +0100 Subject: concise code (beginner) In-Reply-To: <13dsvqrqivtf092@corp.supernews.com> References: <13dsvqrqivtf092@corp.supernews.com> Message-ID: Try adding all the functions into a list such as; funcList = [dev.read1, dev.read2, dev.read3] for func in funcList: for dev in devs: try: func() except: print exception remove dev from devs Wes. On 05/09/07, bambam wrote: > I have about 30 pages (10 * 3 pages each) of code like this > (following). Can anyone suggest a more compact way to > code the exception handling? If there is an exception, I need > to continue the loop, and continue the list. > > Steve. > > ----------------------------------- > for dev in devs > try: > dev.read1() > except > print exception > remove dev from devs > > for dev in devs > try: > dev.read2() > except > print exception > remove dev from devs > > for dev in devs > try: > dev.read3() > except > print exception > remove dev from devs > > etc. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From bignose+hates-spam at benfinney.id.au Sun Sep 16 20:50:08 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 17 Sep 2007 10:50:08 +1000 Subject: Python "with" References: Message-ID: <87odg22jzz.fsf@benfinney.id.au> Ivan Voras writes: > I know it can be almost always done by using a temporary variable: > > tmp = some.big.structure.or.nested.objects.element > tmp.member1 = something > tmp.member2 = something > > but this looks ugly to me.) To me, it looks explicit. Python programmers value explicit code. In other words, this looks like the right way to do it. The alternative you're looking for would be to make an implicit reference, which would make the code harder to follow. Note that in the specific case of an attribute of a module, the first lone of the above example can be rewritten as:: from some.big.package.or.nested.module import element as tmp which is at least as common as the assignment example above. -- \ "The only tyrant I accept in this world is the still voice | `\ within." -- Mahatma Gandhi | _o__) | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Sep 20 06:55:32 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 20 Sep 2007 12:55:32 +0200 Subject: I MEANT ONIX.... [it was Re: ONYX] In-Reply-To: <1190283378.175422.73290@r29g2000hsg.googlegroups.com> References: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> <46f1726f$0$15276$426a74cc@news.free.fr> <1190282489.824709.29050@r29g2000hsg.googlegroups.com> <1190283378.175422.73290@r29g2000hsg.googlegroups.com> Message-ID: <46f25191$0$29574$426a34cc@news.free.fr> korovev76 at gmail.com a ?crit : (top-post corrected) > On 20 Set, 12:01, korove... at gmail.com wrote: >> On 19 Set, 21:02, Bruno Desthuilliers >> >> wrote: >> >>> I don't know what's "onyx-style" xml, >> i'm not used to xml, so for meonyxis just a mess...http://www.onyx.com/Products/xml.asp > i'm such a lame... i meant onix... not onyx... > http://xml.coverpages.org/onix.html > > the questions remain the same ones... > > >>> but if it's xml, any xml parser >>> will parse it, and any validating parser should be able to validate it >>> given the correct DTD. >> For example?where do I find a good validating parser? First question : do you *really* need a validating parser ? Second question : did you try to google for "+Python +validating +XML +parser" From carsten at uniqsys.com Tue Sep 25 06:01:29 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 25 Sep 2007 06:01:29 -0400 Subject: obtaining multiple values from a function. In-Reply-To: <87zlzbrsih.fsf@rudin.co.uk> References: <1190708155.683502.93040@r29g2000hsg.googlegroups.com> <87sl53m90t.fsf@benfinney.id.au> <87zlzbrsih.fsf@rudin.co.uk> Message-ID: <1190714489.3402.8.camel@dot.uniqsys.com> On Tue, 2007-09-25 at 10:41 +0100, Paul Rudin wrote: > Going off on a tangent a bit, but I was idly considering the absence > of itertools.ireduce the other day. A problem is that reduce gives a > single result, so it's not clear what ireduce would do (perhaps why > it's not there). One obvious candidate would be to give the whole > sequence of partial reductions. I'm not sure if this would be > generally useful, but it would give a succinct way to do the Fibonacci > sequence: > > itertools.ireduce(operator.add, itertools.count()) Let's try it: >>> def ireduce(op, iterable, partial=0): ... for nxt in iterable: ... partial = op(partial, nxt) ... yield partial ... >>> import operator >>> from itertools import islice, count >>> >>> for x in islice(ireduce(operator.add, count()), 0, 10): ... print x ... 0 1 3 6 10 15 21 28 36 45 That's not the Fibonacci sequence. -- Carsten Haese http://informixdb.sourceforge.net From mail at microcorp.co.za Thu Sep 20 02:56:02 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 20 Sep 2007 08:56:02 +0200 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com><1190164166.378500.155990@o80g2000hse.googlegroups.com> <13f2hctdoob87e5@corp.supernews.com> Message-ID: <00f701c7fb59$3272e480$03000080@hendrik> "Steven D'Aprano" wrote: > > I think a better question is, how much faster/slower would Stein's code > be on today's processors, versus CPython being hand-simulated in a giant > virtual machine made of clockwork? This obviously depends on whether or not the clockwork is orange - Hendrik From zzbbaadd at aol.com Mon Sep 17 03:12:57 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 17 Sep 2007 00:12:57 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> <46e97917$0$9014$426a74cc@news.free.fr> Message-ID: <1190013177.473529.167770@o80g2000hse.googlegroups.com> > > > > Hi, I'm new to Python, I don't even fully know the language, never done > a full project in Python. What's more, probably I'll never will. > But that's not the point, the point is I want YOU people to modify the > language you know in and out, the program with which you've done many > systems, I want you to change it to suit my whims, so that I'll be > comfortable with the 3 ten liners I'll write. > TIA > > Hi, I've used Python and have fallen in love with it. I know exactly how Guido pronounces his name and since I saw him use the obtuse phrase syntactic sugar I try and work it into every discussion I have on Python syntax. I hate it when anyone offers criticism of Guido's language. I have a picture of Bruce Eckel with a red universal not sign over it on my wall and I throw my mechanical pencils at it every night. I am especially upset when someone talks bad about kluges like @staticmethod or FunctionName = staticmethod(FunctionName). Sure "def static" or "static def" would be so much cleaner, simpler and clearer but let's face it my fellow Pythonistas, this language may have started out based on what was easy for people to learn and use but we're in Nerdville now and clean and clear have become roadblocks! I have so much more respect for Perl and the way it developed now! From hniksic at xemacs.org Fri Sep 21 10:14:33 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 21 Sep 2007 16:14:33 +0200 Subject: __contains__() and overload of in : Bug or Feature ??? References: <1190383050.514560.232660@50g2000hsm.googlegroups.com> Message-ID: <87y7f0cdh2.fsf@mulj.homelinux.net> "sebastien.lannez at gmail.com" writes: >> The string "yop" evaluates to the boolean value True, as it is not >> empty. > > Does it means that when overloading an operator, python just > wrap the call to the method and keep control of the returned > values ??? In case of 'in' operator, it does. From kay.schluehr at gmx.net Mon Sep 24 06:23:22 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 24 Sep 2007 03:23:22 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <5lp64dF95s07U1@mid.uni-berlin.de> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> <1190454275.282176.90830@k79g2000hse.googlegroups.com> <46f6e9b0$0$32168$426a74cc@news.free.fr> <1190597548.214612.181140@22g2000hsm.googlegroups.com> <5lp64dF95s07U1@mid.uni-berlin.de> Message-ID: <1190629402.040102.175860@50g2000hsm.googlegroups.com> On Sep 24, 9:09 am, Marc 'BlackJack' Rintsch wrote: > Python: > > class B(object): > def __init__(self): > self.things = list() > > def add(self, thing): > self.things.append(thing) > > And Io: > > B := Object clone do( > init := method( > self things := list() > self > ) > > add := method(thing, > self things append(thing) > ) > ) > > The `init` is called by the default `clone` method automatically just like > `__init__()` in Python. It is really much like the class/instance > relationship in Python with just the line between class and instance > blurred. [...] > Ciao, > Marc 'BlackJack' Rintsch O.K. Marc, I'm convinced by the examples you presented. So init is also special in Io and is called at the clone event to fill object slots with data. Now I have to track back in the discussion thread to remember why we started to talk about Io... From gslindstrom at gmail.com Mon Sep 17 22:07:18 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 17 Sep 2007 21:07:18 -0500 Subject: Why 'class spam(object)' instead of class spam(Object)' ?7 Message-ID: > > Does the user care whether an object is implemented in C? > > Colin W. > > You're damn right I care! This is critical to just about everything I write because...well..I mean....well. I guess it isn't really all that important. Never mind. --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From shankarjee at gmail.com Wed Sep 12 17:00:52 2007 From: shankarjee at gmail.com (Shankarjee Krishnamoorthi) Date: Wed, 12 Sep 2007 16:00:52 -0500 Subject: File Parsing Question Message-ID: Hi, I am new to Python. I am trying to do the following inp = open(my_file,'r') for line in inp: # Perform some operations with line if condition something: # Start re reading for that position again for line in inp: if some other condition break # I need to go back one line and use that line value. # I need to perform the operations which are listed in the top with this line # value. I cannot push that operation here # I cannot do this with seek or tell. In Perl this is what I have while ( ){ # my_operations next if /pattern/ while () { operations again last if /pattern2/ } seek(inp,(-1-length),1) } This works perfectly in Perl. Can I do the same in Python. Thanks Jee From zzbbaadd at aol.com Mon Sep 10 17:11:37 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 10 Sep 2007 14:11:37 -0700 Subject: Enum class with ToString functionality In-Reply-To: <46e59bf7$0$21897$426a74cc@news.free.fr> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <1189425154.788466.132370@d55g2000hsg.googlegroups.com> <46e59bf7$0$21897$426a74cc@news.free.fr> Message-ID: <1189458697.707725.244980@g4g2000hsf.googlegroups.com> On Sep 8, 9:52 am, Bruno Desthuilliers wrote: > TheFlyingDutchman a ?crit : > > > > > On Sep 10, 2:28 am, bg... at yahoo.com wrote: > > >>Hi, > > >>I have the following class - > > >>class TestOutcomes: > >> PASSED = 0 > >> FAILED = 1 > >> ABORTED = 2 > > >>plus the following code - > > >>testResult = TestOutcomes.PASSED > > >>testResultAsString > >>if testResult == TestOutcomes.PASSED: > >> testResultAsString = "Passed" > >>elif testResult == TestOutcomes.FAILED : > >> testResultAsString = "Failed" > >>else: > >> testResultAsString = "Aborted" > > >>But it would be much nicer if I had a function to covert to string as > >>part of the TestOutcomes class. How would I implement this? > > >>Thanks, > > >>Barry > > > class TestOutcomes: > > PASSED = 0 > > FAILED = 1 > > ABORTED = 2 > > > def ToString(outcome): > > if outcome == TestOutcomes.PASSED: > > return "Passed" > > elif outcome == TestOutcomes.FAILED : > > return "Failed" > > else: > > return "Aborted" > > > ToString = staticmethod(ToString) > > > if __name__ == "__main__": > > testResult = TestOutcomes.PASSED > > testResultAsString = TestOutcomes.ToString(testResult) > > print testResultAsString > > print TestOutcomes.ToString(testResult) > > Technically correct, but totally unpythonic. Speaking of unpythonic, I would call ToString = staticmethod(ToString) A Perlific syntax. > > May I suggest some reading ?http://dirtsimple.org/2004/12/python-is-not-java.html Well the Foo.Foo complaint is bogus: from Foo import Foo From iclark at mail.ewu.edu Thu Sep 20 19:35:41 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Thu, 20 Sep 2007 16:35:41 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190330015.131971.265680@y42g2000hsy.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Sep 20, 5:46 pm, Paul Hankin wrote: >> On Sep 20, 10:59 pm, Python Maniac wrote: >> >>> I am new to Python however I would like some feedback from those who >>> know more about Python than I do at this time. >>> def scrambleLine(line): >>> s = '' >>> for c in line: >>> s += chr(ord(c) | 0x80) >>> return s >>> def descrambleLine(line): >>> s = '' >>> for c in line: >>> s += chr(ord(c) & 0x7f) >>> return s >>> ... >> Well, scrambleLine will remove line-endings, so when you're >> descrambling >> you'll be processing the entire file at once. This is particularly bad >> because of the way your functions work, adding a character at a time >> to >> s. >> >> Probably your easiest bet is to iterate over the file using read(N) >> for some small N rather than doing a line at a time. Something like: >> >> process_bytes = (descrambleLine, scrambleLine)[action] >> while 1: >> r = f.read(16) >> if not r: break >> ff.write(process_bytes(r)) >> >> In general, rather than building strings by starting with an empty >> string and repeatedly adding to it, you should use ''.join(...) >> >> For instance... >> def descrambleLine(line): >> return ''.join(chr(ord(c) & 0x7f) for c in line) >> >> def scrambleLine(line): >> return ''.join(chr(ord(c) | 0x80) for c in line) >> >> It's less code, more readable and faster! > > I would have thought that also from what I've heard here. > > def scrambleLine(line): > s = '' > for c in line: > s += chr(ord(c) | 0x80) > return s > > def scrambleLine1(line): > return ''.join([chr(ord(c) | 0x80) for c in line]) > > if __name__=='__main__': > from timeit import Timer > t = Timer("scrambleLine('abcdefghijklmnopqrstuvwxyz')", "from > __main__ import scrambleLine") > print t.timeit() > > ## scrambleLine > ## 13.0013366039 > ## 12.9461998318 > ## > ## scrambleLine1 > ## 14.4514098748 > ## 14.3594400695 > > How come it's not? Then I noticed you don't have brackets in > the join statement. So I tried without them and got > > ## 17.6010847978 > ## 17.6111472418 > > Am I doing something wrong? > >> -- >> Paul Hankin > > I got similar results as well. I believe the reason for join actually performing slower is because join iterates twice over the sequence. [1] The first time is to determine the size of the buffer to allocate and the second is to populate the buffer. Ian [1] http://mail.python.org/pipermail/python-list/2007-September/458119.html From attn.steven.kuo at gmail.com Tue Sep 11 01:46:34 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Mon, 10 Sep 2007 22:46:34 -0700 Subject: Mac OSX sqlite problem. Missing? In-Reply-To: <1189457469.285055.212670@r29g2000hsg.googlegroups.com> References: <1189455305.994439.107100@r34g2000hsd.googlegroups.com> <5klocbF498ruU1@mid.uni-berlin.de> <1189457469.285055.212670@r29g2000hsg.googlegroups.com> Message-ID: <1189489594.584753.312330@g4g2000hsf.googlegroups.com> On Sep 10, 1:51 pm, ricardo.turp... at gmail.com wrote: > Diez B. Roggisch wrote: > > > Are you by any chance using the python 2.3 when issuing that import > > statement? > > > Diez > > Unfortunately not :( > > ibook:~/project1$ python -V > Python 2.5 > ibook:~/project1$ python > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> import sqlite > > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named sqlite > > Isn't it sqlite3 (instead of sqlite)? Python 2.5.1c1 (r251c1:54692, Apr 17 2007, 21:12:16) [GCC 4.0.0 (Apple Computer, Inc. build 5026)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.Connection >>> sqlite3.Connection.__doc__ 'SQLite database connection object.' >>> I also see it under that name in the repository: http://svn.python.org/view/python/trunk/Lib/sqlite3/ -- Hope this helps, Steven From rschroev_nospam_ml at fastmail.fm Fri Sep 7 05:41:13 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 07 Sep 2007 09:41:13 GMT Subject: unexpected behavior: did i create a pointer? In-Reply-To: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> Message-ID: gu schreef: > copyOfA = a > > now, in the second "for" cycle and in functionA() i only 'touch' copyOfA > (altering it). copyOfA isn't a copy of a; it's a different name bound to the same object as a. You can verify that: id(a) and id(copyOfA) will return the same value. To make a copy of a (assuming a is a dict), you can do: copyOfA = dict(a) or copyOfA = a.copy() or more generally import copy copyOfA = copy.copy(a) Cheers, Roel -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From steve at holdenweb.com Thu Sep 6 07:52:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Sep 2007 04:52:11 -0700 Subject: interesting puzzle......try this you will be rewarded... In-Reply-To: <13dvn2q9qogq484@corp.supernews.com> References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> <13dvn2q9qogq484@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Thu, 06 Sep 2007 09:56:16 +0000, Renu wrote: > >> Hi, >> >> Just click on this link n use ur common sence to navigate. >> >> It has 23 pages one after the other, starting from this first >> Page. The trick is to find a way to go to the next page. > > [snip] > > In case it wasn't obvious, the site is nothing but adware. Banner ads, > google ads, text ads, blah blah blah. I stopped at page 1. > > I'm surprised you went even that far. It was pretty obviously going to be a click trap. Why bother? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From fw3 at hotmail.co.jp Fri Sep 7 13:37:00 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Fri, 07 Sep 2007 17:37:00 +0000 Subject: Speed of Python In-Reply-To: <1189185542.798286.168880@50g2000hsm.googlegroups.com> Message-ID: Hi, Here is the matlab code: function [z]=bench1(n) for i=1:n, for j=1:1000, z=log(j); z1=log(j+1); z2=log(j+2); z3=log(j+3); z4=log(j+4); z5=log(j+5); z6=log(j+6); z7=log(j+7); z8=log(j+8); z9=log(j+9); end end z = z9; I am not familiar with python, so I just simply try to reproduce the same code in python. If you think that my python script is not efficient, could you tell me how to make it more efficient? Thanks Frank >From: Roberto Bonvallet >To: python-list at python.org >Subject: Re: Speed of Python >Date: Fri, 07 Sep 2007 17:19:02 -0000 > >On Sep 7, 12:42 pm, "wang frank" wrote: > > Here is the bench1.py: > > import math > > def bench1(n): > > for i in range(n): > > for j in range(1000): > > m=j+1 > > z=math.log(m) > > z1=math.log(m+1) > > z2=math.log(m+2) > > z3=math.log(m+3) > > z4=math.log(m+4) > > z5=math.log(m+5) > > z6=math.log(m+6) > > z7=math.log(m+7) > > z8=math.log(m+8) > > z9=math.log(m+9) > > return z9 > > > > Is my conclusion correct that Python is slower than matlab? > >Show us your Matlab code in order to see if both are equivalent. >Your Python code creates n lists of 1000 elements, so you're not >actually >measuring only the numeric computations. > >Cheers, >-- >Roberto Bonvallet > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ ??????????????????????????????????? http://messenger.live.jp/ From whamil1 at entergy.com Tue Sep 11 07:40:28 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 11 Sep 2007 06:40:28 -0500 Subject: Checking if elements are empty In-Reply-To: Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB39@LITEXETSP001.etrsouth.corp.entergy.com> > From: Steve Holden > Neil Cerutti wrote: > > On 2007-09-10, Chris Mellon wrote: > >> On 9/10/07, Neil Cerutti wrote: > >>> Agreed; but I prefer 'if y[0] == ""', absent more context and > >>> better names. > >> Probably should use u"" if you're going to take that route, as > >> this will fail spuriously if y[0] contains a unicode string > >> that can't be implicitly converted to ascii. Personally, I > >> prefer the boolean check and I'll let operations fail elsewhere > >> if there's a type mismatch. > > > > I have a quibble not with the functionality of the boolean check, > > but with its expressiveness. if y[0] == "" expresses more, i.e., > > that I expect y[0] to contain a Python byte string. > > > I have a quibble with a test that will raise an exception when the > anticipated condition is true. Your test is patently absurd, as you > would have discovered had you bothered to try it: > > >>> y = "" > >>> if y[0] == "": > ... print "True" > ... else: > ... print "False" > ... > Traceback (most recent call last): > File "", line 1, in > IndexError: string index out of range > >>> > > Further, when the string is *not* the null string the test will always > return False, as you will be comparing two strings of unequal length. > > So, absent a solution that works, len(y) == 0 looks pretty good. Going back to the OP, the problem is taking a string such as >>> x = ' \t"ff' then splitting that string like this >>> y = x.split('\t') The question is, does the first element of the list y contain an empty string or not? In this case, the logic in the following conditional is perfectly valid. >>> if y[0] == "": ... print "True" ... else ... print "False" (len(y[0]) == 0) would also work, and is the solution you originally gave the OP. -- -Bill Hamilton From nick at craig-wood.com Thu Sep 20 05:30:16 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 20 Sep 2007 04:30:16 -0500 Subject: compile for ARM References: <5ld5avF7ne3mU1@mid.uni-berlin.de> <1190226961.806875.205530@i13g2000prf.googlegroups.com> <1190242283.372338.253440@22g2000hsm.googlegroups.com> Message-ID: Paul Boddie wrote: > On 19 Sep, 20:36, Paul McGuire wrote: > The inquirer might also consider crosstool, which is good at building > cross-compilers for GNU/Linux targeting "Embedded Linux": > > http://www.kegel.com/crosstool/ > > As for building Python itself, searching the Python bug tracker for > "cross-compile" might provide some patches and advice: You could also do the build using qemu which can emulate an ARM system. Debian do a complete ARM userspace, so you can install that under qemu and do native builds. Cross compilers work well though - we build our app which has python embedded for ARM using a cross compiler running under debian. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From namesagame-usenet at yahoo.com Thu Sep 13 12:25:49 2007 From: namesagame-usenet at yahoo.com (gamename) Date: Thu, 13 Sep 2007 09:25:49 -0700 Subject: Python+Expect+Win32 = Not Possible? In-Reply-To: <1189684296.283237.286220@g4g2000hsf.googlegroups.com> References: <1189657637.539038.317280@k79g2000hse.googlegroups.com> <1189684296.283237.286220@g4g2000hsf.googlegroups.com> Message-ID: <1189700749.642756.27830@o80g2000hse.googlegroups.com> On Sep 13, 4:51 am, Philem wrote: > On Sep 13, 12:27 am, gamename wrote: > > > Hi, > > > Is it still the case there is no practical Expect-like module for > > win32? I know that cygwin can support pexpect, but that isn't an > > option here --- I have to use a native win32 Python version. > > > Are there alternatives, or is it simply not an option to replicate > > Expect on win32 with python? > > > All I'm trying to do is start a couple processes, wait for each to say > > "done" on stdout and then quit (or timeout if something went wrong). > > > TIA, > > -T > > You could try this link:http://www.activestate.com/Products/activetcl/features.plex > and see if that gives you what you need. It absolutely gives me what I need. But the requirement is to use Python specifically. :) Tcl is a great language, but not an option in this case. > > Luck! > -J From steve at REMOVE-THIS-cybersource.com.au Fri Sep 7 22:58:33 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Sep 2007 02:58:33 -0000 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> <7x3axq7a8a.fsf@ruckus.brouhaha.com> <7xodgejx3l.fsf@ruckus.brouhaha.com> Message-ID: <13e43ups034ld13@corp.supernews.com> On Fri, 07 Sep 2007 08:47:58 -0700, Paul Rubin wrote: > Paul Rubin writes: >> def unique_id(): >> return os.urandom(10).encode('hex') > > Sorry, make that 32 or 40 instead of 10, if the number of id's is large, > to make birthday collisions unlikely. I did a small empirical test, and with 16 million ids, I found no collisions. However, I did find that trying to dispose of a set of 16 million short strings caused my Python session to lock up for twenty minutes until I got fed up and killed the process. Should garbage-collecting 16 million strings really take 20+ minutes? > If you don't want the id's to be that large, you can implement a Feistel > cipher using md5 or sha as the round function pretty straightforwardly, > then just feed successive integers through it. That also guarantees > uniqueness, at least within one run of the program. I have some sample > code around for that, let me know if you need it. I'm not sure that I need it, but I would certainly be curious to see it. Thanks, -- Steven. From ebgssth at gmail.com Sat Sep 15 08:51:20 2007 From: ebgssth at gmail.com (js) Date: Sat, 15 Sep 2007 21:51:20 +0900 Subject: how to join array of integers? In-Reply-To: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> Message-ID: print ''.join([str(i) for i in [1,2,3]]) On 9/15/07, Summercool wrote: > i think in Ruby, if you have an array (or list) of integers > > foo = [1, 2, 3] > > you can use foo.join(",") to join them into a string "1,2,3" > > in Python... is the method to use ",".join() ? but then it must take > a list of strings... not integers... > > any fast method? > > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Sat Sep 15 23:29:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 15 Sep 2007 23:29:25 -0400 Subject: List append In-Reply-To: References: <1189826727.204061.310380@d55g2000hsg.googlegroups.com> Message-ID: Rob E wrote: > On Sat, 15 Sep 2007 03:25:27 +0000, mouseit wrote: > >> I'm trying to add an element to a list which is a property of an >> object, stored in an array. When I append to one element, all of the >> lists are appended! >> >> Example Code: >> >> class Test: >> array = [] >> >> myTests = [Test() , Test() , Test()] >> print len(myTests[1].array) >> myTests[0].array.append( 5 ) >> print len(myTests[1].array) >> >> prints: >> 0 >> 1 >> >> This is probably a really easy question (I'm very new to python), so >> thanks in advance for your help! > > Yes, that's easy: > > class myclass: > var1 = [] > > means that var1 is associated with the class. If you want an attribute: > > class myclass: > def __init__ (self): > self.var1 = [] > > is the correct way. > It's easy to get confused, though, because when you try to access an instance attribute, if the attribute isn't found in the instance the interpreter will then look in the class, and then (if there is one) in the class's superclass, and so on. A further complication arises with methods, since even when the method is acquired by inheritance it is bound to the instance. >>> class Mine(object): ... pass ... >>> Mine.__init__ >>> mine = Mine() >>> mine.__init__ >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From carsten at uniqsys.com Mon Sep 10 09:31:10 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 10 Sep 2007 09:31:10 -0400 Subject: encoding latin1 to utf-8 In-Reply-To: <1189429907.971736.307210@57g2000hsv.googlegroups.com> References: <1189427146.723304.270600@22g2000hsm.googlegroups.com> <1189429907.971736.307210@57g2000hsv.googlegroups.com> Message-ID: <1189431070.3385.28.camel@dot.uniqsys.com> On Mon, 2007-09-10 at 13:11 +0000, Harshad Modi wrote: > thx for Reply , > but I need some basic knowledge . how to encoding ? which algorithm > use for that . bz my data has some special char , i have not > confidence this function got proper result. i want to make my own > function / script for encoding. For basic knowledge about Unicode and character encodings, I highly recommend amk's excellent Unicode How-To here: http://www.amk.ca/python/howto/unicode Once you've read and understood the How-To, I suggest you examine the following: 1) Are you *sure* that the special characters in the original file are latin-1 encoded? (If you're not sure, try to look at the file in a HEX editor to see what character codes it uses for the special characters). 2) Are you sure that what you were using to look at the result file understands and uses UTF-8 encoding? How are you telling it to use UTF-8 encoding? Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From steve at REMOVE-THIS-cybersource.com.au Thu Sep 20 00:16:33 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Sep 2007 04:16:33 -0000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <87k5qn5cwi.fsf@mulj.homelinux.net> <87y7f2w0xj.fsf@benfinney.id.au> <13f3pbfh7to7k4b@corp.supernews.com> <873axavwhi.fsf@benfinney.id.au> Message-ID: <13f3t11ql8s5c16@corp.supernews.com> On Thu, 20 Sep 2007 13:36:41 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> On Thu, 20 Sep 2007 12:00:40 +1000, Ben Finney wrote: >> >> > In its latter form, it is worthless to me when I'm looking for "get >> > superclass of A", but its name and parameters and documentation all >> > lead me very strongly to believe otherwise. >> >> Why are you looking for the superclass of A? > > Currently irrelevant to the point. Whether for good or bad reasons, I > looked for a way to "get the superclass of A". A.__base__ and A.__bases__ are, I believe, the "right" way to do that. > Everything about 'super' > ? its name, parameter semantics, and documentation ? all firmly led me > to believe that was the correct function for that purpose. Name, I can accept. Parameter semantics? That's borderline. "Get the superclass of A" looks like it should take ONE and ONLY one argument, namely A. super() typically takes two arguments, and only in non-typical use does it take a single argument. And documentation? From help(super): class super(object) | super(type) -> unbound super object | super(type, obj) -> bound super object; requires isinstance(obj, type) | super(type, type2) -> bound super object; requires issubclass(type2, type) | Typical use to call a cooperative superclass method: | class C(B): | def meth(self, arg): | super(C, self).meth(arg) Hmmm... it says it returns a super object, not a type or a class and certainly not "the superclass". It doesn't say what a super object actually is, but it doesn't say it is a type, or it would say "returns a type object". Nor does it say it returns the superclass -- it doesn't even use the term, with or without the hyphen. And with a typical example shown right there, so close to the top, the documentation is pretty clear that super() doesn't do what you imagined it does. So while I accept that the name of super() is misleading, I don't accept that the documentation is misleading. Incomplete, yes, hard to understand, yes, but not misleading. At least, it didn't mislead _me_, and I'm pretty gullible sometimes... *wink* -- Steven. From sajmikins at gmail.com Thu Sep 27 22:18:21 2007 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 27 Sep 2007 19:18:21 -0700 Subject: cute use of lambda Message-ID: <1190945901.551940.165240@k79g2000hse.googlegroups.com> class FakeQueue(list): put = list.append get = lambda self: self.pop(0) ;] From steve at holdenweb.com Sun Sep 16 18:42:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Sep 2007 18:42:20 -0400 Subject: Processing drag & drop on the desktop In-Reply-To: <200709162124.38761.forty-two@is.nonze.ro> References: <1189961614.510561.194610@w3g2000hsg.googlegroups.com> <200709162124.38761.forty-two@is.nonze.ro> Message-ID: Thomas Jollans wrote: > On Sunday 16 September 2007, Pierre Quentel wrote: >> Hi all, >> >> I would like to create an application on a Windows machine, such that >> when a document is dragged and dropped on the application icon on the >> desktop, the document is processed by the application >> >> For instance, if I drag & drop an Outlook message or a PPT >> presentation, the application would propose to tag the document with >> keywords taken from a database >> >> Is it possible to do this with a Python script, and how ? > > Maybe the file name is passed as a command-line argument ? > This may give you some information that help, but it's not file-based. You should be able to at least use it to explore the interface to Windows Explorer, though: http://fraca7.free.fr/blog/index.php?2006/11/15/53-thunderbird-drag-and-drop-with-wxpython regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From stefan.behnel-n05pAM at web.de Tue Sep 25 03:50:26 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 25 Sep 2007 09:50:26 +0200 Subject: Google and Python In-Reply-To: References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com><1190231094.276099.136250@22g2000hsm.googlegroups.com><1190235678.019823.315850@o80g2000hse.googlegroups.com><7xejgr68pm.fsf@ruckus.brouhaha.com> Message-ID: <46F8BDC2.40101@web.de> Hendrik van Rooyen wrote: > "Nick Craig-Wood" wrote: > >> Passing file descriptors between processes is one of those things I've >> always meant to have a go with, but the amount of code (in Advanced >> Programming in the Unix Environment) needed to implement it is rather >> disconcerting! A python module to do it would be great! > > I must be missing something here. > > What is the advantage of passing the open file rather than just the > fully qualified file name and having the other process open the > file itself? A "file descriptor" under Unix is not necessarily an open file that you can find on the hard-disk. It might also be a socket connection or a pipe, or it might be a file that was opened or created with specific rights or in an atomic step (like temporary files). Many things are (or look like or behave like) files in Unix, that's one of its real beauties. Stefan From steveo at syslang.net Fri Sep 21 11:07:23 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 21 Sep 2007 11:07:23 -0400 (EDT) Subject: An Editor that Skips to the End of a Def In-Reply-To: <87hclpjm3a.fsf@rudin.co.uk> References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> Message-ID: On Thursday, Sep 20th 2007 at 18:14 +0100, quoth Paul Rudin: =>"W. Watson" writes: => =>> Thanks, but no thanks. The learning curve is way too steep. => =>Up to you but, these days emacs comes with all sorts of =>pointing-clicky-menu-y type things - you don't really have to learn =>anything to get started. => =>(It even gives useful advice on top-posting if you use it as a news =>client :/) Vuts det? Iz no longer Editor Mit Aggravating Control Sequencez? ;-) -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From bj_666 at gmx.net Sat Sep 1 15:53:47 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Sep 2007 19:53:47 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <1i3ob5k.dm3jmoqx1z68N%aleax@mac.com> Message-ID: <5jtuabF16jr4U1@mid.uni-berlin.de> On Sat, 01 Sep 2007 13:44:28 -0600, Michael L Torrie wrote: > Alex Martelli wrote: > >> is the "one obvious way to do it" (the set(...) is just a simple and >> powerful optimization -- checking membership in a set is roughly O(1), >> while checking membership in a list of N items is O(N)...). > > Depending on a how a set is stored, I'd estimate any membership check in > a set to be O(log N). Sets are stored as hash tables so membership check is O(1) just like Alex said. Ciao, Marc 'BlackJack' Rintsch From mahs at telcopartners.com Thu Sep 20 19:13:54 2007 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 20 Sep 2007 16:13:54 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190325588.608625.259800@q3g2000prf.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> Message-ID: Python Maniac wrote: > I am new to Python however I would like some feedback from those who > know more about Python than I do at this time. > > def scrambleLine(line): > s = '' > for c in line: > s += chr(ord(c) | 0x80) > return s > > def descrambleLine(line): > s = '' > for c in line: > s += chr(ord(c) & 0x7f) > return s > Try using str.translate instead - it's usually much faster than a pure python loop: >>> scramble = "".join(chr(c | 0x80) for c in range(256)) >>> "source text".translate(scramble) '\xf3\xef\xf5\xf2\xe3\xe5\xa0\xf4\xe5\xf8\xf4' >>> descramble = "".join(chr(c & 0x7F) for c in range(256)) >>> '\xf3\xef\xf5\xf2\xe3\xe5\xa0\xf4\xe5\xf8\xf4'.translate(descramble) 'source text' >>> You might then do the translation inline e.g., untested: > def scrambleFile(fname,action=1): translators = {0: descramble, 1: scramble} # defined as above try: translation_action = translators[action] except KeyError: raise ValueError("action must be 0 or 1") > if (path.exists(fname)): ... ... for line in f: ff.write(line.translate(translation_action)) ... HTH Michael From vriolk at gmail.com Sat Sep 22 19:11:17 2007 From: vriolk at gmail.com (coldpizza) Date: Sat, 22 Sep 2007 16:11:17 -0700 Subject: database persistence with mysql, sqlite Message-ID: <1190502677.970811.181100@22g2000hsm.googlegroups.com> Hi, I want to run a database query and then display the first 10 records on a web page. Then I want to be able to click the 'Next' link on the page to show the next 10 records, and so on. My question is how to implement paging, i.e. the 'Next/Prev' NN records without reestablishing a database connection every time I click Next/Prev? Is it at all possible with cgi/mod_python? For example, in a NON-web environment, with sqlite3 and most other modules, I can establish a database connection once, get a cursor object on which I run a single 'SELECT * FROM TABLE' statement and then use cursor.fetchmany(NN) as many times as there are still results left from the initial query. How do I do the same for the web? I am not using any high-level framework. I am looking for a solution at the level of cgi or mod_python (Python Server Pages under Apache). To call cursor.fetchmany(NN) over and over I need to pass a handle to the database connection but how do I keep a reference to the cursor object across pages? I use mysql and sqlite3 as databases, and I am looking for an approach that would work with both database types (one at a time). So far I have successfully used the following modules for database access: sqlite3, mysqld, and pyodbc. So far, with mysql I use 'SELECT * FROM TABLE LIMIT L1, L2' where L1 and L2 define the range for the 'Next' and 'Previous' commands. I have to run the query every time a click a 'Next/Prev' link. But I am not sure that this is the best and most efficient way. I suppose using CURSOR.FETCHMANY(NN) would probably be faster and nicer but how do I pass an object reference across pages? Is it possible without any higher-level libraries? What would be the proper way to do it on a non-enterprise scale? Would SqlAlchemy or SqlObject make things easier with regard to database persistence? From deets at nospam.web.de Mon Sep 10 15:35:56 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Sep 2007 21:35:56 +0200 Subject: Getting error zipimport.ZipImportError: can't decompress data; zlib not available In-Reply-To: <1189452462.021120.199680@50g2000hsm.googlegroups.com> References: <1189452462.021120.199680@50g2000hsm.googlegroups.com> Message-ID: <5klkldF4du6mU2@mid.uni-berlin.de> shabda raaj schrieb: > I have a VPS server with fedora 7. > I wanted to install easy_install on this server, but I got an error > saying > unable to open /usr/lib/ > python2.5/config/Makefile (No such file or > directory). > So I installed the latest version of python from source. > Now when I am trying to install libraries, I am getting an error like, > "zipimport.ZipImportError: can't decompress data; zlib not available" You'd better install the python-devel-package of the fedora-python. Then the first attempt should work, and you can forget about the self-compiled version. Diez From gagsl-py2 at yahoo.com.ar Fri Sep 28 01:09:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Sep 2007 02:09:58 -0300 Subject: Asynchronous Messaging References: <1190807252.731074.141450@k79g2000hse.googlegroups.com> <1190819912.344267.52680@50g2000hsm.googlegroups.com> <1190868212.383316.20990@57g2000hsv.googlegroups.com> <1190951577.293881.44040@r29g2000hsg.googlegroups.com> Message-ID: En Fri, 28 Sep 2007 00:52:57 -0300, wink escribi?: > Interesting, from the documentation for deque says; > "Deques support thread-safe, ..." which would seem to > imply a mutex of some sort would be used. But in > looking at collectionsmodule.c for 2.5.1 I don't see > any mutex which would seem to imply there is one > place else, maybe the GIL, or the documentation is > incorrect. Uh, I had never noticed that append/pop claimed to be thread safe. Ok, they don't appear to call any Python code, neither Py_DECREF is used, so the GIL would make those methods thread safe, I think. R. Hettinger, any comments? -- Gabriel Genellina From pavlovevidence at gmail.com Wed Sep 12 19:41:12 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Sep 2007 16:41:12 -0700 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1i4c3p7.1o7gssi1ws1xa2N%aleax@mac.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> <1i4bnbp.1l8sr3mjdojghN%aleax@mac.com> <1189630374.506503.190690@r34g2000hsd.googlegroups.com> <1i4c3p7.1o7gssi1ws1xa2N%aleax@mac.com> Message-ID: <1189640472.939618.281820@g4g2000hsf.googlegroups.com> On Sep 12, 7:23 pm, al... at mac.com (Alex Martelli) wrote: > Carl Banks wrote: > > ... > > > How about this? The decorator could generate a bytecode wrapper that > > would have the following behavior, where __setlocal__ and > > __execute_function__ are special forms that are not possible in > > Python. (The loops would necessarily be unwrapped in the actual > > bytecode.) > > I'm not entirely sure how you think those "special forms" would work. > > Right now, say, if the compiler sees somewhere in your function > z = 23 > print z > it thereby knows that z is a local name, so it adds a slot to the > function's locals-array, suppose it's the 11th slot, and generates > bytecode for "LOAD_FAST 11" and "STORE_FAST 11" to access and bind that > 'z'. (The string 'z' is stored in f.func_code.co_varnames but is not > used for the access or storing, just for debug/reporting purposes; the > access and storing are very fast because they need no lookup). > > If instead it sees a "print z" with no assignment to name z anywhere in > the function's body, it generates instead bytecode "LOAD_GLOBAL `z`" > (where the string `z` is actually stored in f.func_code.co_names). The > string (variable name) gets looked up in dict f.func_globals each and > every time that variable is accessed or bound/rebound. Withdrawn. For some reason it was in my mind that variables not bound within in the function would be local. :| [snip] > > This wouldn't be that much slower than just assigning local variables > > to locals by hand, and it would allow assignments in the > > straightforward way as well. > > The big performance hit comes from the compiler having no clue about > what you're doing (exactly the crucial hint that "assigning local > variables by hand" DOES give the compiler;-) Right. Carl Banks From me_zara at dea.spamcon.org Mon Sep 10 06:27:52 2007 From: me_zara at dea.spamcon.org (Zara) Date: Mon, 10 Sep 2007 12:27:52 +0200 Subject: Enum class with ToString functionality References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> Message-ID: <1r6ae3tuv8rj19ka3b2tpqsni29v48b7p5@4ax.com> On Mon, 10 Sep 2007 02:28:57 -0700, bg_ie at yahoo.com wrote: >Hi, > >I have the following class - > >class TestOutcomes: > PASSED = 0 > FAILED = 1 > ABORTED = 2 > >plus the following code - > >testResult = TestOutcomes.PASSED > >testResultAsString >if testResult == TestOutcomes.PASSED: > testResultAsString = "Passed" >elif testResult == TestOutcomes.FAILED : > testResultAsString = "Failed" >else: > testResultAsString = "Aborted" > >But it would be much nicer if I had a function to covert to string as >part of the TestOutcomes class. How would I implement this? > You should implement __str__ (or __repr__) method in your class, class TestOutcomes: PASSED = 0 FAILED = 1 ABORTED = 2 def __str__(self): textResultAsString="Unknown" if testResult == TestOutcomes.PASSED: testResultAsString = "Passed" elif testResult == TestOutcomes.FAILED : testResultAsString = "Failed" else: testResultAsString = "Aborted" return testResultAsString Regards, Zara From per9000 at gmail.com Mon Sep 24 03:04:07 2007 From: per9000 at gmail.com (per9000) Date: Mon, 24 Sep 2007 00:04:07 -0700 Subject: annoying stdin/stdout + pipes problem In-Reply-To: <46f69324$0$90263$14726298@news.sunsite.dk> References: <1190554821.677666.93530@w3g2000hsg.googlegroups.com> <46f69324$0$90263$14726298@news.sunsite.dk> Message-ID: <1190617447.995633.48480@n39g2000hsh.googlegroups.com> On 23 Sep, 18:24, Damjan wrote: > > I want to create a program that reads input from stdio that can prompt > > a user for input while doing so without getting into problems. > ... > > The trick (which works on Linux for sure) is to open /dev/tty and ask > question/get input on/from it. > ... > > I'm not usre for other *nix-es, and on Windows this will surelly not work > -- > damjan Thanks, it worked just fine on my Gnu/Linux machine, but I'd really like it to be independent of OS. Any one else got some idea - or a windows version of the same? /Per -- PS: for the record: ***>cat replace3.py && echo "---" && cat input.txt | python replace3.py from sys import stdin, stdout def censor(foo, bar, input): return input.replace(foo, bar) fp = open('/dev/tty', 'r+') fp.write('Remove what? ') i = fp.readline().strip() fp.write('Replace %s with what? ' %i) o = fp.readline().strip() fp.close() for line in stdin.xreadlines(): line = censor('foo', 'candy', line) line = censor('bar', 'donkey', line) line = censor('baz', 'hare rama', line) line = censor(i, o, line) stdout.write(line) --- Remove what? black Replace black with what? beige candy donkey hare rama fudonkey donkeyooba xyxxyt raboof txet beige knight From steven.bethard at gmail.com Fri Sep 28 19:36:02 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Sep 2007 17:36:02 -0600 Subject: Numeric command-line options vs. negative-number arguments In-Reply-To: <1191021181.401767.41040@n39g2000hsh.googlegroups.com> References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <0a6dnQmBPIzuqmHbnZ2dnUVZ_vihnZ2d@comcast.com> <87ejgj4lpy.fsf_-_@benfinney.id.au> <87wsub2s4w.fsf@benfinney.id.au> <1191021181.401767.41040@n39g2000hsh.googlegroups.com> Message-ID: <8_adnam3nq95EmDbnZ2dnUVZ_qSonZ2d@comcast.com> Carl Banks wrote: > On Sep 28, 9:51 am, Steven Bethard wrote: >> It was decided that practicality beats purity here. Arguments with >> leading hyphens which look numeric but aren't in the parser are >> interpreted as negative numbers. Arguments with leading hyphens which >> don't look numeric and aren't in the parser raise errors. Sure, it's not >> the pure answer, but it's the practical answer: "-123" is much more >> likely to be a negative number than an option. > > What if (for example) you define a option "-3", and also accept > numerical arguments on the command line. Then you could get sudden > unexpected behavior if you input the wrong number: > > "./hello -1" works ok. > "./hello -2" works ok. > "./hello -3" ... whoops, now the negative number is suddenly an > option. > > Granted, it would be stupid for a program to do that, but it suggests > to me that it's probably a good idea to treat all negative numbers the > same. I.e. if there are any numerical options, then all negative > numbers are treated as options. If there are none, then negative > numbers are treated as numbers. That's probably a good guideline. Anyone mixing numeric flags with negative number arguments is asking for an exception of some sort. ;-) I'm going to let it sit for a while and think about it, but I'll probably make that change in the next release. STeVe From hall.jeff at gmail.com Sat Sep 29 12:49:37 2007 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Sat, 29 Sep 2007 16:49:37 -0000 Subject: Program inefficiency? In-Reply-To: <13fsvsp6p743qba@corp.supernews.com> References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> <13fss68juscn33@corp.supernews.com> <1191080844.248426.316340@g4g2000hsf.googlegroups.com> <13fsvsp6p743qba@corp.supernews.com> Message-ID: <1191084577.091823.88960@57g2000hsv.googlegroups.com> no swaps... memory usage is about 14k (these are small Html files)... no hard drive cranking away or fan on my laptop going nutty... CPU usage isn't even pegged... that's what makes me think it's not some sort of bizarre memory leak... Unfortunately, it also means I'm out of ideas... From rafael81 at dif.um.es Wed Sep 19 12:42:24 2007 From: rafael81 at dif.um.es (Rafael Marin Perez) Date: Wed, 19 Sep 2007 18:42:24 +0200 Subject: compile for ARM Message-ID: <1190220144.11755.13.camel@rapema-desktop> Hello I'm Rafael Marin, and work as reseacher in University of Murcia (Spain). I want to install and compile modules of python2.4 in a ARMv5b architecture. Any idea? Thank for your time. Regards, Rafa. From nick at craig-wood.com Mon Sep 24 04:30:11 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 24 Sep 2007 03:30:11 -0500 Subject: Google and Python References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> <7xejgr68pm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > David writes: > > Another method is for the apps to run continuously and serve on non-80 > > port (or on 80 from another host), and your main web server on port 80 > > reverse proxies to it when appropriate. > > You can also pass the open sockets around between processes instead of > reverse proxying, using the SCM_RIGHTS message on Unix domain sockets > under Linux, or some similar mechanism under other Unixes (no idea > about Windows). Python does not currently support this but one of > these days I want to get around to writing a patch. An interesting idea! Are there any web servers which work like that at the moment? Passing file descriptors between processes is one of those things I've always meant to have a go with, but the amount of code (in Advanced Programming in the Unix Environment) needed to implement it is rather disconcerting! A python module to do it would be great! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From aleax at mac.com Tue Sep 18 01:24:10 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 17 Sep 2007 22:24:10 -0700 Subject: can Python be useful as functional? References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Message-ID: <1i4lvih.8g4kwjijx8e2N%aleax@mac.com> Rustom Mody wrote: > Can someone help? Heres the non-working code > > def si(l): > p = l.next() > yield p > (x for x in si(l) if x % p != 0) > > There should be an yield or return somewhere but cant figure it out Change last line to for x in (x for x in si(l) if x % p != 0): yield x if you wish. Alex From rschroev_nospam_ml at fastmail.fm Wed Sep 19 04:28:38 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 19 Sep 2007 08:28:38 GMT Subject: The meaning of a = b in object oriented languages In-Reply-To: <_4OdnQi5jow61m3bnZ2dnUVZ_tvinZ2d@comcast.com> References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> <_4OdnQi5jow61m3bnZ2dnUVZ_tvinZ2d@comcast.com> Message-ID: Lew schreef: > Roel Schroeven wrote: >> Laurent Pointal schreef: >>> Summercool a ?crit : >>>> The meaning of a = b in object oriented languages. >>>> ==================================================== >>> >>> >>> Oups, reading the subject I thought it was a Xah Lee post. >> me too ... > > Nah, this dude's all right, so far. As if my opinion mattered. > > Stay with it, Summercool. It's what discussion groups are for. > > Here's why the reaction: cross-posting of computer-science-type essays, > something Xah Lee does. But he recycles all his decades-old crap and really > doesn't participate in the discussion. This isn't that at all. I fully agree and I didn't in any way mean to compare Summercool to Xah Lee. My apologies to Summercool if anyone interpreted it that way. It's just that somehow the subject seems to follow the same template as what I've become used to from Xah Lee. I almost skipped reading the post because of that. Once I started reading it though, it became immediately clear that it was not comparable to Xah Lee's postings in any way, shape or form. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From andrewblakeslee at gmail.com Fri Sep 28 17:27:58 2007 From: andrewblakeslee at gmail.com (AndyB) Date: Fri, 28 Sep 2007 17:27:58 -0400 Subject: Checking for the existence of Duplicates Message-ID: I have found a lot of material on removing duplicates from a list, but I am trying to find the most efficient way to just check for the existence of duplicates in a list. Here is the best I have come up with so far: CheckList = [x[ValIndex] for x in self.__XRList[z]] FilteredList = filter((lambda x:x != 0),CheckList) if len(FilteredList) > len(sets.Set(FilteredList)): return False The first statement pulls the slice out of a matrix I need to check. The filter statement gets rid of zeroes (they don't count as duplicates). The if statement is the actual duplicates check This is in a program that generates random numbers to do a brute force solve on a sudoku-like puzzle. Once a certain level of difficulty in the puzzle is reached, performance goes off a cliff because the duplicate checking code, although fast, is executed so many times. From rschroev_nospam_ml at fastmail.fm Sat Sep 22 04:47:36 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 22 Sep 2007 08:47:36 GMT Subject: Newbie completely confused In-Reply-To: References: Message-ID: Jeroen Hegeman schreef: > ...processing all 2 files found > --> 1/2: ./test_file0.txt > Now reading ... > DEBUG readLines A took 0.093 s > ...took 8.85717201233 seconds > --> 2/2: ./test_file0.txt > Now reading ... > DEBUG readLines A took 3.917 s > ...took 12.8725550175 seconds > > So the first time around the file gets read in in ~0.1 seconds, the > second time around it needs almost four seconds! As far as I can see > this is related to 'something in memory being copied around' since if > I replace the 'alternative 1' by the 'alternative 2', basically > making sure that my classes are not used, reading time the second > time around drops back to normal (= roughly what it is the first pass). (First, I had to add timing code to ReadClasses: the code you posted doesn't include them, and only shows timings for ReadLines.) Your program uses quite a bit of memory. I guess it gets harder and harder to allocate the required amounts of memory. If I change this line in ReadClasses: built_classes[len(built_classes)] = HugeClass(long_line) to dummy = HugeClass(long_line) then both times the files are read and your data structures are built, but after each run the data structure is freed. The result is that both runs are equally fast. Also, if I run the first version (without the dummy) on a computer with a bit more memory (1 GiB), it seems there is no problem allocating memory: both runs are equally fast. I'm not sure how to speed things up here... you're doing much processing on a lot of small chunks of data. I have a number of observations and possible improvements though, and some might even speed things up a bit. You read the files, but don't use the contents; instead you use long_line over and over. I suppose you do that because this is a test, not your actual code? __init__() with nothing (or only return) in it is not useful; better to just leave it out. You have a number of return statements that don't do anything (i.e. they return nothing (None actually) at the end of the function). A function without return automatically returns None at the end, so it's better to leave them out. Similarly you don't need to call sys.exit(): the script will terminate anyway if it reaches the end. Better leave it out. LongClass.clear() doesn't do anything and isn't called anyway; leave it out. ModerateClass.__del__() doesn't do anything either. I'm not sure how it affects what happens if ModerateClass gets freed, but I suggest you don't start messing with __del__() until you have more Python knowledge and experience. I'm not sure why you think you need to implement that method. The same goes for HugeClass.__del__(). It does delete self.B4v, but the default behavior will do that too. Again, I don't get why you want to override the default behavior. In a number of cases, you use a dict like this: built_classes = {} for i in LINES: built_classes[len(built_classes)] = ... So you're using the indices 0, 1, 2, ... as the keys. That's not what dictionaries are made for; lists are much better for that: built_classes = [] for i in LINES: built_classes.append(...) HugeClass.B4v isn't used, so you can safely remove it. Your readLines() function reads a whole file into memory. If you're working with large files, that's not such a good idea. It's better to load one line at a time into memory and work on that. I would even completely remove readLines() and restructure ReadClasses() like this: def ReadClasses(filename): print 'Now reading ...' built_classes = [] # Open file in_file = open(filename, 'r') # Read lines and interpret them. time_a = time.time() for i in in_file: ## This is alternative 1. built_classes.append(HugeClass(long_line)) ## The next line is alternative 2. ## built_classes[len(built_classes)] = long_line in_file.close() time_b = time.time() print "DEBUG readClasses took %.3f s" % (time_b - time_a) Personally I only use 'i' for integer indices (as in 'for i in range(10)'); for other use I prefer more descriptive names: for line in in_file: ... But I guess that's up to personal preference. Also you used LINES to store the file contents; the convention is that names with all capitals are used for constants, not for things that change. In ProcessList(), you keep the index in a separate variable. Python has a trick so you don't have to do that yourself: nfiles = len(input_files) for file_index, i in enumerate(input_files): print "--> %i/%i: %s" % (file_index + 1, nfiles, i) ReadClasses(i) Instead of item0, item1, ... , it's generally better to use a list, so you can use item[0], item[1], ... And finally, John Machin's suggestion looks like a good way to restructure that long sequence of conversions and assignments in HugeClass. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From jasondrew72 at gmail.com Mon Sep 17 09:22:08 2007 From: jasondrew72 at gmail.com (Jason Drew) Date: Mon, 17 Sep 2007 06:22:08 -0700 Subject: simple regular expression problem In-Reply-To: <1190034041.796626.66790@n39g2000hsh.googlegroups.com> References: <1190034041.796626.66790@n39g2000hsh.googlegroups.com> Message-ID: <1190035328.837246.318920@d55g2000hsg.googlegroups.com> You just need a one-character addition to your regex: regex = re.compile(r'', re.S) Note, there is now a question mark (?) after the .* By default, regular expressions are "greedy" and will grab as much text as possible when making a match. So your original expression was grabbing everything between the first opening tag and the last closing tag. The question mark says, don't be greedy, and you get the behaviour you need. This is covered in the documentation for the re module. http://docs.python.org/lib/module-re.html Jason On Sep 17, 9:00 am, duikboot wrote: > Hello, > > I am trying to extract a list of strings from a text. I am looking it > for hours now, googling didn't help either. > Could you please help me? > > >>>s = """ \n\n28996\n\n\n28997\n""" > >>> regex = re.compile(r'', re.S) > >>> L = regex.findall(s) > >>> print L > > ['organisatie>\n28996\n > \n\n28997\n > I expected: > [('organisatie>\n28996\n > \n), (\n28997\n organisatie')] > > I must be missing something very obvious. > > Greetings Arjen From tomharding at inbox.com Mon Sep 17 13:02:31 2007 From: tomharding at inbox.com (Tom Harding) Date: Mon, 17 Sep 2007 18:02:31 +0100 Subject: Using python to create windows apps that everyone can use? Message-ID: <000001c7f94c$8a280de0$0202fea9@upstairs> Hi guys, sorry to post another topic on this, as I am aware that it has already been posted a few times, but not with specifically what I am looking for. I want an app that makes a gui interface for python (similar to Microsoft visual studio or qt designer, not a code based one) and/or an app that can make this into a .exe that can be opened by any person on any computer without python installed. I would just love to do this in python and not C++, its so simple and logical. So basically, the easiest way to do that, please! Thanks, Tom Harding -------------- next part -------------- An HTML attachment was scrubbed... URL: From ricaraoz at gmail.com Tue Sep 18 18:44:10 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 18 Sep 2007 19:44:10 -0300 Subject: Pseudo-Private Class Attributes Message-ID: <46F054BA.9050709@bigfoot.com> That is self.__attributes Been reading about the reasons to introduce them and am a little concerned. As far as I understand it if you have a class that inherits from two other classes which have both the same name for an attribute then you will have a name clash because all instance attributes "wind up in the single instance object at the bottom of the class tree". Now I guess this means that in any real OOP project you'd better use __attr for all your attributes, because classes are usually meant to be subclassed and you can never know when you'll be subclassing from two classes with attributes with the same name, and I guess you can't take the risk of this happening because when it happens it will be hell to find out what's going on. Is this right? From jura.grozni at gmail.com Wed Sep 19 05:55:48 2007 From: jura.grozni at gmail.com (azrael) Date: Wed, 19 Sep 2007 09:55:48 -0000 Subject: Help, I'm going mad with this In-Reply-To: References: <1190173561.822713.200070@d55g2000hsg.googlegroups.com> Message-ID: <1190195748.442539.245200@r29g2000hsg.googlegroups.com> I didn't found this one. Looks interesting and complex because I ran away from C to Python because of the developing speed and pointers. Thanks mate, I'll try it. Other C implementations I found were much shorter, at least this is going to be a little challenge. :D From e.frerich at nord-com.net Tue Sep 25 16:37:29 2007 From: e.frerich at nord-com.net (Egon Frerich) Date: Tue, 25 Sep 2007 22:37:29 +0200 Subject: Zope review In-Reply-To: <54e1e4bc0709220757r5609f19brabadc43f34ae90d8@mail.gmail.com> References: <1190331847.514475.284200@22g2000hsm.googlegroups.com> <1190403772.862325.113960@y42g2000hsy.googlegroups.com> <1190432460.360614.293400@n39g2000hsh.googlegroups.com> <54e1e4bc0709220757r5609f19brabadc43f34ae90d8@mail.gmail.com> Message-ID: <46F97189.20501@freudenberg.ih> Sean Tierney schrieb: >>From Twisted's website "Twisted is a networking engine written in > Python, supporting numerous protocols. It contains a web server, > numerous chat clients, chat servers, mail servers, and more. > > Given that Zope is also a written in python, supports numerous > protocols, contains a webserver, has several chat packages available, > a comparison/contrast would be quite useful. Zope 3 uses Twisted Egon From jscrerar at compuserve.com Sun Sep 30 10:42:56 2007 From: jscrerar at compuserve.com (Jim) Date: Sun, 30 Sep 2007 07:42:56 -0700 Subject: Command-line does work when scheduled In-Reply-To: References: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> <1191104269.578536.56470@g4g2000hsf.googlegroups.com> <1191114246.668635.327080@o80g2000hse.googlegroups.com> Message-ID: <1191163376.067339.34740@d55g2000hsg.googlegroups.com> On Sep 29, 8:45 pm, "Gabriel Genellina" wrote: > En Sat, 29 Sep 2007 22:04:06 -0300, Jim escribi?: > > >> If it works this way, maybe the .py file extension is not correctly > >> registered. > > > Yes, it works this way. > > How do I register the .py extension correctly? > > From a command line, type: > assoc .py > You should get: > .py=Python.File > If you get an error, or another thing like py_auto_file: > assoc .py=Python.File > > Then: > ftype Python.File > You should get: > Python.File=c:\path\to\python.exe "%1" %* > If you don't: > ftype Python.File=c:\path\to\python.exe "%1" %* > > The %* at the end is important: if you created the association by using > "Open with...", or selecting Python from the list of installed programs, > very likely the command says only "%1" - that is, the script being open, > but without any additional arguments. > > Better if you have administrative rights to do this tasks. > > -- > Gabriel Genellina I believe I get the correct results as follows: ============================================== Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. J:\Jim Crerar\mypython\misc>assoc .py .py=Python.File J:\Jim Crerar\mypython\misc>ftype Python.File Python.File="E:\Python25\python.exe" "%1" %* J:\Jim Crerar\mypython\misc> =============================================== What else could be wrong? Thanks, Jim From khemkaamit at gmail.com Wed Sep 5 04:31:49 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 5 Sep 2007 14:01:49 +0530 Subject: Printing lists in columns In-Reply-To: <1188979665.052672.211110@r34g2000hsd.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> <1188913394.763871.218660@d55g2000hsg.googlegroups.com> <46dd69b1$0$24998$426a74cc@news.free.fr> <1188917550.261894.84010@k79g2000hse.googlegroups.com> <46ddbb26$0$18672$426a74cc@news.free.fr> <1188979665.052672.211110@r34g2000hsd.googlegroups.com> Message-ID: <1360b7230709050131xf709fe0k8a4f9e46bf525bdb@mail.gmail.com> On 9/5/07, cjt22 at bath.ac.uk wrote: > Thanks guys, I really appreciate it. I have never used google groups > before and am so impressed with how helpful you all are. It is also lovely > that none of you mock my little knowledge of Python but just want to > improve it. And we are proud of it ! > I have another question in relation to the izip_longest function (I > persume > this should be within the same topic). > Using this funciton, is there a way to manipulate it so that the > columns can be formated > tabular i.e. perhaps using something such as str(list).rjust(15) > because currently the columns > overlap depending on the strings lengths within each column/list of > lists. i.e. my output is > currently like: > > bo, daf, da > pres, ppar, xppc > magnjklep, *, dsa > *, *, nbi > > But I want it justified, i.e: > > bo , daf, da > pres , ppar, xppc > magnjklep, *, dsa > * , *, nbi You can format the output while "print"ing the table. Have a look at: http://www.python.org/doc/current/lib/typesseq-strings.html example: for tup in izip_longest(*d, **dict(fillvalue='*')): print "%15s, %15s, %15s" %tup # for a tuple of length 3, you can generalize it > I am struggling to understand how the izip_longest function works > and thus don't really know how it could be manipulated to do the > above. > It would be much apprecited if somoene could also explain how > izip_function > works as I don't like adding code into my programs which I struggle to > understand. > Or perhaps I have to pad out the lists when storing the Strings? > > Any help would be much appreciated. This is an example of "generator" functions, to understand what they are and how they work you can: 1. web-search for "python generators" 2. have a look at "itertools" module, for more generators -- ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in From gagsl-py2 at yahoo.com.ar Mon Sep 17 16:37:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Sep 2007 17:37:44 -0300 Subject: Class for custom Tkinter widget--difficulty References: <5786d$46eedf63$4275d90a$16155@FUSE.NET> Message-ID: En Mon, 17 Sep 2007 17:11:03 -0300, Kevin Walzer escribi?: > I'm trying to create a custom Tkinter widget class, and I'm having some > difficulty getting it set up properly. > > The class is called MacToolbar, saved in its own module MacToolbar.py, > and imported with this statement: > > import MacToolbar > > Here is the relevant portion of the class: > > ###relevant class code > > class MacToolbar: > def __init__(self, master): > self.tk.call("package", "require", "macsearchfield") > self.tk.call('package', 'require', 'tile') > > > def create(self): > self.baseframe = Tile.Frame(self, master) > self.baseframe.pack(side='top', fill='both', expand='no') > > > def toolbar(self): > self.create() > self.newframe = Tile.Frame(self.baseframe) > self.newframe.pack(fill='both', expand='yes') > > self.buttonframe = Tile.Frame(self.newframe) > self.buttonframe.pack(side='top', fill='both', expand = 'yes') > > > I'm a bit confused on how to call a class that is imported via a module. > Both approaches I try produce errors: > > self.topframe = MacToolbar.toolbar(self.mainframe) > self.topframe = MacToolbar.MacToolbar.toolbar(self.mainframe) > [...] I was expecting to be able to use the standard Class.Method > notation in > calling MacToolbar class methods, but it appears that this does not work > at all: that's what I see in the first error above. Instead I have to > use Module.Class.Method notation? I've never seen this before. > > Can someone point out what I am doing wrong, either in the construction > of the class, the way it's imported, or in how I'm calling methods? You have to create an instance, and then you call methods on that instance. But toolbar() doesn't look like a method; both the create and toolbar methods appear to create the toolbar itself; probably you should move all that code into __init__. Perhaps you should inherit from Frame? Given the kind of mistakes you have, I suggest you read something about classes and object orientation in Python. (Maybe you have used a lot of classes, but perhaps this is the first class you *design*?) -- Gabriel Genellina From not_here at no_where.com Sun Sep 9 12:41:42 2007 From: not_here at no_where.com (Brian) Date: Sun, 09 Sep 2007 09:41:42 -0700 Subject: python 2.5 problems Message-ID: <3nVEi.98555$Vk6.66626@newsfe07.phx> Finally deleted 2.2 and loaded 2.5 (see below), using the msi, on my XP partition. Having intermittent system crashes. Assumed a corrupt download, so deleted and did another download/install. Same problems. The associated DLLs when XP says that it must shut down the idle shell are not consistent. So is there something not stable about ver 2.5 on XP ? Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Thanks very much from my cat and dog. From khemkaamit at gmail.com Wed Sep 5 07:22:35 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 5 Sep 2007 16:52:35 +0530 Subject: Looping through File Question In-Reply-To: <79b79e730709050407m7b13a19eh72f8638ccfa65e81@mail.gmail.com> References: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> <79b79e730709050407m7b13a19eh72f8638ccfa65e81@mail.gmail.com> Message-ID: <1360b7230709050422s202d3c4dr6d0e0c1b8335d1c3@mail.gmail.com> On 9/5/07, Francesco Guerrieri wrote: > On 9/5/07, planetmatt wrote: > > I am a Python beginner. I am trying to loop through a CSV file which > > I can do. What I want to change though is for the loop to start at > > row 2 in the file thus excluding column headers. > > > > At present I am using this statement to initiate a loop though the > > records: > > > > for line in f.readlines(): > > > > How do I start this at row 2? > > > > you can simply call (and maybe throw away) f.readline() a single time before > looping. > If the lenght of the first line is fixed, you can also use f.seek to start > reading from the second row. > > francesco Btw, if you are trying to read a csv file and parse it, you can save some work .. have a look at "csv" module ! -- ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in From llothar at web.de Sat Sep 1 06:53:31 2007 From: llothar at web.de (llothar) Date: Sat, 01 Sep 2007 03:53:31 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188369928.755777.142690@i38g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> Message-ID: <1188644011.617040.185520@r29g2000hsg.googlegroups.com> On 29 Aug., 13:45, Russ wrote: > I have not yet personally used it, but I am interested in anything > that can help to make my programs more reliable. If you are > programming something that doesn't really need to be correct, than you > probably don't need it. But if you really need (or want) your software I'm one of the few (thousand) hard core Eiffel programmers on this world and i can tell you that this would not add to much to python. To get the benefits of it you need to use it together with a runtime that is designed from ground with DBC and a language that is fast enough to be able to check the contracts, if you don't have the latter all you get is a better specification language (which you can write as comments in python). Learn the Eiffel design way and then add assert statements whereever you need them. Works well when i do C/C++ programming and maybe even for script languages - but i never used it for scripts as i don't see a real value here. From metawilm at gmail.com Tue Sep 25 13:48:29 2007 From: metawilm at gmail.com (metawilm at gmail.com) Date: Tue, 25 Sep 2007 10:48:29 -0700 Subject: Nested For and While Statements In-Reply-To: <1190740057.329424.57230@r29g2000hsg.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190664644.936871.57050@57g2000hsv.googlegroups.com> <1190701545.148197.191090@o80g2000hse.googlegroups.com> <1190740057.329424.57230@r29g2000hsg.googlegroups.com> Message-ID: <1190742509.262383.137100@o80g2000hse.googlegroups.com> On Sep 25, 7:07 pm, Zentrader wrote: > Note that in list comprehension, [x for x in (1, 2, 3)], the > for loop allocates memory the same way, but the scope changes so that > "x" is visible outside the for loop, How is this different? The variable spilling of list comprehension is the same as for regular for loops. The (#) and (##) lines below don't print the same value of j. >>> for j in range(3): ... print j, "first loop" (#) ... for j in range(3): ... print " ", j, "2nd loop" ... print j, "first loop, again?" (##) - Willem From lucaberto at libero.it Mon Sep 17 03:29:43 2007 From: lucaberto at libero.it (luca72) Date: Mon, 17 Sep 2007 00:29:43 -0700 Subject: QPicture and Qpainter PyQt4 Message-ID: <1190014183.462244.135560@w3g2000hsg.googlegroups.com> Hello at all I have made this small tests: this is the form implementation: # -*- coding: utf-8 -*- """ Module implementing Form. """ from PyQt4.QtGui import QWidget from PyQt4.QtCore import pyqtSignature from PyQt4 import * from disegni import PictureFrame from Ui_form import Ui_Form class Form(QWidget, Ui_Form): """ Class documentation goes here. """ def __init__(self, parent = None): """ Constructor """ QWidget.__init__(self, parent) self.setupUi(self) @pyqtSignature("") def on_pushButton_clicked(self): """ Slot documentation goes here. """ # TODO: not implemented yet #raise "Not implemented yet" #gr = QtGui.QPainter() picture = QtGui.QPicture() gr = QtGui.QPainter() gr.begin(picture) gr.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine)) gr.drawLine(70,100,150,100) gr.end() picture.save('dis.pic') self.frame.update() and this is the clas that implements the paint event: from PyQt4.QtGui import QWidget from PyQt4.QtCore import pyqtSignature from PyQt4 import * class PictureFrame(QtGui.QFrame): def __init__(self, parent = None): QFrame.__init__(self, parent) picture = QtGui.QPicture() def paintEvent(self, event): picture.load('dis.pic') gr = QtGui.QPainter() gr.begin(self.frame) gr.drawPicture(0, 0, picture) gr.end() But nothing is paint. Can you give me some help Regards Luca From gregturn at mindspring.com Wed Sep 19 17:11:59 2007 From: gregturn at mindspring.com (Goldfish) Date: Wed, 19 Sep 2007 14:11:59 -0700 Subject: Spring Python 0.3.0 is released! In-Reply-To: <1189599938.930862.308330@g4g2000hsf.googlegroups.com> References: <1189599938.930862.308330@g4g2000hsf.googlegroups.com> Message-ID: <1190236319.992069.220690@d55g2000hsg.googlegroups.com> Spring Python 0.3.1 was released today. It contains a quick add-on feature: DecoratorBasedApplicationContext. This feature lets you define an IoC container using python code and decorators instead of an XML flat file. It handles things like dependency injection and fetches things in order as needed. It also supports two scopes: PROTOTYPE and SINGLETON. Get it while its hot! From jyamada1 at gmail.com Wed Sep 19 14:04:03 2007 From: jyamada1 at gmail.com (Jason Yamada-Hanff) Date: Wed, 19 Sep 2007 18:04:03 -0000 Subject: Freetype bindings, finally? Message-ID: <1190225043.731294.7050@19g2000hsx.googlegroups.com> Hi all, I'm working on a project that would benefit very much from Python Freetype2 bindings (the Fonty Python project). I don't want to duplicate efforts and wrap the library again if we don't have to. Interestingly, it seems like there have been lots of attempts at doing this. Generally, there are: ft2 - http://www.satzbau-gmbh.de/staff/abel/ft2/index.html No longer maintained, incomplete, beta, from around the 2.0 days. Py-freetype - http://indic-computing.sourceforge.net/projects/pyfreetype2.html More recent, on Pyrex, last update was in 2003, no longer maintained, doesn't compile for me Then, it seems like multiple projects (matplotlib and PIL) have done their own integration with FT, but maintain that code themselves, for themselves. These, of course, are up-to-date and maintained. Are there other projects that have also done their own work on FT bindings? Ultimately, this means that there is no FreeType2 bindings package that is up-to-date and generally available, but that the work has been done multiple times over by individual projects. I understand that this is totally the prerogative of each project. The community, though, could benefit from having a central package of bindings. Are those who have already worked on bindings willing to extract their work into a separate package? It would be great to finally have a set of standard bindings! Thoughts are welcome. I am new to the C extension world, so I am probably missing a whole other level of complexity here. Thanks, Jason p.s. There is a sad message on Freetype's website about this ("Unfortunately, no mature Python bindings for FreeType 2 are available currently..."), right above its notes about all the other languages that do have bindings (including Ruby!). :-) From nospam at non.com Sat Sep 15 09:14:31 2007 From: nospam at non.com (=?iso-8859-1?b?cultaQ==?=) Date: Sat, 15 Sep 2007 13:14:31 GMT Subject: Rename multiple files using names in a text file References: Message-ID: Le Fri, 14 Sep 2007 12:52:52 -0700, James Stroud a ?crit: [...] > Other than that your strip() is stripping off some whitespace that is > part of the name, I really can't see the problem either, but did you try > to add in the explicit path? E.g.: actually, the problem was in "while i <= len(list_jpg_strip)" and i should have been "while i < len(list_jpg_strip)". Antoher problem was the name of jpg's files used for testing. A naughty one was nammed "file.jpg " instead of "file.jpg". So maube, as you saif, stripping is useless for list of jpg files. Thanks a lot. R?mi From sebastien.lannez at gmail.com Fri Sep 21 09:08:05 2007 From: sebastien.lannez at gmail.com (sebastien.lannez at gmail.com) Date: Fri, 21 Sep 2007 13:08:05 -0000 Subject: __contains__() : Bug or Feature ??? Message-ID: <1190380085.770828.19400@o80g2000hse.googlegroups.com> Hi everybody, I need to overload the operator in and let him return an object ... It seems it is not a behavior Python expect : >>> class A: ... def __contains__(self,a): ... return 'yop' ... >>> a=A() >>> print 'toto' in a True >>> print a.__contains__('toto') yop I don't know if it's a bug or a feature but i really need this overloading and don't know how to do it ... Furthermore I can't use a trick of the kind : a |in| b ... because my overloaded operator must be called by : a in b ... Is someone could help me ? From tim.williams at syniverse.com Fri Sep 7 06:38:54 2007 From: tim.williams at syniverse.com (Tim Williams) Date: Fri, 7 Sep 2007 11:38:54 +0100 Subject: why should I learn python In-Reply-To: <200709061624.10112.brown@esteem.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> <1189119676.239459.325280@w3g2000hsg.googlegroups.com> <200709061624.10112.brown@esteem.com> Message-ID: <9afea2ac0709070338s38fe6c2eycd9b58ff19516895@mail.gmail.com> On 07/09/07, Tom Brown wrote: > On Thursday 06 September 2007 16:01, windandwaves wrote: > > Hmmm, thank you all for your replies. I will do some research on the > > net (i did some already, but because I am really not much of a > > programmer, it is often too detailed for me). I have limited time, > > but it does sound like something to learn, just for fun and for > > practical use. How would you use it in a web development > > environment? I mean, in real practical terms. Could it assist with > > php? Is it easy to write GUI programs in Python? > > Checkout http://www.djangoproject.com/ or http://turbogears.org/ for web > development. Checkout http://www.riverbankcomputing.co.uk/pyqt/index.php for > writing GUI programs. There are other options for GUI apps. That is the one I > use all the time. Also, check out Karrigell ( www.karrigell.com) . It will show you just how easy & fast Python can be for web development. It has its own web server, or it can sit behind Apache etc. HTH :) From stefan.behnel-n05pAM at web.de Fri Sep 21 08:52:51 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 21 Sep 2007 14:52:51 +0200 Subject: An Editor that Skips to the End of a Def In-Reply-To: <5lhs4pF8bkunU1@mid.individual.net> References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: <46F3BEA3.8080100@web.de> Bjoern Schliessmann wrote: > Lawrence D'Oliveiro wrote: >> After two decades of putting up with vi just to ensure >> compatibility with every proprietary *nix system I might come >> across, let me just say ... >> >> USE EMACS! > > Nah. Use vim. > >> Oh, and >> . > > Esc-Meta-Alt-Ctrl-Shift? :) Yep, that's five of them. Stefan From Graham.Dumpleton at gmail.com Thu Sep 13 19:04:17 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 13 Sep 2007 23:04:17 -0000 Subject: lxml + mod_python: cannot unmarshal code objects in restricted execution mode In-Reply-To: <1189688758.587404.139360@r29g2000hsg.googlegroups.com> References: <1189688758.587404.139360@r29g2000hsg.googlegroups.com> Message-ID: <1189724657.261461.181420@22g2000hsm.googlegroups.com> On Sep 13, 11:05 pm, Dmitri Fedoruk wrote: > Hello everyone, > > I'm developing a mod_python application that is based on XML\XSLT > transforming. > > I used 4Suite libraries for that, but as the speed was unacceptable > for me, I switched to lxml. Everything became much easier and 10 times > faster, but I've encountered the subject problem. > > In brief - all my data and xslt are stored and transferred in UTF-8. > With 4Suite everything was fine all the time. With lxml it works fine > from the console, but inside mod_python it occasionaly dies, ~ one > time out of three. Strange - the same code with the same data works or > dies by its own means. > > As far as I have found, there was a similar problem with PyXML and > encodings module, but there was no clear solution. > > So, my configuration is the following: > Python 2.5.1 > Server version: Apache/2.2.4 (FreeBSD) > mod_python-3.3.1 > > And the relevant parts of my code are these: > > def extApplyXslt(xslt, data, logger ): > try: > strXslt = urllib2.urlopen(xslt).read() > # i have to read the xslt url to the python string > except urllib2.HTTPError, e: > ....... > except urllib2.URLError, e: > ............. > try: > xslt_parser = etree.XMLParser() > xslt_parser.resolvers.add( PrefixResolver("XSLT") ) > > # and now I have to use the string; a more elegant solution, > anyone? > f = StringIO(strXslt) > xslt_doc = etree.parse(f, xslt_parser) > > # and here where the problem comes > transform = etree.XSLT(xslt_doc) > > except Exception, exc: > logger.log(logging.CRITICAL, exc.__str__() ) > > try: > result_tree = transform(data) > return etree.tostring(result_tree, 'utf-8') > except Exception, exc: > print "xslt processing error!", exc.__str__() > return "" > > It dies with the message 'cannot unmarshal code objects in restricted > execution mode'. By profiling I detected the point where problem > occurs: > transform = etree.XSLT(xslt_doc) > > So, I would be grateful for any suggestions how to get rid of this. > I'd really like to use lxml. Maybe I should initialize the xslt > processor in somehow other way? > > Thanks in advance, > Dmitri Try forcing mod_python to run your code in the first interpreter instance created by Python. PythonInterpreter main_interpreter If that still doesn't work then you are hitting problems in mod_python related to how it does GIL management or how the third party package is implemented and whether it is compatible with use in secondary Python interpreters. For details see: If it still doesn't work and your application is a WSGI application and you aren't using mod_python specific features, only choice at this point would be to use mod_fastcgi or mod_wsgi instead. If using mod_wsgi, you would still need to tell it to run your code in first interpreter instance created by Python. WSGIApplicationGroup %{GLOBAL} For some details on issues related to this problem, see sections 'Python Simplified GIL State API' and 'Multiple Python Sub Interpreters' in mod_wsgi document: http://code.google.com/p/modwsgi/wiki/ApplicationIssues Graham From joemystery123 at gmail.com Sun Sep 23 08:32:28 2007 From: joemystery123 at gmail.com (crybaby) Date: Sun, 23 Sep 2007 05:32:28 -0700 Subject: newb: Question regarding custom exception Message-ID: <1190550748.698865.210740@22g2000hsm.googlegroups.com> Why you specify type and name of the exception in your custom exceptions, but not in built in exceptions except IOError: print "no file by the name ccy_rates*.txt" except MyError, e: print e.msg Also, when you do: try: raise MyError(23) In "try: MyError(23) ", you are calling MyError class, but actually get instantiated in except MyError, e: ? From linuxprog at gmail.com Mon Sep 3 05:43:27 2007 From: linuxprog at gmail.com (linuxprog) Date: Mon, 03 Sep 2007 09:43:27 +0000 Subject: SOAP : ZSI error Message-ID: <46DBD73F.6060003@gmail.com> hello i need some help with ZSI module i want to use the web service located here www.ebob42.com/cgi-bin/NumberToWordsInDutch.exe/soap/IDutch the wsdl file : http://www.ebob42.com/cgi-bin/NumberToWordsInDutch.exe/wsdl/IDutch that web service is very simple , the function NumToStr converts numbers to dutch words (description http://www.xmethods.net/ve2/ViewListing.po?key=uuid:01EF9AE1-6DD3-7317-AFA5-05A8A52FCD56) i have generated IDutchservice_services with wsdl2py here is my code : import IDutchservice_services soap = IDutchservice_services.IDutchbindingSOAP("www.ebob42.com/cgi-bin/NumberToWordsInDutch.exe/soap/IDutch") ok = IDutchservice_services.NumToStr0Request() ok.Num=5 print soap.NumToStr(ok) that prints an error RuntimeError: must specify transport or url startswith https/http what's wrong in my script ? thanks From vijayeee at gmail.com Wed Sep 5 08:32:18 2007 From: vijayeee at gmail.com (vijayca) Date: Wed, 05 Sep 2007 12:32:18 -0000 Subject: threads Message-ID: <1188995538.507987.142250@k79g2000hse.googlegroups.com> i have written a script that spawns some threads.... all run in parallel.... now i need to stop all the threads once i press a key(example: "\n") how to do it... From ldo at geek-central.gen.new_zealand Fri Sep 7 20:36:44 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 08 Sep 2007 12:36:44 +1200 Subject: Checking if elements are empty References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> Message-ID: In message <46e115e5$0$7691$9b4e6d93 at newsspool2.arcor-online.net>, Wildemar Wildenburger wrote: > Lawrence D'Oliveiro wrote: > >> In message , Chris >> Mellon wrote: >> >>> On 9/5/07, Steve Holden wrote: >>>> Doran, Harold wrote: >>>>> >>>>> Is there a way to check if the first element of y is null? >>>>> >>>> len(y[0]) == 0 >>>> >>> Better spelled as >>> >>> if y[0]: >> >> Not a good idea. > > Why not? Because there is a situation where your version of the test will fail even if the first element of y is non-null. From bj_666 at gmx.net Mon Sep 10 03:39:21 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2007 07:39:21 GMT Subject: How to insert in a string @ a index References: <1189274564.462664.131240@22g2000hsm.googlegroups.com> <46e4153a$0$32052$426a74cc@news.free.fr> <1189390526.723534.153390@d55g2000hsg.googlegroups.com> <1189409390.235999.307160@r29g2000hsg.googlegroups.com> Message-ID: <5kkal9F3vfqqU2@mid.uni-berlin.de> On Mon, 10 Sep 2007 00:29:50 -0700, Ant wrote: > On Sep 10, 3:15 am, "a.m." wrote: >> Thanks guys for you help. I ended up doing this way (for the >> records)... >> >> t1 = "hello world hello. hello. \nwhy world hello" > ... > > Another approach may be to use the re module's sub function: > > import re > > t1 = 'hello world hello. hello. \nwhy world hello' > > def matchHandler(match): > if : > return "XYZ" + match.group(0) > else: > return match.group(0) > > re.sub(keyword, matchHandler, t1) This doesn't work because according to the OP not all 'hello's are keywords. It seems to depend on the position if it's a keyword or not. Ciao, Marc 'BlackJack' Rintsch From paul at boddie.org.uk Tue Sep 18 07:46:49 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 18 Sep 2007 04:46:49 -0700 Subject: Extracting xml from html In-Reply-To: <1190063681.632965.249020@y42g2000hsy.googlegroups.com> References: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> <1190062919.998077.112810@19g2000hsx.googlegroups.com> <1190063681.632965.249020@y42g2000hsy.googlegroups.com> Message-ID: <1190116009.060004.197470@n39g2000hsh.googlegroups.com> On 17 Sep, 23:14, kyoso... at gmail.com wrote: > > I have lxml installed and I appear to also have libxml2dom installed. > I know lxml has decent docs, but I don't see much for yours. Is this > the only place to go:http://www.boddie.org.uk/python/libxml2dom.html > ? Unfortunately yes, with regard to online documentation, although the distribution contains API documentation, and the package has docstrings for most of the public classes, functions and methods. And the API is a lot like the PyXML and minidom APIs, too. Paul From Brian.McCann at viziant.net Thu Sep 13 15:16:50 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Thu, 13 Sep 2007 15:16:50 -0400 Subject: sys.argv index out of range error Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE33A@efmailx> Hi, I trying to create a bootstrap.sh shell script that takes two command line args that passes them to two scripts. one script is init.sh that sets up some environment varilables the other will be a Python script used as the main build script. the contents of the bootstrap file and init.sh are I've simplified the scripts as much as I could and still retain the errors bootstrap.sh #!/bin/sh cd /home/workspaces export LANG="en_US.UTF-8" source init $1 test.py $2 ################################# init.sh #!/bin/sh WORKSPACE_ROOT="$1"; export JAVA_OPTIONS="-Djava.library.path=$WORKSPACE_ROOT/:$WORKSPACE_ROOT/:$WORKSPACE_ROOT/" echo "JAVA_OPTIONS="$JAVA_OPTIONS; set PATH="$WORKSPACE_ROOT/vendor/basistech/rlp5.4/rlp/bin/ia32-glibc23-gcc32:$WORKSPACE_ROOT/vendor/basistech/rlp5.4/rlp/bin/ia32-w32-msvc71:$WORKSPACE_ROOT/lib/core:$PATH" ############################################################################## when I run the bootstrap.sh with two args $ ./bootstrap.sh spam ham init takes the spam with no problem this is the output on the command line $ ./bootstrap.sh spam ham JAVA_OPTIONS=-Djava.library.path=spam/:spam/:spam/ Traceback (most recent call last): File "./test.py", line 12, in ? aaa = sys.argv[1] IndexError: list index out of range This is the test.py script that gets the second arg ###################################### !/usr/bin/python import string import os import sys filename = sys.argv[0] aaa = sys.argv[1] print aaa ################################# If I remove "source init $1" from init.sh and replace it with "init 1$" I get this output which works $ bootstrap.sh spam ham JAVA_OPTIONS=-Djava.library.path=spam/:spam/:spam/ ham what's wrong with the line "source init $1 ? Thanks, Brian -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Mon Sep 3 23:13:31 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 04 Sep 2007 05:13:31 +0200 Subject: concise code (beginner) In-Reply-To: <13dsvqrqivtf092@corp.supernews.com> References: <13dsvqrqivtf092@corp.supernews.com> Message-ID: <46de8545$0$10566$426a74cc@news.free.fr> bambam a ?crit : > I have about 30 pages (10 * 3 pages each) of code like this > (following). Can anyone suggest a more compact way to > code the exception handling? If there is an exception, I need > to continue the loop, and continue the list. > > Steve. > > ----------------------------------- > for dev in devs > try: > dev.read1() > except > print exception > remove dev from devs for method_name in ['read1', 'read2', 'read3']: for dev in devs: try: meth = getattr(dev, method_name) except AttributeError, e: # should not happen, but we want to handle it anyway your_code_here() else: try: meth() except (SomePossibleException, SomeOtherPossibleException), e: print e # do what's needed to remove dev from devs # paying attention not to screw the looping machinery... (snip) From zentraders at gmail.com Wed Sep 19 10:43:12 2007 From: zentraders at gmail.com (Zentrader) Date: Wed, 19 Sep 2007 07:43:12 -0700 Subject: Find the ID, but how to select/copy the whole string by ID? In-Reply-To: <1190209195.493784.133340@q3g2000prf.googlegroups.com> References: <1190209195.493784.133340@q3g2000prf.googlegroups.com> Message-ID: <1190212992.394640.257390@q3g2000prf.googlegroups.com> sourcefile.find(stringID) returns the start location. You can use print to see this. You can then slice from start+len(stringID) and print it out. That should give you enough info to figure out how to find and extract to the end of the string tag as well. There are other ways to do this, but string.find is the easiest to understand. From mensanator at aol.com Mon Sep 10 13:45:31 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 10 Sep 2007 10:45:31 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: <13e9pjoc9rdfrf9@corp.supernews.com> References: <13e9iqhmgofasfb@corp.supernews.com> <1189403844.128637.85950@k79g2000hse.googlegroups.com> <13e9pjoc9rdfrf9@corp.supernews.com> Message-ID: <1189446331.405110.291060@o80g2000hse.googlegroups.com> On Sep 10, 1:38 am, Dennis Lee Bieber wrote: > On Sun, 09 Sep 2007 22:57:24 -0700, "mensana... at aol.com" > declaimed the following in comp.lang.python: > > > > > But, in general, doesn't (-11,-4) also satisfy > > x = y * a + b > > -70 = 6 * -11 + (-4)? > > > Do you overpay your car loans and wait for a refund? > > As I stated, integer division and modulo are linked... Which is > "correct" is probably dependent upon the language specifications. I didn't make an opinion on which was "correct". > Either > method allows one to recover the original value from the output of > divmod. My point was the need to satisfy x = y * a + b doesn't explain WHY divmod(-70,6) returns (-12,2) instead of (-11,-4). > > Whether that works in the way you intend is a different matter -- my > car loans usually have interest factors which are applied per payment by > payment date, so using modulo (or divmod) is not applicable, one must > actually build the table of payments one at a time (especially since the > automatic payments taken from paychecks gets "corrupted" during > holidays, when paychecks are issued a day or two earlier than normal, > meaning less interest charges during that period and more applied to > principle; with more on interest the following week, and less on > interest). Ok, poor example. Suppose instead we are slicing a 70 character string from the right. We certainly CAN'T have 6 12-letter slices, can we? But we can have 6 11-letter slices with 4 characters left over. And there are probably examples where (-12,2) would make more sense, although I can't think of one at the moment. Again, I'm not saying (-12,2) is wrong, just that the explanation why it's (-12,2) is wanting since there are cases where (-11,-4) makes more sense. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ From bdesth.quelquechose at free.quelquepart.fr Tue Sep 4 05:56:53 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 04 Sep 2007 11:56:53 +0200 Subject: PythonAlley.com In-Reply-To: <1189012363.397845.174960@y42g2000hsy.googlegroups.com> References: <1189012363.397845.174960@y42g2000hsy.googlegroups.com> Message-ID: <46def2a5$0$12296$426a34cc@news.free.fr> dkeeney a ?crit : (snip) > The Python community online now seems to have two major segments, the > c.l.p newsgroup (here), > and a large selection of blogs. C.l.p is unmoderated and often > hostile. (snip) > A moderated forum that gives recognition to the experienced and > tolerance to newbies would be a good thing. I'm surprised you find c.l.py an "hostile" place with no "tolerance to newbies", since it known for being one of the most friendly and helpful newsgroups on the comp.* usenet hierarchy - FWIW, may I quote some lines of a recent thread here ? """ Thanks guys, I really appreciate it. I have never used google groups before and am so impressed with how helpful you all are. It is also lovely that none of you mock my little knowledge of Python but just want to improve it. """ Also, please notice there's mailing-list for CS-newbies (http://mail.python.org/mailman/listinfo/tutor), and quite a few web forums, starting with http://python-forum.org, so I'm not sure a new one is really that useful. My 2 cents... From deets at nospam.web.de Mon Sep 3 12:43:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Sep 2007 18:43:51 +0200 Subject: TypeError: 'module object is not callable' References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> Message-ID: <5k2ru7F1srgiU1@mid.uni-berlin.de> christophertidy at hotmail.com wrote: > >> >> The others spottet the error I missed. But I can offer something else: >> >> http://dirtsimple.org/2004/12/python-is-not-java.html >> >> It's a worthy read for someone coming from Java, needing time to adjust. >> >> Diez- Hide quoted text - >> >> - Show quoted text - > > That deffinately was a useful read, thanks. > Thankyou to everyone who sorted these problems for me, I have > progressed very well > with this python program throughout the day now. > > I have another little question before I finish today: > I am currently struggling to use a global variable in my static > functions. I'll explain further > > Within my main.py file I have > > class Main(object): > stepStore = StepStore() > > @staticmethod > def createDepSteps(): > .... > stepStore.addStep([bol7, pre5]) > ....... > > @staticmethod > def processSteps(): > for step in stepStore.stepList[:]: > ...... > > Main.createDepSteps() > Main.processSteps() > > > Trying this approach I am getting a error saying with the > processSteps() method, stepStore is undefined > To solve this problem I am currently passing in the processSteps() > parameter a stepStore instance created within createDepSteps() > but there is surely a way stepStore can be a global attribute which > can be accessed from both methods? > Any help would be much appreciated again You are deeeeep down in javaland again. first of all, with the exception of factory methods, staticmethods or classmethods usually aren't needed. In Python, you can define functions directly. So move the above methods "toplevel", aka out of the class-context. and just make stepStore a module-global variable. Then things should work. The distinction between staticmethod and classmethod is, that staticmethod is a "pure" method, something unknown in Java. the classmethod OTOH is a method that gets the class as first argument (instead of the instance, as in an instance-method): class Foo(object): @classmethod def bar(cls): print cls However: get rid of unnecessary classes. Java is severely limited regarding the definition of "pure" code, the permanently needed class-context for e.g. a main-method is absurd - to say the least. Diez From xingfukun at 126.com Wed Sep 19 01:57:07 2007 From: xingfukun at 126.com (Xing) Date: Wed, 19 Sep 2007 13:57:07 +0800 Subject: Puzzled in the coding of Chinese References: <1190073045.618869.261290@k79g2000hse.googlegroups.com>, , , <871wcvlwly.fsf@rudin.co.uk> Message-ID: <200709191357069843001@126.com> Dear list members, I am a newcomer in the world of Python. But I am attracted by Python's power in handling text! Now I apply it to handle Chinese but the Chinese character cann't be displayed on the screen. What displayed on the screen is the 16bits codes. I am so puzzled! I believe this is an easy question to most of python users and an important question to me. Thanks a lot to your help! From fructidor00 at gmail.com Sun Sep 9 18:02:55 2007 From: fructidor00 at gmail.com (GuillaumeC) Date: Sun, 09 Sep 2007 22:02:55 -0000 Subject: UnboundLocalError on global variable In-Reply-To: References: Message-ID: <1189375375.158754.269140@k79g2000hse.googlegroups.com> > def processLogEntry(entry): # ADD THIS TO YOUR CODE global cmterID_ > > revision = int(entry.getRevision()) > commiter = str(entry.getAuthor()) > datetime = getTimeStamp(entry.getDate()) > message = str(entry.getMessage()) > > Commiter_[0] = cmterID_ //HERE's THE PROBLEM The reason why it does not work is that there is an assignment to cmterID_ in your function - even if it is after the problem. As a consequence, the bytecode compiler makes this name local, and the name is unbound. The quick fix is to add the global statement as above. There is a good explanation here: http://paddy3118.blogspot.com/2006/07/python-functions-assignments-and-scope.html May I suggest that you use less global variables, for instance enclosing your method in a class? From antroy at gmail.com Mon Sep 10 03:29:50 2007 From: antroy at gmail.com (Ant) Date: Mon, 10 Sep 2007 00:29:50 -0700 Subject: How to insert in a string @ a index In-Reply-To: <1189390526.723534.153390@d55g2000hsg.googlegroups.com> References: <1189274564.462664.131240@22g2000hsm.googlegroups.com> <46e4153a$0$32052$426a74cc@news.free.fr> <1189390526.723534.153390@d55g2000hsg.googlegroups.com> Message-ID: <1189409390.235999.307160@r29g2000hsg.googlegroups.com> On Sep 10, 3:15 am, "a.m." wrote: > Thanks guys for you help. I ended up doing this way (for the > records)... > > t1 = "hello world hello. hello. \nwhy world hello" ... Another approach may be to use the re module's sub function: import re t1 = 'hello world hello. hello. \nwhy world hello' def matchHandler(match): if : return "XYZ" + match.group(0) else: return match.group(0) re.sub(keyword, matchHandler, t1) The nice thing about this approach is that you could store keyword: test_function pairs in a dictionary, and reuse this whole block of code for arbitrary keywords with arbitrary rules. -- Ant... From jura.grozni at gmail.com Wed Sep 19 03:57:41 2007 From: jura.grozni at gmail.com (azrael) Date: Wed, 19 Sep 2007 07:57:41 -0000 Subject: help, I'll go crazy Message-ID: <1190188661.325493.68240@n39g2000hsh.googlegroups.com> Some time ago I started a thread about the Otsu Threshold. Well I didn' manage to make any progress to acomplish this task. I tried to implement it from other Languages including Java and C. Well, this is the example list. histogram=[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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 2, 1, 2, 0, 1, 3, 3, 3, 3, 1, 3, 1, 3, 5, 2, 3, 3, 3, 6, 3, 4, 5, 4, 9, 6, 11, 6, 10, 3, 11, 9, 9, 12, 22, 18, 34, 22, 28, 32, 25, 34, 38, 34, 54, 65, 106, 160, 167, 203, 282, 364, 446, 637, 816, 1022, 1264, 1456, 1646, 1753, 1845, 1922, 2203, 2231, 1973, 2245, 2369, 2349, 2258, 2130, 2066, 1835, 1640, 1554, 1414, 1179, 1024, 974, 938, 838, 785, 756, 803, 921, 952, 865, 722, 625, 608, 547, 498, 412, 438, 408, 413, 415, 339, 366, 330, 320, 293, 315, 368, 411, 434, 500, 531, 538, 552, 665, 811, 869, 998, 1021, 1075, 1080, 1030, 934, 926, 1074, 942, 941, 1014, 1440, 2966, 5301, 2729, 3400, 5563, 13096, 9068, 6045, 2813, 686, 180] # var() is from the numpy module My Example is This def otsu(hi): s=sum(hi) border=len(hi) for i in range(border): if hi[i]!=0:break for j in range(border-1,0-1,-1): if hi[j] != 0:break li=[] for l in range(len(hi)): hi[l]=float(hi[l])/s for k in range(i+1,j+1): q1=sum(hi[i:k]) q2=sum(hi[k:j+1]) v1=var(hi[i:k]) v2=var(hi[k:j+1]) a=q1*v1 + q2*v2 li.append(a) print min(li) m,n=li[0],i for k in range(len(li)): if li[k]>m: m=li[k] n=k return n This is a Threshold Method that accepts a list like a histogram and return the optimal threshold value. As I have been surfing the internet, I found several formulas. Please, dear comunity, help me.I am desperate, I'll go mad. I can't bealive it that I can't implement something so simple looking. For this example list the thresh value should be 218. I know it because I i tested it on an image in ImageJ, and then I exported the histogram. If any other examples needed I cant'get you as much as needed If needed, I can Paste 3 other algorithms I tried. Thaks in advance From rrr at ronadam.com Sun Sep 23 12:35:59 2007 From: rrr at ronadam.com (Ron Adam) Date: Sun, 23 Sep 2007 11:35:59 -0500 Subject: Factory function with keyword arguments In-Reply-To: <13fchhi2mnm5tc8@corp.supernews.com> References: <13fbl9ertj5es12@corp.supernews.com> <13fchhi2mnm5tc8@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sun, 23 Sep 2007 03:55:45 -0500, Ron Adam wrote: > >> Steven D'Aprano wrote: >>> I'm writing a factory function that needs to use keywords in the >>> produced function, not the factory. Here's a toy example: > > [snip] > > Thanks everyone who answered, you've given me a lot of good ideas. > > I've run some tests with timeit, and most of the variants given were very > close in speed. The one exception was (not surprisingly) my version that > builds a tuple, puts it in a list, then converts it to a dict, *before* > doing anything useful with it. It was 3-4 times slower than the others. > > George's version, with two definitions of foo(), was the fastest. The > second fastest was the variant using exec, which surprised me a lot. I > expected exec to be the slowest of the lot. Unfortunately, I doubt that > these would scale well as the factory becomes more complicated. The one with exec (the others less so) will depend on the ratio of how often the factory is called vs how often the foo is called. If the factory is called only once, then exec only runs once. If the factory is called every time foo is needed, then it will be much slower. So your test needs to take into account how the factory function will be used in your program also. Ron From klove at tax.ok.gov Tue Sep 25 16:15:05 2007 From: klove at tax.ok.gov (Kenneth Love) Date: Tue, 25 Sep 2007 15:15:05 -0500 Subject: Overriding Logging Config FileHandler Filename Message-ID: <005101c7ffb0$c34dc7d0$e6003dcc@worf2> I have a Python logging config file that contains a RotatingFileHandler handler. In the args key, I have hard-coded the log filename. Everything works great. However, I find that I now need to override this filename at application runtime. Is there a good way to do this? Here is a bit of sample code that (hopefully) clarifies my question. --------------- log.ini ----------------- [loggers] keys=root,processor ; Lots more stuff here: handlers, formatters, and loggers....... [handlers] keys=consoleHandler,fileHandler [handler_fileHandler] class=handlers.RotatingFileHandler level=DEBUG formatter=standard args=('D:\Projects\Python\src\log.log', 'a', 99999, 10) -------------- mymain.py ----------------- import logging.config logging.config.fileConfig('log.ini') # TODO: Override log filename with new name (e.g. 'd:\\logs\\mymain.py.log') log = logging.getLogger('mymain') log.info('START: mymain.py') log.info('FINISH: mymain.py') ------------------------------------------ adTHANKSvance, Kenneth Love -- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Kenneth Love | Oklahoma Tax Commission DP Programmer/Analyst | Information Technology (405) 522 - 5864 | http://www.tax.ok.gov/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- From steve at holdenweb.com Fri Sep 7 22:36:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Sep 2007 19:36:27 -0700 Subject: Generating a unique identifier In-Reply-To: <7xtzq57v64.fsf@ruckus.brouhaha.com> References: <13e2fgbbpsatm39@corp.supernews.com> <7x3axq7a8a.fsf@ruckus.brouhaha.com> <13e3us269f59s7a@corp.supernews.com> <7xd4wt99yv.fsf@ruckus.brouhaha.com> <7xtzq57v64.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Paul Rubin writes: >> the probability is about exp(-(2**60 / 2*2**160)) = 1/exp(2**101) > > Bah. Got that backwards and calculated wrong. The probability of no > collisions is > > exp(-(2**60) / (2*2**160)) = exp(-(2**-101)) = approx (1 - 2**-101) > > which is very close to 1. The probability of collision is about > 2**-101 which is close to 0. Proofread first, then post. I keep > getting that in the wrong order. Right. The words "birthday attack" should have been in the back of your mind while you were writing that message. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kpalamartchouk at gmail.com Wed Sep 12 07:54:44 2007 From: kpalamartchouk at gmail.com (kpalamartchouk at gmail.com) Date: Wed, 12 Sep 2007 04:54:44 -0700 Subject: Sea-or-land test Message-ID: <1189598084.622653.94590@50g2000hsm.googlegroups.com> Could you advise if there exists a simple package, containing function that would take geographic coordinates and return information on whether this point belongs to land or sea? No great accuracy is needed -- I am interested in just major features, like those seen on coarse world maps. From duncan.booth at invalid.invalid Wed Sep 12 10:15:03 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Sep 2007 14:15:03 GMT Subject: An ordered dictionary for the Python library? References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <13efnmi4n959a59@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > In fact, I'm not sure what people mean by ordered dicts. I assume they > mean the keys are ordered, not the values. But ordered by what? > Insertion order? Modification order? Alphabetical order? All of the above at different times. Usually I think they mean original insertion order, I'd more often like modification order though. Insertion order can certainly be useful: any situation where you currently keep items in a list because the original order is important but also copy them into a dictionary or set because you need fast lookup. e.g. if you want only unique items out of a list but need to preserve order of first occurrence. Another example would be uml->code round tripping: you parse in an existing file containing method definitions, then update the method definitions from a UML model and write the file out again: ArchGenXML does exactly that, but last I looked the methods were written out in whatever order the dictionary stored them which really messes up version control. It really should preserve the order that methods appeared in the file. Modification order would be great for a cache. Touch items whenever they are referenced and then whenever the cache gets too big just pop the oldest until you get back to the desired size. Alphabetical or other sorted order when you want to get smallest/largest or next smaller/larger then a specific item. I don't agree you necessarily mean ordered by key rather than value, I think you could specify any sortkey and expect updating the value to restore the ordering. Maybe if you are recording some stats and want to regularly output the top 10? From robert.schweikert at mathworks.com Thu Sep 20 15:23:52 2007 From: robert.schweikert at mathworks.com (Robert Schweikert) Date: Thu, 20 Sep 2007 15:23:52 -0400 Subject: validating parser Message-ID: Is there a Python module which will do XSD validation? Thanks, Robert -- Robert Schweikert MAY THE SOURCE BE WITH YOU (robert.schweikert at mathworks.com) LINUX From steve at holdenweb.com Fri Sep 21 13:38:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Sep 2007 13:38:20 -0400 Subject: xml-rpc timeout In-Reply-To: <2_WdnTQ86eZNY27bnZ2dnUVZ_jCdnZ2d@comcast.com> References: <2_WdnTQ86eZNY27bnZ2dnUVZ_jCdnZ2d@comcast.com> Message-ID: Jd wrote: > Hi > I have a multi-threaded application. For certain operations to the > server, I would like to explicitly set timeout so that I get correct > status from the call and not timed out exception. > Does anyone know how to go about doing it ? > The easiest way is to use socket.setdefaulttimeout() to establish a longer timeout period for all sockets, I guess. It's difficult to establish different timeouts for individual sockets when they aren't opened directly by your own code (though each socket does also have a method to set its timeout period). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From gnewsg at gmail.com Sun Sep 9 11:48:38 2007 From: gnewsg at gmail.com (billiejoex) Date: Sun, 09 Sep 2007 08:48:38 -0700 Subject: os.sep and os.path.sep Message-ID: <1189352918.534864.195850@g4g2000hsf.googlegroups.com> >>> import os >>> hasattr(os, 'sep') True >>> hasattr(os.path, 'sep') True By chance I noticed it. Are there differences (I think not...)? IMHO, if there are no differences os.path.sep should be removed since it may be confusing. From jeff at jmcneil.net Thu Sep 27 17:08:17 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 27 Sep 2007 17:08:17 -0400 Subject: How to Catch Errors in SimpleXMLRPCServer In-Reply-To: <1190926533.435603.245530@o80g2000hse.googlegroups.com> References: <1190921745.575519.53560@y42g2000hsy.googlegroups.com> <1190926533.435603.245530@o80g2000hse.googlegroups.com> Message-ID: <82d28c40709271408m162ff9b4v4aa654a0eb48e053@mail.gmail.com> Yeah, that code was out of memory and I didn't test it, my apologies. Need to actually return a value from _dispatch. class MyCalls(object): def _dispatch(self, method, args): try: return getattr(self, method)(*args) except: handle_logging() server = SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(MyCalls()) server.serve_forever() -Jeff On 9/27 On 9/27/07, gregpinero at gmail.com wrote: > On Sep 27, 3:55 pm, "Jeff McNeil" wrote: > > Instead of register_function, use register_instance and provide a > > _dispatch method in that instance that handles your exception logging. > > > > Pseudo: > > > > class MyCalls(object): > > def _dispatch(self, method, args): > > try: > > self.getattr(self, method)(*args) > > except: > > handle_logging() > > > > server = SimpleXMLRPCServer(("localhost", 8000)) > > server.register_instance(MyCalls()) > > server.serve_forever() > > > > There might be an easier way... but this works for me. > > I wonder if there is something wrong with that. I get this error on > calling ever method: > > Fault 1: 'exceptions.TypeError:cannot marshal None unless allow_none > is enabled' but I can't see anywhere None would be coming from. > > -Greg > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Tue Sep 25 23:09:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Sep 2007 00:09:49 -0300 Subject: Nested For and While Statements References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190664644.936871.57050@57g2000hsv.googlegroups.com> <1190701545.148197.191090@o80g2000hse.googlegroups.com> <1190740057.329424.57230@r29g2000hsg.googlegroups.com> <1190742509.262383.137100@o80g2000hse.googlegroups.com> Message-ID: En Tue, 25 Sep 2007 14:48:29 -0300, escribi?: > On Sep 25, 7:07 pm, Zentrader wrote: >> Note that in list comprehension, [x for x in (1, 2, 3)], the >> for loop allocates memory the same way, but the scope changes so that >> "x" is visible outside the for loop, > > How is this different? The variable spilling of list comprehension is > the same as for regular for loops. The fact that list comprehensions "leak" its loop variable is an unfortunate accident and will be corrected in Python 3.0 > The (#) and (##) lines below don't > print the same value of j. > >>>> for j in range(3): > ... print j, "first loop" (#) > ... for j in range(3): > ... print " ", j, "2nd loop" > ... print j, "first loop, again?" (##) Because neither list comprehensions nor for loops start a new scope. j is a global here, might be local to the enclosing function if any. Anyway, all j's are the same variable. -- Gabriel Genellina From martin at v.loewis.de Sun Sep 2 14:45:49 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 02 Sep 2007 20:45:49 +0200 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <46daeaec$0$19889$426a74cc@news.free.fr> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> Message-ID: <46DB04DD.80801@v.loewis.de> >> (2) it is a interpretation language > Not quite. It's compiled to byte-code - just like Java (would you call > Java an 'interpreted language' ?) Python is not implemented like Java. In Java (at least in HotSpot), the byte code is further compiled to machine code before execution; in Python, the byte code is interpreted. Whether this makes Python an interpreter or a compiler, I don't know. Regards, Martin From perl4hire at softouch.on.ca Sun Sep 16 13:23:40 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Sun, 16 Sep 2007 13:23:40 -0400 Subject: Coming from Perl In-Reply-To: <1189712287.671352.72940@w3g2000hsg.googlegroups.com> References: <1189712287.671352.72940@w3g2000hsg.googlegroups.com> Message-ID: <46ED669C.5090304@softouch.on.ca> Paddy wrote: > On Sep 13, 1:30 am, Amer Neely wrote: >> I'm a complete newbie with Python, but have several years experience >> with Perl in a web environment. >> >> A question I have, if someone here is familiar with Perl, does Python >> have something like Perl's 'here document'? I've just searched and read >> some postings on generating HTML but they all seem to refer to various >> template utilities. Is this the only way, or am I missing something? I'm >> used to generating X/HTML by hand, which makes the here document in Perl >> ideal for me. Also, many times a client already existing HTML code that >> I can use in a script. > Hi Amer, > Just as an aside, you might find this helpful: > http://wiki.python.org/moin/PerlPhrasebook > It has perl code with python equivalents/notes. > Hello Paddy, Thanks for that link - it does look quite useful. -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From http Wed Sep 19 22:14:39 2007 From: http (Paul Rubin) Date: 19 Sep 2007 19:14:39 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> <1190241711.344058.238380@57g2000hsv.googlegroups.com> <1190242799.954176.279440@22g2000hsm.googlegroups.com> Message-ID: <7xps0ew0a8.fsf@ruckus.brouhaha.com> TheFlyingDutchman writes: > The very fastest Intel processor of the last 1990's that I found came > out in October 1999 and had a speed around 783Mhz. Current fastest > processors are something like 3.74 Ghz, with larger caches. Memory is > also faster and larger. It appears that someone running a non-GIL > implementation of CPython today would have significantly faster > performance than a GIL CPython implementation of the late 1990's. > Correct me if I am wrong, but it seems that saying non-GIL CPython is > too slow, while once valid, has become invalid due to the increase in > computing power that has taken place. This reasoning is invalid. For one thing, disk and memory sizes and network bandwith have increased by a much larger factor than CPU speed since the late 1990's. A big disk drive in 1999 was maybe 20gb; today it's 750gb, almost 40x larger, way outstripping the 5x cpu mhz increase. A fast business network connection was a 1.4 mbit/sec T-1 line, today it's often 100 mbit or more, again far oustripping CPU mhz. If Python was just fast enough to firewall your T1 net connection or index your 20gb hard drive in 1999, it's way too slow to do the same with today's net connections and hard drives, just because of that change in the hardware landscape. We have just about stopped seeing increases in cpu mhz: that 3.74ghz speed was probably reached a couple years ago. We get cpu speed increases now through parallelism, not mhz. Intel and AMD both have 4-core cpu's now and Intel has a 16-core chip coming. Python is at a serious disadvantage compared with other languages if the other languages keep up with developments and Python does not. Also, Python in the late 90's was pitched as a "scripting language", intended for small throwaway tasks, while today it's used for complex applications, and the language has evolved accordingly. CPython is way behind the times, not only from the GIL, but because its slow bytecode interpreter, its non-compacting GC, etc. The platitude that performance doesn't matter, that programmer time is more valuable than machine time, etc. is at best an excuse for laziness. And more and more often, in the application areas where Python is deployed, it's just plain wrong. Take web servers: a big site like Google has something like a half million of them. Even the comparatively wimpy site where I work has a couple thousand. If each server uses 150 watts of power (plus air conditioning), then if making the software 2x faster lets us shut down 1000 of them, the savings in electricity bills alone is larger than my salary. Of course that doesn't include environmental benefits, hardware and hosting costs, the costs and headaches of administering that many boxes, etc. For a lot of Python users, significant speedups are a huge win. However, I don't think fixing CPython (through GIL removal or anything else) is the answer, and Jython isn't the answer either. Python's future is in PyPy, or should be. Why would a self-respecting Python implementation be written in (yikes) C or (yucch) Java, if it can be written in Python? So I hope that PyPy's future directions include true parallelism. From rcdailey at gmail.com Tue Sep 25 23:32:05 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 25 Sep 2007 22:32:05 -0500 Subject: Invoking python through C++: How to? In-Reply-To: References: <496954360709251010q159199a4h9dd2b0e2ecad7a01@mail.gmail.com> Message-ID: <496954360709252032j1298b259l54659b3bfc7c2a37@mail.gmail.com> On 9/25/07, Gabriel Genellina wrote: > > If you don't want to "share" objects between Python and C++, that's the > simplest way. > Or, look at the document "Extending and Embedding the Python Interpreter" > > > -- > Gabriel Genellina Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From robin at reportlab.com Fri Sep 28 07:50:54 2007 From: robin at reportlab.com (Robin Becker) Date: Fri, 28 Sep 2007 12:50:54 +0100 Subject: recipient validation with smtplib In-Reply-To: <9afea2ac0709280433n361ce4fx2a26a05de2b1b1ae@mail.gmail.com> References: <46FCE387.9070601@chamonix.reportlab.co.uk> <9afea2ac0709280433n361ce4fx2a26a05de2b1b1ae@mail.gmail.com> Message-ID: <46FCEA9E.3030700@chamonix.reportlab.co.uk> Tim Williams wrote: > On 28/09/2007, Robin Becker wrote: >> Is there a way to use smtplib to get recipient validation. I can use smtplib >> quite happily to send emails using the locahost's sendmail, but sendmail is just >> fire and forget, so some bad addresses eg idiot at www.dingo.zzz don't cause any >> error in the sending application. I know some smtp setups do enforce recipient >> validation, but it doesn't seem terribly easy to do this with sendmail. I >> wondered if there were some way to do this in python? > > There is no way of validating *every* email address you send to using > SMTP alone. Some servers accept every address and bounce later - as > you have found out. So for the purpose of the SMTP client, or relaying > server, the address is valid at sending time to those servers. > > Checking DNS for MX records is a possibility for removing some bad > addresses, but it's not fool proof as the RFCs don't require MX > records to exist for a domain to be able to receive email. If no MX > records are present, one (and only one!) IP address returned from the > domain's A record(s) should be tried. > > HTH :) Thanks, it's at least ammunition for me to say it cannot easily be done. I found this milter http://www.jmaimon.com/sendmail/callahead-milter/ but I think this will cause every send to be checked which is probably not what we need. -- Robin Becker From gagsl-py2 at yahoo.com.ar Wed Sep 5 19:46:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Sep 2007 20:46:09 -0300 Subject: Sort of an odd way to debug... References: <1188933503.704007.285590@22g2000hsm.googlegroups.com> <1i3xrwm.ah5pxyzzlxnaN%aleax@mac.com> Message-ID: En Wed, 05 Sep 2007 02:15:52 -0300, Alex Martelli escribi?: > xkenneth wrote: > ... >> What I'd like to do, is define a base class. This base class would >> have a function, that gets called every time another function is >> called (regardless of whether in the base class or a derived class), >> and prints the doc string of each function whenever it's called. I'd >> like to be able to do this without explicitly specifying the function >> inside all of the other functions of a base class or derived class. > > So you need to write a metaclass that wraps every function attribute of > the class into a wrapper performing such prints as you desire. [...] > > import inspect > class MetaWrapFunctions(type): > def __init__(cls, name, bases, attrs): > for k, f in attrs.iteritems(): > if inspect.isfunction(f): > attrs[k] = make_printing_wrapper(f) > type.__init__(cls, name, bases, attrs) > > Should behave as you described. I have not tested the code I'm > suggesting (so there might be some errors of detail) but the general > idea should work. After playing a bit with the code I found a problem, __init__ is too late, changes to `attrs` are not reflected in the class namespace. Using __new__ instead is OK. The metaclass should be then: import inspect class MetaWrapFunctions(type): def __new__(cls, name, bases, attrs): for k, f in attrs.iteritems(): if inspect.isfunction(f): attrs[k] = make_printing_wrapper(f) return super(MetaWrapFunctions, cls).__new__(cls, name, bases, attrs) [another way would be to keep __init__ but using setattr(cls, k, wrapper(...)] -- Gabriel Genellina From mrc2323 at cox.net Thu Sep 13 17:59:44 2007 From: mrc2323 at cox.net (Michael R. Copeland) Date: Thu, 13 Sep 2007 14:59:44 -0700 Subject: How to Start Message-ID: I've decided that Python is a language/environment I'd like to learn (I've been a professional programmer for 45+ years), but I really don't know where and how to start! I have a number of books - and am buying some more - but because of the bewildering number of after-market packages, environments, and add-ons, I am really quite perplexed about starting. 8<{{ Yes, I could fire up the interactive mode and play with some statements...but I consider that sort of thing for programming neophytes or experimenting with specific issues. First, I want to develop a simple Windows application, and because of the plethora of "stuff" the Python world offers, I don't know where to begin. For example, what basic, easy-to-use interface might I start with to build a simple text file parsing and analysis program? That is, I'd like to start with a simple Windows shell that prompts for a file name, processes it, and then displays some result. I am certainly impressed with the apparent experience and openness of the regular players here, but the discussions here (and in c.l.p.announce) truly presume knowledge and experience with Python I don't yet have. Yes, for even a very experienced programmer, entering the Python world is very daunting - but I want to get started. Please advise. TIA From carsten at uniqsys.com Mon Sep 10 11:12:26 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 10 Sep 2007 11:12:26 -0400 Subject: printing list containing unicode string In-Reply-To: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> References: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> Message-ID: <1189437146.7187.7.camel@dot.uniqsys.com> On Mon, 2007-09-10 at 06:59 -0700, Xah Lee wrote: > If i have a nested list, where the atoms are unicode strings, e.g. > > # -*- coding: utf-8 -*- > ttt=[[u"?",u"?"], [u"???"],...] > print ttt > > how can i print it without getting the u'\u1234' notation? > i.e. i want it print just like this: [[u"?"], ...] > > I can of course write a loop then for each string use > "encode("utf-8")", but is there a easier way? It's not quite clear why you want to do this, but this is how you could do it: print repr(ttt).decode("unicode_escape").encode("utf-8") However, I am getting the impression that this is a "How can I use 'X' to achieve 'Y'?" question instead of the preferable "How can I achieve 'Y'?" type of question. In other words, printing the repr() of a list might not be the best solution to reach the actual goal, which you have not stated. HTH, -- Carsten Haese http://informixdb.sourceforge.net From paul.hankin at gmail.com Sun Sep 30 19:07:36 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 30 Sep 2007 23:07:36 -0000 Subject: s.split() on multiple separators In-Reply-To: <1191179790.181227.323480@k79g2000hse.googlegroups.com> References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> <1191179790.181227.323480@k79g2000hse.googlegroups.com> Message-ID: <1191193656.196253.242100@19g2000hsx.googlegroups.com> On Sep 30, 8:16 pm, mrk... at gmail.com wrote: > > > c=' abcde abc cba fdsa bcd '.split() > > > dels='ce ' > > > for j in dels: > > > cp=[] > > > for i in xrange(0,len(c)-1): > > > The "-1" looks like a bug; remember in Python 'stop' bounds > > are exclusive. The indexes of c are simply xrange(len(c)). > > Yep. Just found it out, though this seems a bit counterintuitive to > me, even if it makes for more elegant code: I forgot about the high > stop bound. You made a common mistake of using a loop index instead of iterating directly. Instead of: for i in xrange(len(c)): cp.extend(c[i].split(j)) Just write: for words in c: cp.extend(words.split(j)) Then you won't make a bounds mistake, and this snippet becomes a LOT more readable. (Of course, you're better using re.split instead here, but the principle is good). -- Paul Hankin From gnewsg at gmail.com Mon Sep 10 21:30:59 2007 From: gnewsg at gmail.com (billiejoex) Date: Mon, 10 Sep 2007 18:30:59 -0700 Subject: distutils question Message-ID: <1189474259.573612.61270@57g2000hsv.googlegroups.com> Hi there, I'm having problems with creating an installer for a module of mine by using distutils. I'll try to explain my problem as clear as I can (sorry but English is not my first language). This is the structure of my module: -------------------------------- setup.py mypackage/ __init__.py module.py demo/ script.py test/ test_script.py test test_module.py -------------------------------- By using distutils in such way a 'mypackage' directory within 'module.py' is created in python's 'site-packages' directory: from distutils.core import setup setup( ... packages = ['mypackage'], ) The problem is that I can't find a way for including "demo" and "test" directories (along with files contained in them) into "site-packages/ mypackage" directory. The only way I found is *moving* 'demo' and 'test' directories into 'mypackage' but I would want to avoid that, if possible. Could someone point me in the right direction? I passed the entire night without finding a clue... From rcdailey at gmail.com Wed Sep 26 11:51:55 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 26 Sep 2007 10:51:55 -0500 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> <496954360709251421l578b9dfdwcc0e67d293ede1f3@mail.gmail.com> <496954360709251516teda6f2dwe8190236029e3688@mail.gmail.com> Message-ID: <496954360709260851r2c0e1382x29e812484d764920@mail.gmail.com> Even better! Now I can drop the regular expression that did the same thing :) Thanks! On 9/26/07, Fredrik Lundh wrote: > > Robert Dailey wrote: > > > Hmm, ElementTree.tostring() also adds a space between the last character > > of the element name and the />. Not sure why it is doing this. > > ET is commonly used to generate (X)HTML fragments, and that space > provides partial HTML compatibility. > > since the default serializer never generates CDATA sections, it should > be safe to simply do a text.replace(" />", "/>") on the resulting string. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nytrokiss at gmail.com Sun Sep 30 02:59:42 2007 From: nytrokiss at gmail.com (James Matthews) Date: Sat, 29 Sep 2007 23:59:42 -0700 Subject: New to python In-Reply-To: <46ff326e$0$17745$9b622d9e@news.freenet.de> References: <1191126010.260942.89230@y42g2000hsy.googlegroups.com> <46ff326e$0$17745$9b622d9e@news.freenet.de> Message-ID: <8a6b8e350709292359h1710bb13je8f146835a472913@mail.gmail.com> Both are good however when looking for a book i would recommend core python programming version 2! Enjoy OOP On 30 Sep 2007 05:21:50 GMT, Stargaming wrote: > > On Sat, 29 Sep 2007 21:20:10 -0700, Googy wrote: > > > I am new to python... > > > > The programming language i know well is C Can any one recommend me the > > good ebook for beginners. I have loads of ebooks but i am not able to > > decide which to start with which book. Also i am learning XML so later > > on i can switch to books on Python and XML but initially which book to > > read?? > > > > Please help... > > Generically, `A byte of Python`_ and `Dive into Python`_ are pretty > common. ABOP has a few comments for C programmers as well, AFAIK. > > If you already got a few (e)books, you should perhaps just look through > all of them and then, sequentially, read them. > > .. _A byte of Python: http://www.byteofpython.info/download/ > .. _Dive into Python: http://www.diveintopython.org/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/mens/cufflinks.html http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbellon at sbellon.de Fri Sep 28 16:56:03 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Fri, 28 Sep 2007 22:56:03 +0200 Subject: List search References: Message-ID: <20070928225603.20575a72@cube.tz.axivion.com> On Fri, 28 Sep, Kevin Walzer wrote: > I'm having a problem with searching a list. Here's my code: > > mylist = ['x11', 'x11-wm', 'x11-system'] > > for line in mylist: > if 'x11' in line: > print line Just compare for equality: if line == 'x11': or print "\n".join(x for x in mylist if x == 'x11') -- Stefan Bellon From ptmcg at austin.rr.com Tue Sep 25 11:14:02 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 25 Sep 2007 08:14:02 -0700 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> Message-ID: <1190733242.746403.264650@o80g2000hse.googlegroups.com> On Sep 24, 11:23 pm, "Gabriel Genellina" wrote: > En Mon, 24 Sep 2007 23:51:57 -0300, Robert Dailey > escribi?: > > > What I meant was that it's not an option because I'm trying to learn > > regular > > expressions. RE is just as built in as anything else. > > Ok, let's analyze what you want. You have for instance this text: > "" > which should become > "" > > You have to match: > (opening angle bracket)(any word)(closing angle bracket)(opening angle > bracket)(slash)(same word as before)(closing angle bracket) > > This translates rather directly into this regular expression: > > r"<(\w+)>" > > where \w+ means "one or more alphanumeric characters or _", and being > surrounded in () creates a group (group number one), which is > back-referenced as \1 to express "same word as before" > The matched text should be replaced by (opening <)(the word > found)(slash)(closing >), that is: r"<\1/>" > Using the sub function in module re: > > py> import re > py> source = """ > ... > ... > ... > ... > ... """ > py> print re.sub(r"<(\w+)>", r"<\1/>", source) > > > > > > > Now, a more complex example, involving tags with attributes: > --> > > You have to match: > (opening angle bracket)(any word)(any sequence of words,spaces,other > symbols,but NOT a closing angle bracket)(closing angle bracket)(opening > angle bracket)(slash)(same word as before)(closing angle bracket) > > r"<(\w+)([^>]*)>" > > [^>] means "anything but a >", the * means "may occur many times, maybe > zero", and it's enclosed in () to create group 2. > > py> source = """ > ... > ... > ... """ > py> print re.sub(r"<(\w+)([^>]*)>", r"<\1\2 />", source) > > > > > Next step would be to allow whitespace wherever it is legal to appear - > left as an exercise to the reader. Hint: use \s* > > -- > Gabriel Genellina And let's hope the OP doesn't have to parse anything truly nasty like: -- Paul From zzbbaadd at aol.com Wed Sep 19 17:01:18 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 19 Sep 2007 14:01:18 -0700 Subject: Google and Python In-Reply-To: References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> Message-ID: <1190235678.019823.315850@o80g2000hse.googlegroups.com> On Sep 19, 1:02 pm, Erik Jones wrote: > is usually Apache at most sites? > > No an http server and application server are two different things. > An http server services requests of a web server those requests can > be for static files or for services of a local application in which > case the request if forwarded on to the application. An application > services requests of an application. They are separate concepts, > often chained, although they are sometimes implemented together. > What they are saying here is that they have built a highly optimizing > custom web server in C++ that services web requests for services of > applications written in any of the three listed languages. So, yes, > in this case it is what is often Apache in other installations. > OK, thanks. Would you know what technique the custom web server uses to invoke a C++ app (ditto for Java and Python) CGI is supposed to be too slow for large sites. From sjmachin at lexicon.net Mon Sep 17 18:07:02 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 17 Sep 2007 15:07:02 -0700 Subject: qa In-Reply-To: References: Message-ID: <1190066822.258702.158240@g4g2000hsf.googlegroups.com> On Sep 18, 7:15 am, Shawn Minisall wrote: > I'm trying to get a space in between these two strings but it's ignoring > the space in between when it prints. > > >>> string.capwords (string.join([s1 + " " + s2])) * 3 > 'Spam Ni!Spam Ni!Spam Ni!' > >>> -1. "qa" as a subject heading scarcely invites potential readers to bother opening up your posting ... 0. Which 2 strings? You have got a space between 'spam' and 'ni'. 1. string.join([ONLY_ONE_element]) is a big fat no-operation. 2. It's ignoring what space when it prints? 3. Break your expression down into simple steps, so that you can see where you are going wrong, like this: >>> import string >>> s1 = 'spam' >>> s2 = 'ni!' >>> s3 = s1 + " " + s2 >>> s3 'spam ni!' >>> list1 = [s3] >>> list1 ['spam ni!'] >>> s4 = string.join(list1) >>> s4 'spam ni!' >>> s5 = string.capwords(s4) >>> s5 'Spam Ni!' >>> s6 = s5 * 3 >>> s6 'Spam Ni!Spam Ni!Spam Ni!' >>> Now: which part(s) of the above are not doing what you expected, and what did you expect, and what is the basis for your expectation? 4. Almost all of the string module is deprecated -- instead you should be using methods of string objects. Are you using an old book or tutorial? If so, throw it away; it's well out of date. 5. capwords breaks the string into words (like the following) which is a bit silly on a string that you've just laboriously constructed. >>> def capwords(s): ... return " ".join(w.capitalize() for w in s.split()) ... >>> capwords('foo bar zot') 'Foo Bar Zot' >>> 6. What are you actually trying to achieve? From crcarleRemoveThis at BOGUSsandia.gov Mon Sep 17 20:01:38 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Mon, 17 Sep 2007 17:01:38 -0700 Subject: Entering strings as user input but interpreting as Python input (sort of) Message-ID: Hi: I'm writing a Python program, a hex line editor, which takes in a line of input from the user such as: >>> cmd = raw_input('-').split() -e 01 02 "abc def" 03 04 >>> cmd ['e', '01', '02', '"abc', 'def"', '03', '04'] Trouble is, I don't want to split the quoted part where the space occurs. So I would prefer the resulting list to contain: ['e', '01', '02', '"abc def"', '03', '04'] Furthermore, if the user entered: -e 01 02 "abc \"def\"\r\n" 03 04 I would want the quoted part to be interpreted as if I entered it into Python itself (recognize escape sequences, and not split at spaces) as: >>> s = '"abc \"def\"\r\n"' >>> print s "abc "def" " >>> In other words, if a quoted string occurs in the user input, I want only that part to be treated as a Python string. Even more horrifying is that I want the outer quotes to remain as is (which Python doesn't do, of course). I have begun to solve this problem by winding up writing what amounts to a custom split() method (I call it hsplit(), a function) which is a DFA that implements some of Python's string lexical analysis. Code shown below. The point of this in the context of the hex editor is that the user should be able to enter hex bytes without qualifications like "0xXX" but rather as simply: "0A 1B 2C" etc. but also be able to input a string without having to type in hex ASCII codes. Hence the following input would be valid (the 'e' is the edit command to the editor): -e 01 02 "a string with newline\n" 3d 4e 5f -p Is there a simpler way? ---------------------------------------------------------------- HSTRIP_NONE = 0 HSTRIP_IN_WORD = 1 HSTRIP_IN_QUOTE = 2 HSTRIP_IN_ESC = 3 def hsplit(string): lst = [] word = [] state = HSTRIP_NONE # not in word for c in string: if state == HSTRIP_NONE: if c == '"': word.append(c) state = HSTRIP_IN_QUOTE elif c != ' ': word.append(c) state = HSTRIP_IN_WORD # else c == ' ', so pass elif state == HSTRIP_IN_QUOTE: if c == '"': word.append(c) lst.append(''.join(word)) word = [] state = HSTRIP_NONE elif c == '\\': state = HSTRIP_IN_ESC else: word.append(c) elif state == HSTRIP_IN_ESC: if c == '\\': word.append(c) state = HSTRIP_IN_QUOTE elif c == '"': word.append(c) state = HSTRIP_IN_QUOTE elif c == 'n': word.append('\n') state = HSTRIP_IN_QUOTE else: # c == non escape or quote # for unrecognized escape, just put in verbatim word.append('\\') word.append(c) state = HSTRIP_IN_QUOTE else: # if state == HSTRIP_IN_WORD if c == ' ' or c == '"': lst.append(''.join(word)) if c == '"': word = [c] state = HSTRIP_IN_QUOTE else: word = [] state = HSTRIP_NONE else: word.append(c) # this only happens if you run out of chars in string before a state change: if word: lst.append(''.join(word)) return lst ---------------------------------------------------------------- -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Sep 10 07:53:08 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 10 Sep 2007 13:53:08 +0200 Subject: Python syntax wart References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> <5ki2sdF3nr68U1@mid.individual.net> <5kk8p0F3vfqqU1@mid.uni-berlin.de> <5kkcmvF3vfqqU3@mid.uni-berlin.de> Message-ID: <5kkph4F486kdU2@mid.individual.net> Lawrence D'Oliveiro wrote: > In message <5kkcmvF3vfqqU3 at mid.uni-berlin.de>, Marc 'BlackJack' >> I see a tree structure here ... > > Good, you're improving. Tree structures can't, IMHO, be called two-dimensional. Although, you can represent them with a two-dimensional graph. If the tree gets more complex this can become very messy. >> And this is also easily written that way in Python if you don't >> insist on the line break after the ``if`` or can live with >> backslashes. > > Which is precisely the point. You're the first person I see using a complete line just for an "if" or "for". Is this for tuning the code line count? Regards, Bj?rn -- BOFH excuse #194: We only support a 1200 bps connection. From tgrav at mac.com Wed Sep 5 10:07:01 2007 From: tgrav at mac.com (Tommy Grav) Date: Wed, 5 Sep 2007 10:07:01 -0400 Subject: handling modules in packages In-Reply-To: References: <619B716A-C1EB-42DF-9702-E288AD04F613@mac.com> Message-ID: <384C9792-3923-42C6-8F9C-E3EB19B8811A@mac.com> >> > The simplest thing to do would be to have PyAstro.__init__.py > import all > the sub-modules, and define __all__ as the set of names that the > package > should inject into importing modules. > > Then you could write (for example) > > from PyAstro import numpy, constants, conversion, obsrvations > > However if you are simply worried about run-time efficiency then don't > be: once a module is imported further imports essentially reduce to > checking that the module is already present in the sys.modules > dict, and > so take almost no time at all. So am I understanding it right that a second import numpy statement in a different module (and thus a different namespace) just results in a binding to the already existing numpy "object"? Cheers Tommy From stefan.behnel-n05pAM at web.de Thu Sep 20 07:55:10 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 20 Sep 2007 13:55:10 +0200 Subject: lxml and identification of elements in source In-Reply-To: <46f18900$0$5083$ba4acef3@news.orange.fr> References: <46f18900$0$5083$ba4acef3@news.orange.fr> Message-ID: <46F25F9E.7010700@web.de> Laurent Pointal wrote: > I use lxml to parse a document, modify some elements in the tree, run > xinclude on it (thanks to Stefan Behnel for the pointer), and finally use > the data to feed my sax-aware tool. > > To report warnings/errors to the user (not related to XML itself, but to > things like missing source for a cross-reference by example), is there a > way to get the source-file and line/column of an element ? > > [note: these informations are available when lxml parse the source, but are > they kept anywhere in the document tree ?] The lxml mailing list is a good place to ask these questions - although having the name come up in c.l.py from time to time makes for some good advertising :) Elements have a "sourceline" property that returns the line the Element was parsed from. It returns None if the Element was created through the API. Also, lines may become meaningless when you merge documents, e.g. xincluded elements will refer to the line in the xincluded document, not some magically calculated line in the target document. The column is not stored for an Element after parsing is finished (no, we can't change that). You can call getroottree() on an Element to retrieve it's root ElementTree, which knows about the URL (and other things) in its docinfo property. Stefan From garyjefferson123 at gmail.com Tue Sep 11 12:14:56 2007 From: garyjefferson123 at gmail.com (garyjefferson123 at gmail.com) Date: Tue, 11 Sep 2007 09:14:56 -0700 Subject: customizing a logging logger In-Reply-To: <1187412814.493872.325190@j4g2000prf.googlegroups.com> References: <1187412814.493872.325190@j4g2000prf.googlegroups.com> Message-ID: <1189527296.426004.17600@19g2000hsx.googlegroups.com> I think the following question is clearer. I want to make it so that method1 below can be transformed: logger = logging.getLogger("somelogger") class SomeOp: def __init__(self, ctx): self.ctx = ctx def method1(self): logger.info("%s: here's a message", self.ctx) logger.debug("%s: msg #2", self.ctx) v = 'yessir' logger.debug("%s: msg #3 %s", self.ctx, v) into something like: def method1(self): logger.info("here's a message") logger.debug("msg #2") v = 'yessir' logger.debug("msg #3 %s", v) What is the best way to do this, so that I don't have to manually put the self.ctx in the log string in hundreds of different places? Thanks, Gary From steve at holdenweb.com Fri Sep 7 15:13:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Sep 2007 12:13:05 -0700 Subject: unexpected behavior: did i create a pointer? In-Reply-To: References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> Message-ID: Steven D'Aprano wrote: > On Fri, 07 Sep 2007 11:46:38 +0200, Wildemar Wildenburger wrote: > >> gu wrote: >>> hi to all! >>> after two days debugging my code, i've come to the point that the >>> problem was caused by an unexpected behaviour of python. or by lack of >>> some information about the program, of course! i've stripped down the >>> code to reproduce the problem: >>> >>> [snip FAQ] >> Yes, basically you *created* a pointer. That's all that python has: >> pointers. > > No, you are confusing the underlying C implementation with Python. Python > doesn't have any pointers. CPython is implemented with pointers. PyPy, > being written entirely in Python, is implemented with Python objects like > lists and dicts. Jython, being implemented in Java, probably isn't > implemented with pointers either -- although of course the underlying > Java compiler might be. IronPython and Python for .Net, I have no idea > how they work. Could be magic for all I know. (Probably necromancy.) > > Naturally, regardless of whether you are using CPython, IronPython, PyPy > or some other variety of Python, the objects available to you include > ints, floats, strings, lists, dicts, sets and classes... but not pointers. > > Nor does it include "peek" and "poke" commands for reading and writing > into random memory locations. Python is not C, and it is not Basic, nor > is it Forth or Lisp or assembler, and you shouldn't hammer the round peg > of Python objects into the square hole of C pointers. > This seems to be obscuring the real issue for the sake of hammering an error in vocabulary. gu said """Yes, basically you *created* a pointer. That's all that python has: pointers.""" and you took issue with that, ultimately saying """the objects available to you include ints, floats, strings, lists, dicts, sets and classes... but not pointers""". You are both right, and you are also both wrong. Python does indeed provide a rich set of strongly typed object classes, and so clearly to say "Python only has pointers" is strictly an error. However, this overlooks the fact that *all* names in Python, and *all* items in container objects (lists, tuples, dicts ...) hold references to objects. I mention this because it *is* significant to the semantics of assignment. From the point of view of a C programmer Python might actually look quite like a language in which all data objects had to be malloc'd, and the only variables were pointers to. Assignment (binding) in Python creates copies of references to objects, not copies of the objects themselves. I have deliberately omitted discussion of the automatic dereferencing that takes place in Python, thereby allowing us to treat names as though they contained objects, but the fact remains that names *don't* contain objects, they contain references to objects. If you want to regard a reference and a pointer as two different things then I guess that's your nit to pick. But I don't think the original assertions quite justified your scathing remarks about "peek" and "poke". regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From arkanes at gmail.com Tue Sep 4 15:26:53 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 4 Sep 2007 14:26:53 -0500 Subject: Sort of an odd way to debug... In-Reply-To: <1188933503.704007.285590@22g2000hsm.googlegroups.com> References: <1188933503.704007.285590@22g2000hsm.googlegroups.com> Message-ID: <4866bea60709041226h741c6774l1fa19177bd329324@mail.gmail.com> On 9/4/07, xkenneth wrote: > All, > > Sorry for the vague topic, but I really didn't know how to > describe what I want to do. I'd like to almost do a traceback of my > code for debugging and I thought this would be a really cool way to do > it if possible. > > What I'd like to do, is define a base class. This base class would > have a function, that gets called every time another function is > called (regardless of whether in the base class or a derived class), > and prints the doc string of each function whenever it's called. I'd > like to be able to do this without explicitly specifying the function > inside all of the other functions of a base class or derived class. > > Here's what I think it would look like: > > class Base: > __init__(self,debug=False): > if debug: > self.debug = debug > > def functionThatAlwaysGetsCalled(self): > print self.__docstring__ > > class Derived(Base): > """This function prints something""" > def printSometing(something) > #ghost function get's called here > print something > > Output would be: > This function prints something > something > > Thanks for any help! > This approach won't work, because you need cooperation from child classes to trigger your printing. A trace function (see sys.settrace) is probably more useful. From grante at visi.com Sat Sep 15 12:25:15 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Sep 2007 16:25:15 -0000 Subject: how to join array of integers? References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <46EBE498.9040800@ehas.org> Message-ID: <13eo1rb73mg8b77@corp.supernews.com> On 2007-09-15, Erik Jones wrote: >>> print ''.join([str(i) for i in [1,2,3]]) >> >> It's better to use generator comprehension instead of LC: >> >> ",".join(str(i) for i in [1, 2, 3]) > > Why is that? That entire expression must be evaluated to obtain the > result, so what is the advantage of using a generator comprehension > v. a list comprehension? The generator avoids creating the intermediate list -- it generates the intermediate values on the fly. For short sequences it probably doesn't matter much. For a very long list it's probably noticable. -- Grant Edwards grante Yow! Mr and Mrs PED, can I at borrow 26.7% of the RAYON visi.com TEXTILE production of the INDONESIAN archipelago? From cscheit at lstm.uni-erlangen.de Tue Sep 18 09:58:42 2007 From: cscheit at lstm.uni-erlangen.de (Christoph Scheit) Date: Tue, 18 Sep 2007 15:58:42 +0200 Subject: Memory Problem In-Reply-To: <5la11gF71rf0U2@mid.uni-berlin.de> References: <5la11gF71rf0U2@mid.uni-berlin.de> Message-ID: <200709181558.43026.cscheit@lstm.uni-erlangen.de> On Tuesday 18 September 2007 15:10, Marc 'BlackJack' Rintsch wrote: > On Tue, 18 Sep 2007 14:06:22 +0200, Christoph Scheit wrote: > > Then the data is added to a table, which I use for the actual > > Post-Processing. The table is actually a Class with several "Columns", > > each column internally being represented by array. > > Array or list? array More details: class DBTable: # the class DBTable has a list, each list entry referencing a DBColu bject self.cols = [] self.dict = {, -1} #the dictionary is used to look up if an entry # already exists class DBColumn: # has a name (string and a datatype (int, float, e.g.) as attribute plus self.data = array('f') # an array of type float I have to deal with several millions of data, actually I'm trying an example with 360 grid points and 10000 time steps, i.e. 3 600 000 entries (and each row consits of 4 int and one float) Of course, the more keys the bigger is the dictionary, but is there a way to evaluate the actual size of the dictionary? Greets and Thanks, Chris > > > # create reader > > breader = BDBReader("", "", "#") > > > > # read data > > bData = breader.readDB(dbFileList[0]) > > > > # create table > > dTab = DBTable(breader.headings, breader.converters, [1,2]) > > addRows(bData, dTab) > > > > Before I add a new entry to the table, I check if there is already an > > entry like this. To do so, I store keys for all the entries with > > row-number in a dictionary. What about the memory consumption of the > > dictionary? > > The more items you put into the dictionary the more memory it uses. ;-) > > > Here the code for adding a new row to the table: > > > > # check if data already exists > > if (self.keyDict.has_key(key)): > > rowIdx = self.keyDict[key] > > for i in self.mutableCols: > > self.cols[i][rowIdx] += rowData[i] > > return > > > > # key is still available - insert row to table > > self.keyDict[key] = self.nRows > > > > # insert data to the columns > > for i in range(0, self.nCols): > > self.cols[i].add(rowData[i]) > > > > # add row i and increment number of rows > > self.rows.append(DBRow(self, self.nRows)) > > self.nRows += 1 > > > > Maybe somebody can help me. If you need, I can give more implementation > > details. > > IMHO That's not enough code and/or description of the data structure(s). > And you also left out some information like the number of rows/columns and > the size of the data. > > Have you already thought about using a database? > > Ciao, > Marc 'BlackJack' Rintsch -- ============================ M.Sc. Christoph Scheit Institute of Fluid Mechanics FAU Erlangen-Nuremberg Cauerstrasse 4 D-91058 Erlangen Phone: +49 9131 85 29508 ============================ From x_john at timney.eclipse.co.uk Tue Sep 11 14:50:33 2007 From: x_john at timney.eclipse.co.uk (John Timney (MVP)) Date: Tue, 11 Sep 2007 19:50:33 +0100 Subject: Car-ac-systems References: <1189532573.728913.306470@g4g2000hsf.googlegroups.com> <5ko2rjF4om2bU1@mid.uni-berlin.de> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:5ko2rjF4om2bU1 at mid.uni-berlin.de... > On Tue, 11 Sep 2007 17:42:53 +0000, Zentrader wrote: > >> >> What is it about "please do not top-post" that you have difficulty >> understanding? Or do "MVP"s feel that their time is so much more >> valuable than anyone else's that they are free to ignore the norms? >> >> Who made this the norm? > > Common sense and (western) reading habits. > >> In my travels through web-land, it appears to be the opposite. > > You must travel strange territories. ;-) > >> Don't waste space repeating everything in every post, and it wastes >> everyone's time by have to go over the same thing again and again. > > That's why you trim the quoted part to the minimum to understand what one > is answering. Top posting and full quoting wastes time for people who > want to see the context because context and answer are way apart and in > the > wrong order so one has to scroll back and forth to keep track of the > discussion. > > Ciao, > Marc 'BlackJack' Rintsch I like top posted threads, its my preferred response method - and actually also how I prefer to read a thread. Normally, I and the thread followers are familiar with a threads context - and don't need to read down to get the context of a response. Not much of a hardship really and just as I give my time freely in answering a thread - everyone else can chose freely to read it or ignore. I don't though have no issues with people who chose to bottom post, or respond with the full thread if its relevent, or trim it. If the answer is relevent, I'll gladly spend the time reading it from any direction. Regards John Timney (MVP) http://www.johntimney.com http://www.johntimney.com/blog From planetmatt at gmail.com Wed Sep 5 06:58:54 2007 From: planetmatt at gmail.com (planetmatt) Date: Wed, 05 Sep 2007 10:58:54 -0000 Subject: Looping through File Question Message-ID: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> I am a Python beginner. I am trying to loop through a CSV file which I can do. What I want to change though is for the loop to start at row 2 in the file thus excluding column headers. At present I am using this statement to initiate a loop though the records: for line in f.readlines(): How do I start this at row 2? From fructidor00 at gmail.com Sun Sep 9 18:03:15 2007 From: fructidor00 at gmail.com (GuillaumeC) Date: Sun, 09 Sep 2007 22:03:15 -0000 Subject: UnboundLocalError on global variable In-Reply-To: References: Message-ID: <1189375395.552350.196510@50g2000hsm.googlegroups.com> > def processLogEntry(entry): # ADD THIS TO YOUR CODE global cmterID_ > > revision = int(entry.getRevision()) > commiter = str(entry.getAuthor()) > datetime = getTimeStamp(entry.getDate()) > message = str(entry.getMessage()) > > Commiter_[0] = cmterID_ //HERE's THE PROBLEM The reason why it does not work is that there is an assignment to cmterID_ in your function - even if it is after the problem. As a consequence, the bytecode compiler makes this name local, and the name is unbound. The quick fix is to add the global statement as above. There is a good explanation here: http://paddy3118.blogspot.com/2006/07/python-functions-assignments-and-scope.html May I suggest that you use less global variables, for instance enclosing your method in a class? From duncan.booth at invalid.invalid Thu Sep 6 04:52:02 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Sep 2007 08:52:02 GMT Subject: Autogenerate functions (array of lambdas) References: <1189067829.685339.50550@y42g2000hsy.googlegroups.com> Message-ID: Chris Johnson wrote: > 2) Is there a better or preferred method than the one I've found? > Use function default arguments to keep the current value of i at the point where you define the function. a = [(lambda n=i: n) for i in range(10)] From bj_666 at gmx.net Thu Sep 13 13:33:33 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Sep 2007 17:33:33 GMT Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> <46e96aaa$0$7685$9b4e6d93@newsspool2.arcor-online.net> <1189703457.297526.172460@50g2000hsm.googlegroups.com> Message-ID: <5ktajdF57ml9U2@mid.uni-berlin.de> On Thu, 13 Sep 2007 10:10:57 -0700, TheFlyingDutchman wrote: >> Isn't one of the main ideas behind python that it doesn't force you to >> do (well, declare) anything? And by "ideas" I mean "design decisions". >> Thats exactly what makes python great for prototyping; you just do it >> and see if it works. As soon as you need to declare things you have to >> change stuff in at least 2 places for every change of heart you have. >> >> (Can you tell I'm currently forced to developing in Java? ;) (Which I'm >> currently avoiding to do, by wasting my time on usenet.)) >> > But if you are looking at code you didn't write, it's nice to be able > to see all the member variables that a class has listed separate from > method code. That information is usually in the `__init__()` method and the class docstring. > I think static typing helps in trying to deduce what code is doing, > particularly when you are looking at function definitions. You don't > have to work to find out what type of variables it takes. This should either be obvious or in the docstring. Ciao, Marc 'BlackJack' Rintsch From ebgssth at gmail.com Tue Sep 18 07:15:34 2007 From: ebgssth at gmail.com (js) Date: Tue, 18 Sep 2007 20:15:34 +0900 Subject: Looking for web software in Python. In-Reply-To: References: Message-ID: http://wiki.python.org/moin/WebApplications?highlight=%28%28PythonWikiEngines%29%29 Hope this helps On 9/18/07, Kevin Ar18 wrote: > > Are any of the following pieces of web software available in Python (under a non-copyleft license like BSD or MIT or Python license)? > > > Mailing list - with web accessable archive and list maintenance. > Source control > Wiki System > > Again, only non-copyleft licenses like MIT, BSD, or public domain. > > > Or would I be better off with PHP? > > > > BTW, does anyone know where that project is that was working on a forum made with Python? > _________________________________________________________________ > More photos; more messages; more whatever ? Get MORE with Windows Live? Hotmail(r). NOW with 5GB storage. > http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_5G_0907 > -- > http://mail.python.org/mailman/listinfo/python-list > From eduardo.padoan at gmail.com Fri Sep 14 21:59:13 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Fri, 14 Sep 2007 22:59:13 -0300 Subject: How to avoid overflow errors In-Reply-To: <7xmyvoag7j.fsf@ruckus.brouhaha.com> References: <13em8vnr527rq20@corp.supernews.com> <7xmyvoag7j.fsf@ruckus.brouhaha.com> Message-ID: On 14 Sep 2007 18:08:00 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Eduardo O. Padoan" writes: > > Not totally unrelated, but in Py3k, as it seems, overflows are really > > things of the past: > > > > > > Python 3.0a1 (py3k:58061, Sep 9 2007, 13:18:37) > > [GCC 4.1.3 20070831 (prerelease) (Ubuntu 4.1.2-16ubuntu1)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> class MyInt(int): > > ... pass > > ... > > >>> import sys > > >>> MyInt(sys.maxint) > > 2147483647 > > >>> MyInt(sys.maxint+1) > > 2147483648 > > I'd be interested in knowing what happens in 3.0a1 with > > a = itertools.count(sys.maxint) > print a.next() > print a.next() >>> print(next(a)) Traceback (most recent call last): File "", line 1, in OverflowError: cannot count beyond PY_SSIZE_T_MAX Hum, you've got me there. it is the same as in 2.x. Maybe the message should be less crypt, at least - nothing that googling for PY_SSIZE_T_MAX cant help. -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From martin at v.loewis.de Sat Sep 22 11:04:29 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 22 Sep 2007 17:04:29 +0200 Subject: uninstall python2.5 on debian In-Reply-To: References: Message-ID: <46f52efe$0$15178$9b622d9e@news.freenet.de> > I have tried make uninstall and searched the web, but that did not help me. > I guess rm -Rf python2.5 is not a wise thing to do. It's part of the solution. There is no automated install procedure; you have to manually remove everything that got installed. In /bin, it's most files that have 2.5 in their name, plus any links to them. In /lib, it's python2.5. In /include, it's python2.5. Plus a few things that I probably forgot. Regards, Martin From tdelaney at avaya.com Mon Sep 24 08:07:20 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 24 Sep 2007 20:07:20 +0800 Subject: Almost There - os.kill() In-Reply-To: <1190634935.3385.36.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > On Mon, 2007-09-24 at 19:48 +0800, Delaney, Timothy (Tim) wrote: >> Always be careful with int() incase any of the values have a leading >> zero - check the documentation for int() carefully. > > Why would leading zeroes be a problem? > >>>> int("10") > 10 >>>> int("010") > 10 >>>> int("0010") > 10 >>>> int("00010") > 10 > > Maybe you're thinking of "evil eval?" > >>>> eval("10") > 10 >>>> eval("010") > 8 Nope - pretty sure that an earlier version of Python defaulted to a radix of 0, but it appears to default to a radix of 10 in Python 2.5. In any case, I've submitted a bug report and suggested new text for the documentation of int() to make it clear what happens when a radix is not specified. Tim Delaney From mal at egenix.com Tue Sep 25 08:13:41 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 25 Sep 2007 14:13:41 +0200 Subject: database persistence with mysql, sqlite In-Reply-To: <1190502677.970811.181100@22g2000hsm.googlegroups.com> References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> Message-ID: <46F8FB75.2070409@egenix.com> On 2007-09-23 01:11, coldpizza wrote: > Hi, > > I want to run a database query and then display the first 10 records > on a web page. Then I want to be able to click the 'Next' link on the > page to show the next 10 records, and so on. > > My question is how to implement paging, i.e. the 'Next/Prev' NN > records without reestablishing a database connection every time I > click Next/Prev? Is it at all possible with cgi/mod_python? > > For example, in a NON-web environment, with sqlite3 and most other > modules, I can establish a database connection once, get a cursor > object on which I run a single 'SELECT * FROM TABLE' statement and > then use cursor.fetchmany(NN) as many times as there are still results > left from the initial query. > > How do I do the same for the web? I am not using any high-level > framework. I am looking for a solution at the level of cgi or > mod_python (Python Server Pages under Apache). To call > cursor.fetchmany(NN) over and over I need to pass a handle to the > database connection but how do I keep a reference to the cursor object > across pages? I use mysql and sqlite3 as databases, and I am looking > for an approach that would work with both database types (one at a > time). So far I have successfully used the following modules for > database access: sqlite3, mysqld, and pyodbc. > > So far, with mysql I use 'SELECT * FROM TABLE LIMIT L1, L2' where L1 > and L2 define the range for the 'Next' and 'Previous' commands. I > have to run the query every time a click a 'Next/Prev' link. But I am > not sure that this is the best and most efficient way. I suppose using > CURSOR.FETCHMANY(NN) would probably be faster and nicer but how do I > pass an object reference across pages? Is it possible without any > higher-level libraries? > > What would be the proper way to do it on a non-enterprise scale? Depends on what "enterprise" scale means to you :-) The easiest way to get excellent performance for such queries is using a long running process, mod_scgi and have the browser send a session cookie for you to use to identify the request. You can then open the connection and keep it open while the user browses the site. If you want to save yourself from most of the details, just use Zope or Plone + e.g. our mxODBC Zope DA for the database connection (it works with all the databases you mention on Windows, Linux and Mac OS X). Even if you don't want to code things using Zope/Plone, you should still consider it for taking care of all the middleware logic and then write your application as separate package which you hook into Zope/Plone using "external methods" or "Python scripts" (in their Zope sense). > Would SqlAlchemy or SqlObject make things easier with regard to > database persistence? Not really: they don't provide the session mechanisms you would need. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 25 2007) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From carsten at uniqsys.com Thu Sep 13 21:26:33 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 13 Sep 2007 21:26:33 -0400 Subject: Extending Python with C API In-Reply-To: References: Message-ID: <1189733193.3248.7.camel@localhost.localdomain> On Thu, 2007-09-13 at 18:05 -0700, Thierry Masson wrote: > Hello, > > I'm trying to use the C API to extend Python. I've looked at various > books and web sites (including the docs at python.org) and I can't get > any of the samples to work. Below is a very minimalist example that > I'm trying to get working and I was wondering if someone could tell me > where I'm going wrong. It's probably something very obvious to those > familiar with this technique. >[snip...] > The setup script builds the library OK, and I've verified that > gtestmodule.so is getting created. But when I try to run a test script > ( test.py, above) that uses the library, I get this error: > > Traceback (most recent call last): > File "test.py", line 2, in ? > import gtestmodule > ImportError: ./gtestmodule.so: undefined symbol: PyBuildValue Your module C code uses an unknown function by the name of PyBuildValue. The actual name of the function you mean is Py_BuildValue. HTH, -- Carsten Haese http://informixdb.sourceforge.net From marcobonifazi at gmail.com Thu Sep 20 11:21:06 2007 From: marcobonifazi at gmail.com (Marco Bonifazi) Date: Thu, 20 Sep 2007 15:21:06 -0000 Subject: Python and RTF In-Reply-To: <13f51i4adkseae5@corp.supernews.com> References: <1190271676.160077.99270@w3g2000hsg.googlegroups.com> <13f51i4adkseae5@corp.supernews.com> Message-ID: <1190301666.417426.13320@r29g2000hsg.googlegroups.com> On 20 Set, 16:40, Grant Edwards wrote: > On 2007-09-20, Rufman wrote: > > > Does anyone have a good rtf library for python, > > pyRTF is the only one I found. > > > have exprience with pyRTF > > Yes. > > > or a link to a good tutorial? > > Just the examples that come with pyRTF. > > FWIW, I've added support for EMF graphics and enhanced the > scaling options for graphics: > > http://groups.google.com/group/comp.lang.python.announce/browse_threa... > > -- > Grant Edwards grante Yow! Uh-oh!! I'm having > at TOO MUCH FUN!! > visi.com Oh, wonderful! Is licensed with the GPL and LGPL as like the previous versions are? Then, can I put in my closed software and at the end of my development make a donation? Marco Bonifazi From arnodel at googlemail.com Mon Sep 3 17:32:57 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 03 Sep 2007 14:32:57 -0700 Subject: trap setting attribute when the attribute is dict In-Reply-To: References: <1188845236.417709.307160@50g2000hsm.googlegroups.com> Message-ID: <1188855177.466618.53640@22g2000hsm.googlegroups.com> On Sep 3, 8:47 pm, wrote: [...] > My intention was to have a propery 'sum' in my object, and which has sum > of all the values() of the dict (i have code to make sure that the value > of dict are all numeric). I could just the propery being calculated > everytime the property got __getattr__. But I thought that it was > inefficient to calculate the same number over and over when the value is > already known. So I was thiking of calculating the number only when the > dict got modified. > > I also experimented with the idea of subclassing dict itself to > calculate the sum. Is this what would be better solution? Why not simply have a method to update the dictionary that also keeps the sum up to date? Something like that: >>> class MyObj(object): ... def __init__(self): ... self._d = {} ... self._sum = 0 ... def set_key(self, key, val): ... self._sum += val - self._d.get(key, 0) ... self._d[key] = val ... def get_key(self, key): ... return self._d[key] ... def sum(self): ... return self._sum ... >>> a = MyObj() >>> a.set_key(1, 2) >>> a.sum() 2 >>> a.set_key('a', 10) >>> a.set_key(1, 5) >>> a.sum() 15 >>> Of course this is only worth it if you need to use the sum often enough. If you update the dictionary a lot but only need the sum from time to time, then it might not be worth it at all. Of course you could subclass dict: class MyDict(dict): def __init__(self, *args, **kwargs): self._sum = sum(self.itervalues()) def __setitem__(self, key, val): self._sum += val - self.get(key, 0) dict.__setitem__(self, key, val) def sum(self): return self._sum # overload all other methods that mutate the dict # to keep _sum up to date >>> d = MyDict() >>> d.sum() 0 >>> d['a']=5 >>> d.sum() 5 >>> d['b']=10 >>> d['a']=8 >>> d.sum() 18 >>> HTH -- Arnaud From tokland at gmail.com Sat Sep 29 17:17:36 2007 From: tokland at gmail.com (tokland at gmail.com) Date: Sat, 29 Sep 2007 21:17:36 -0000 Subject: question about for cycle In-Reply-To: <1191094689.726813.235340@50g2000hsm.googlegroups.com> References: <1191073123.459709.98870@g4g2000hsf.googlegroups.com> <1191079144.724699.250470@o80g2000hse.googlegroups.com> <1191094689.726813.235340@50g2000hsm.googlegroups.com> Message-ID: <1191100656.710846.108810@o80g2000hse.googlegroups.com> On 29 sep, 21:38, Zentrader wrote: > ctr_a=0 > ctr_b=0 > while ctr_a < len(generator_a): > this_el_a = generator_a[ctr_a] > while ctr_b < len(generator_b): > this_el_b = generator_b[ctr_ b] > if something_happen: > ctr_b = len(generator_b) ## break this loop > if something_else: > ctr_a = len(generator_a) ## break outer while loop > ctr_b += 1 > ctr_a += 1 Mmm, isn't a bit complicated? Anyway, neither len() nor __getitem__ work on generators. From grante at visi.com Thu Sep 20 10:35:24 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Sep 2007 14:35:24 -0000 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190269056.975115.217050@22g2000hsm.googlegroups.com> Message-ID: <13f519cj6nor65c@corp.supernews.com> On 2007-09-20, TheFlyingDutchman wrote: > Is the only point in getting rid of the GIL to allow multi-threaded > applications? That's the main point. > Can't multiple threads also provide a performance boost versus > multiple processes on a single-core machine? That depends on the algorithm, the code, and the synchronization requirements. > OK, have to agree. Sounds like it could be a good candidate > for a fork. One question - is it a computer science maxim that > an interpreter that implements multi-threading will always be > slower when running single threaded apps? I presume you're referring to Amdahl's law. http://en.wikipedia.org/wiki/Amdahl's_law Remember there are reasons other than speed on a multi-processor platorm for wanting to do multi-threading. Sometimes it just maps onto the application better than a single-threaded solution. -- Grant Edwards grante Yow! I want you to MEMORIZE at the collected poems of visi.com EDNA ST VINCENT MILLAY ... BACKWARDS!! From duncan.booth at invalid.invalid Wed Sep 26 04:31:15 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Sep 2007 08:31:15 GMT Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> Message-ID: Mark Summerfield wrote: > As you've no doubt realised, this particular implementation gives best > performance when the pattern of use is: lots of edits, lots of > lookups, ..., and gives worst performance when the pattern of use is: > edit, lookup, edit, lookup (in which case using a dict and sorted() is > probably better). > > So there is lots of scope for someone to do a version that has good > performance for all patterns of use:-) I that's the point though: you can't write one implementation that has good performance for all patterns of use: you have to either compromise on performance somewhere, or use an implementation specifically matched to your use case. For example, if the use case was some updates followed by iterating over the first few keys only, it may be faster to use a heap for iteration. I suspect that for many use patterns you could improve performance significantly by having two levels of invalidation for the the key list: in __setitem__, if the key already exists you don't need to discard the list in __keycache (although if a key or cmp function was provided it may no longer be sorted). In that case it might be worthwhile keeping __keycache but flagging it as needing to be sorted again next time it is used. Given that Python's sort is very fast on sorted or nearly sorted lists this could provide a worthwhile speedup for cases where the values change but the keys don't change often. From michele.simionato at gmail.com Wed Sep 12 11:12:15 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 12 Sep 2007 15:12:15 -0000 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189608231.151112.147550@y42g2000hsy.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> Message-ID: <1189609935.347945.139000@19g2000hsx.googlegroups.com> On Sep 12, 4:43 pm, Charles Fox wrote: > Thanks guys -- yeah these two stategies (short s.varname; and explicit > rescoping, a=self.a etc) are more or less what I was using. That's > still kind of annoying though. > > The s.varname approach still makes numerical code much harder to read. > > I had a nasty bug with the boilerplate approach when forgetting to > reassign some of the variables back to members (self.a=a). And that's > a lot of boilerplate you need -- I thought the python way was to > minimize redundant code? (Ditching header files and curley brackets > was a main reason for me coming here). You still can play with dictionaries, for instance: def __init__(self, a, b, c): vars(self).update(locals()) correspond to self.a = a self.b = b self.c = c (and actually also to self.self =self). > I see the argument for making self explicit -- what would be wrong > with just .a instead of self.a though? That's still explicit but much > easier to read. (I think I've seen that somewhere else, is it C#?) This has been proposed many times. But self is handy because you can give a different name to it: for instance it becomes cls when you are inside a classmethod. Michele Simionato From gandalf at shopzeus.com Thu Sep 13 09:41:30 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 13 Sep 2007 15:41:30 +0200 Subject: wx.ToplevelWindow.SetIcon: Native MS Windows error dialog pops up in wxPython app, no exception raised, no stack trace In-Reply-To: <1189689558.938858.43970@g4g2000hsf.googlegroups.com> References: <1189689558.938858.43970@g4g2000hsf.googlegroups.com> Message-ID: <46E93E0A.9090706@shopzeus.com> > See main.py of the Demo, line 1129. img2py is in the following default > location: > C:\Python24\Lib\site-packages\wx-2.8-msw-unicode\wxPython\tools > > Without seeing how you create the image, it's hard to troubleshoot, > but I would guess that you have an absolute path that you're using in > your script that is different than what the exe is looking for. > I actually do have a wx.Icon instance loaded from a file. This problem is not about loading a file into a wx.Icon instance. This why I'm suprised about the message ("cannot load image file"). I already have both the icon and the top level window in memory. If I comment out the self.SetIcon(icon) line in my code then there is no error message (and no icon on the frame). The SetIcon method will call the Windows API at the end, and it has nothing to do with files. It accepts a window handle and a pointer to an icon resource. I cannot think about anything that would need to read from a file while setting the icon of the frame. Moreover, the icon is showing on the frame, looks like there is no error, so why am I getting a message? It is not a python Exception, it pops out from nowhere. :-) I suspect it will be an internal error in wxWidgets or wxPython. But their mailing list is not working. :-( Thanks anyway. Laszlo From ldo at geek-central.gen.new_zealand Thu Sep 27 01:05:32 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 27 Sep 2007 17:05:32 +1200 Subject: database persistence with mysql, sqlite References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> <1190650748.590245.221490@n39g2000hsh.googlegroups.com> Message-ID: In message , Bryan Olson wrote: > Lawrence D'Oliveiro wrote: >> In Bryan Olson wrote: >> >>> coldpizza wrote: >>>> It turned out that the method above ('SELECT * FROM TABLE LIMIT L1, >>>> L2') works ok both with mysql and sqlite3, therefore I have decided to >>>> stick with it until I find something better. With Sqlite3 you are >>>> supposed to use LIMIT 10 OFFSET NN, but it also apparently supports >>>> the mysql syntax (LIMIT NN, 10) for compatibility reasons. > >>> A more reliable form is along the lines: >>> >>> SELECT keyfield, stuff >>> FROM table >>> WHERE keyfield > ? >>> ORDER BY keyfield >>> LIMIT 10 >>> >>> With the right index, it's efficient. >> >> But that involves keeping track of the right starting keyfield value for >> the next batch of records, which is complicated and nontrivial. > > We write the link so that the browser will send back the parameter we > need. If the largest keyfield value on the page is > "Two-Sheds" the link might read: > > Next That's assuming keyfield is a) unique, and b) a relevant ordering for displaying to the user. > Keeping a cursor with pending data across HTTP requests is > a world of hurt. "limit offset, count" avoids all that. From mccredie at gmail.com Fri Sep 21 19:48:07 2007 From: mccredie at gmail.com (Matt McCredie) Date: Fri, 21 Sep 2007 16:48:07 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190417120.723579.267560@22g2000hsm.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> <1190394011.148384.106280@q3g2000prf.googlegroups.com> <1190417120.723579.267560@22g2000hsm.googlegroups.com> Message-ID: <9e95df10709211648q281d82dk2fa496816e04ff31@mail.gmail.com> > It would be nice if Python could be made to automatically detect the > LC and string translation patterns used by the unoptimized Python code > and make them into optimized Python code on the fly at runtime. I am > more than a little amazed nobody has chosen to build a JIT (Just In- > Time compiler) or cached-compiler into Python but maybe that sort of > thing is just not needed given the fact that Python code can be easily > optimized to run 30x faster. See PyPy http://codespeak.net/pypy/ for a JIT comiler for python. Although it is in the research phase, but worth taking a look at. Matt From __peter__ at web.de Thu Sep 27 14:08:05 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Sep 2007 20:08:05 +0200 Subject: getopt with negative numbers? References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <1190915197.390247.313590@57g2000hsv.googlegroups.com> Message-ID: Casey wrote: > On Sep 27, 1:34 pm, Peter Otten <__pete... at web.de> wrote: >> optparse can handle options with a negative int value; "--" can be used >> to signal that no more options will follow: > > Thanks, Peter. getopt supports the POSIX "--" end of options indicator > as well, but that seems a little less elegant than being able to simply > set a value that tells the parser "I don't use any numeric values as > options, and I want to allow negative values as arguments". At the > parser level implemening this would be trivial and I frankly was hoping > it had been implemented and it just wasn't mentioned in the spares > Python getopt library reference. After a quick glance into the getopt and optparse modules I fear that both hardcode the "if it starts with '-' it must be an option" behaviour. Peter From ianare at gmail.com Tue Sep 4 18:16:20 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: Tue, 04 Sep 2007 15:16:20 -0700 Subject: function call In-Reply-To: <46ddc866$0$25003$426a34cc@news.free.fr> References: <1188937059.459609.61850@57g2000hsv.googlegroups.com> <46ddc12c$0$24997$426a74cc@news.free.fr> <46ddc866$0$25003$426a34cc@news.free.fr> Message-ID: <1188944180.835384.40310@r34g2000hsd.googlegroups.com> > > Every reasonable use case for this (and several unreasonable ones) > > that I've encountered (and some that I've just imagined) can be better > > addressed with a trace function (sys.set_trace) than by trying to do > > this at the point of call. > > Indeed. Thanks for the correction. > > > relevant doc here:http://docs.python.org/lib/debugger-hooks.html > Thanks for your help. I was hoping to see a quick and easy way to do this, so this was helpful for this particular situation. I did not want to set up a debugger, although I am aware it's the "correct" thing to do ... Cheers! From techwr-l-confirm+22d099e2f3d881b010eaeb38c05837f62bbf60ad at lists.techwr-l.com Mon Sep 17 19:24:38 2007 From: techwr-l-confirm+22d099e2f3d881b010eaeb38c05837f62bbf60ad at lists.techwr-l.com (techwr-l-confirm+22d099e2f3d881b010eaeb38c05837f62bbf60ad at lists.techwr-l.com) Date: Mon, 17 Sep 2007 17:24:38 -0600 Subject: Your confirmation is required to join the TECHWR-L mailing list Message-ID: Mailing list subscription confirmation notice for mailing list TECHWR-L We have received a request from python-list at python.org for subscription of your email address, "python-list at python.org", to the techwr-l at lists.techwr-l.com mailing list. To confirm that you want to be added to this mailing list, simply reply to this message, keeping the Subject: header intact. Or visit this web page: http://lists.techwr-l.com/mailman/confirm/techwr-l/22d099e2f3d881b010eaeb38c05837f62bbf60ad Or include the following line -- and only the following line -- in a message to techwr-l-request at lists.techwr-l.com: confirm 22d099e2f3d881b010eaeb38c05837f62bbf60ad Note that simply sending a `reply' to this message should work from most mail readers, since that usually leaves the Subject: line in the right form (additional "Re:" text in the Subject: is okay). If you do not wish to be subscribed to this list, please simply disregard this message. If you think you are being maliciously subscribed to the list, or have any other questions, send them to techwr-l-owner at lists.techwr-l.com. From jcd at sdf.lonestar.org Thu Sep 13 14:52:47 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Thu, 13 Sep 2007 14:52:47 -0400 Subject: plotting pixels in python In-Reply-To: <1189708663.253748.323460@y42g2000hsy.googlegroups.com> References: <1189706620.564963.29690@d55g2000hsg.googlegroups.com> <1189707751.846412.51420@r29g2000hsg.googlegroups.com> <1189708663.253748.323460@y42g2000hsy.googlegroups.com> Message-ID: <20070913185247.GA7833@sdf.lonestar.org> On Thu, Sep 13, 2007 at 06:37:43PM -0000, jo5867472 at gmail.com wrote regarding Re: plotting pixels in python: > > On Sep 13, 11:22 pm, Paul McGuire wrote: > > On Sep 13, 1:03 pm, jo5867... at gmail.com wrote: > > > > > hi to all > > > I am just a beginner of python. I want to know how pixels are plotted > > > in python. I am not intending to use PIL because I don't need to > > > manipulate images. So is there a simple module for 2D graphics and > > > plot pixels > > > > Here is a *very* simple-minded module for creating BMP files, that > > supports drawing points, lines, and simple shapes. > > > > http://www.geocities.com/ptmcg/python/index.html#bmp > > > > -- Paul > > No currently I am using a canvas from the Tkinter module > What I actually want is to show how a line is plotted pixel by pixel > using a delay loop. I want functions something like putpixel not > draw_line > The question to your answer can be found here: http://catb.org/~esr/faqs/smart-questions.html Cheers, Cliff From govisathish at gmail.com Thu Sep 13 10:19:04 2007 From: govisathish at gmail.com (python_lover) Date: Thu, 13 Sep 2007 07:19:04 -0700 Subject: Help to start python Message-ID: <1189693144.493878.130220@w3g2000hsg.googlegroups.com> Hi All, I'm new to python. I installed python 2.5 and IDLE 1.2.1 . I'm able to run shell commands. But I don't know how to execute a python program using this. When I'm opeing a py program a seperate IDLE window opeing with program text. But I don't know to to execute the prg. Please help me on this . thank you regards Sat From perl4hire at softouch.on.ca Mon Sep 17 23:34:31 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Mon, 17 Sep 2007 23:34:31 -0400 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: Bryan Olson wrote: > Amer Neely wrote: >> I don't have shell access but I can run 'which python' from a Perl >> script, and I will try the different shebang line you suggested. > > And after trying it, Amer Neely reported: > >> I tried `which python` and `whereis python` and got 0 back as a >> result. So it seems Python is not installed at all. > > Probably right, but just to be thorough... Since you do not > have shell access, I'm guessing you are running these within > a Perl cgi script, and getting the results via a browser. Is > that right? Yes. > > Can you backtick other commands? What do you get if you run > `which perl` the same way? How about `whoami`, `whereis sh`, > and `which nosuchthingas5748614`? Can you list /, /bin and > /usr/bin? I just looked at my code and tried something else: @SysCmd="which python"; system(@SysCmd); and it came back /usr/local/bin/python > > How did you learn that this system could run your Perl > scripts? Can that source give us anything to go on here? > If Python is not installed, do you have some avenue for > requesting it? > > We're down to long shots. Still, hosts that support Perl > but will not support Python are getting to be the rare. > > I've asked my host to put in a request for it. So it seems python IS installed, but not where I thought it was. I just tried my script with the new path, but still got a 500 server error. Can I trap errors to a file locally? -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From jonas at mit.edu Tue Sep 4 10:06:59 2007 From: jonas at mit.edu (jonas at mit.edu) Date: Tue, 04 Sep 2007 07:06:59 -0700 Subject: GC performance with lists Message-ID: <1188914819.723858.25000@d55g2000hsg.googlegroups.com> While working on some python wrapping, I've run into some problems where the GC seems to take an unreasonable amount of time to run. The code below is a demonstration: import gc #gc.disable() data = [] for i in xrange(100000): shortdata = [] for j in range(57): mytuple = (j, i+1, i+2, i+3, i+4, i+5, i+6) shortdata.append(mytuple) data.extend(shortdata) print len(data) with gc disabled (the second line) the code runs in 15 seconds, with it enabled it runs in 2:15, or ~9x slower. I expected some gc overhead, but not an order of magnitude! Am I doing something obviously wrong in the above code? Thanks, ...Eric From neogregorian at gmail.com Fri Sep 7 10:51:43 2007 From: neogregorian at gmail.com (NeoGregorian) Date: Fri, 07 Sep 2007 07:51:43 -0700 Subject: Python wrapper, problem with subprocess read/write Message-ID: <1189176703.245411.60350@r29g2000hsg.googlegroups.com> Hello, I am writing a wrapper to a basic Input/Output programs (where you type a one line command at a time and then get 0 or more lines of output before you can input the next command). I'm sorry if this problem description is a bit long, but I wanted to make the problem clear. Example run of the original program: C:\home\>start Starting up program [Welcome to program v.X.Y.Z] blahblahblah and some more lines >input command program response... more program response... etc. >another command ... This is what the wrapper is expected to do... 1: Start up the program. 2: Forward the startup printouts by the program until the line where it first asks for a command. 3: When waiting for input, input a command from a sequential list of strings (or other source of strings). 4: Forward the programs printouts until all lines are read and the program prompts for new command. 5: Repeat 3-4 until list is depleted or program is terminated and then close the program. Now, to the problem: In step 2/4, how to read all lines except the one which is unfinished (in the example, the lines beginning with >) and waiting for input? My attempts use something like this: proc = Popen(['programname'], stdout = PIPE, stdin = PIPE ) for string_element in string_source : proc.stdin.write(string_element) lines = proc.stdout.readlines() method_that_processes_output(lines) The problem with this is that stdout.readlines() doesn't return since it reads until EOF... I tried instead to use: lines = [] line = proc.stdout.readline() while line : lines.append(line) line = proc.stdout.readline() This prints out everything except the ">" line, which is good. But then freezes while waiting for input, which is bad. Any suggestions on how to solve this in a good way? From arnodel at googlemail.com Mon Sep 10 02:13:55 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 09 Sep 2007 23:13:55 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> <46E4466C.2030303@sdf.lonestar.org> Message-ID: <1189404835.984772.287220@r34g2000hsd.googlegroups.com> On Sep 9, 10:06 pm, stef mientki wrote: > J. Cliff Dyer wrote: > > Dotan Cohen wrote: > > >> FIrst of all, how is the % symbol (as in 70%6=4) called in English? > > >> Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or > >> the other in error? Is this a known gotcha? I tried to google the > >> subject however one cannot google the symbol %. Thanks in advance. > > >> Dotan Cohen > > > The % operator is called "modulo" in English. I don't think the > > difference in implementation is an error. It's just a difference of > > calculation method. > > > Python will always yield a number x = m%n such that 0 <= x < n, but > > Turbo C will always yield a number such that if x = m%n -x = -m%n. That > > is, since 111 % 10 = 1, -111 % 10 = -1. The two values will always > > differ by n (as used above). > > > I'm sure there are mathematicians on the list who can give you a more > > technical, precise explanation of the reasons for the different results. > > It's a long time ago, but if I remember well, > "modulo" was introduced as an operator in Galois fields theory, > and Galois fields only exists of the whole numbers 0 .. N-1. You're probably thinking of Galois *groups*. Some finite Galois groups are cyclic, so they are of the form Z/nZ that can be described as {0, .. , n-1}. But Galois groups can have many other forms. -- Arnaud From harry.g.george at boeing.com Tue Sep 11 02:25:17 2007 From: harry.g.george at boeing.com (Harry George) Date: Tue, 11 Sep 2007 06:25:17 GMT Subject: Py2.5.1 on Ubuntu AMD X2, unicode problems Message-ID: I'm building 2.5.1 from source, using the ubuntu(7.0.4)-provided gcc 4.1.2. Based on google searches and nints found, here is the process: ------------------------------------------------------------ #---edit configure; test of wchar_t--- #include #include #------------------------------------- cd Lib/test rm test_multibyte* cd ../.. #---edit Include/unicodeobject.h--- /* FIXME: MvL's new implementation assumes that Py_UNICODE_SIZE is properly set, but the default rules below doesn't set it. I'll sort this out some other day -- fredrik at pythonware.com */ #define Py_UNICODE_SIZE 4 #ifndef Py_UNICODE_SIZE #---------------------------- LDFLAGS='-L/usr/lib -lncursesw -L/usr/local/ssl/lib -lssl -lcrypto ' \ ./configure --prefix=/usr/local \ --with-gcc=/usr/bin/gcc \ --enable-shared \ --enable-unicode=usc4 \ #---edit Modules/Setup--- (all the std ones....) SSL=/usr/local/ssl _ssl _ssl.c \ -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ -L$(SSL)/lib -lssl -lcrypto #---end edits--- gmake altinstall ------------------------------------------------------------ I'm getting a failure during final libpython binding, on undefined PyUnicodeUCS4_AsWideChar. All the other PyUnicodeUCS4... functions are being found. It specifically says it is checking on the libpython in /usr/local/lib (not somewhere in the source code build dirtree), so that is a possible oddity. Checking with nm on the lib shows "AsWideChar" is in fact undefined. 1. If I onfigure with unicode=ucs2, does all this go away and I get a working system (efficient or not) on my 64-bit machine? 2. Can you point to a configure (and maybe patch) process which leads to a clean "make altinstall". -- Harry George PLM Engineering Architecture From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 3 07:26:54 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 03 Sep 2007 13:26:54 +0200 Subject: TypeError: 'module object is not callable' In-Reply-To: <1188816626.021956.281040@22g2000hsm.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> Message-ID: <46dbef7d$0$29304$426a74cc@news.free.fr> christophertidy at hotmail.com a ?crit : > Thank you for your help that seems to have done the trick. > You are correct Diez B. Roggisch that I come from a java background! > > I have a new tiny problem I can't understand either. > Withing Step.py I have the following method > > def isCompleted(self): > "Check whether data step has been processed" > return self.isCompleted Java background, indeed !-) In Python, everything (including functions, methods, modules, classes etc) is an object, and methods are just attributes like every others - ie, there's no separate namespaces for methods. So when you set an instance attribute 'isCompleted', it shadows the class attribute by the same name. The obvious solution is to give attributes different names. The perhaps less obvious but much more pythonic solution is to get get rid of the getter if all it does is returning the attribute. I know this sounds strange when coming from Java, but there's no problem doing so - Python has support for computed attributes (aka properties), so you can always replace a plain attribute by a computed one latter if you need to do so, this won't impact the client code. HTH From gagsl-py2 at yahoo.com.ar Fri Sep 14 00:06:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Sep 2007 01:06:11 -0300 Subject: Setting stdout encoding References: <1189416350.069995.220250@w3g2000hsg.googlegroups.com> Message-ID: En Thu, 13 Sep 2007 08:08:39 -0300, Fabio Zadrozny escribi?: >> >> But I don't think it's a good idea. Changing the default encoding will >> change it for *all* scripts, *all* users, *all* objects. And AFAIK you >> have trouble ONLY with sys.std* - one should fix those objects, not mess >> with a global configuration. >> > > Makes sense... Do you think that creating a new object, setting it as > sys.stdout and overriding its write() method to check for a unicode > string > to do original_stdout.write(unicode_str.encode(my_encoding)) would do it? Yes. See the other message from Ryan Ginstrom. > (the ctypes version is not really an option as it is not available on > lots > of installs -- although I can try to use it if it's available, but it > can't > be the only solution). I see... Wrapping stdout with your own object seems reasonable then. -- Gabriel Genellina From inigoserna at gmail.com Mon Sep 3 18:02:36 2007 From: inigoserna at gmail.com (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: Tue, 04 Sep 2007 00:02:36 +0200 Subject: ANN: lfm 2.0 Message-ID: <1188856956.7698.11.camel@inigo> Hi out there, After a few years working silently I'm very pleased to announce here the so much awaited new version of 'lfm'. Last File Manager is a simple but powerful file manager for the UNIX console. It's written in Python, using curses module. Licensed under GNU Public License version 3. Some of the features you could find in lfm: - console-based file manager for UNIX platforms - 1-pane or 2-pane view - bookmarks - vfs for compressed files - dialogs with entry completion - fast access to a shell - direct integration of find/grep, df and other tools - tabs per pane - color files by extension [Andrey Skvortsov] - fast file viewer with text and binary modes - ...and many others Download it from: http://www.terra.es/personal7/inigoserna/lfm or if it doesn't show last version (crap of ISP reverse proxy), try this low-bandwidth home server: http://inigo.katxi.org/devel/lfm Of course, all comments, suggestions etc. are welcome. Changes since previous version: Version 2.0 ("Nine 1/2 weeks... ok, ok, and 3 years") - 2007/09/03: + tabs implemented + color files by extension [Andrey Skvortsov] + new IPC code and API; more flexible, powerful and stable + new un/compress vfs API, added support for .zip and .rar files + make sort mode per tab, not globally + support locale [Andrey Skvortsov] + speed up loading directory contents + speed cursor movement, don't waste much CPU + use logging module in lfm and pyview for debugging + overwrite_all_none: yes, all, no => new options: "none", "skip all"" + rewrite/refactor most of code to make lfm more robust and clean + preferences: - change file name preferences.py => config.py - use ConfigParser + use tempfile secure versions mkdtemp() and mkstemp() + added man pages [Sebastien Bacher] + use reST for documentation + check for python version 2.3 or higher in lfm and pyview + updated to GPL v3 license + and fixed lot of bugs, some of them: - general: . delete garbage if user stops action . run 'do_special_view_file' as dettached from lfm window . path expand in bookmarks ("~/") [Andrey Skvortsov] . an ugly traceback crash appears when user starts "lfm path" and has no permissions to enter. Show error message and default to current directory . lfm crashes when filename is not encoded with same codec than g_encoding utils.{decode|encode}. Needs curses module linked against ncursesw to work properly . sort_mix_cases = 1 performance degrades on larger dirs. Reported by Andrey Skvortsov . escape filenames with chars $ ". Reported by Andrey Skvortsov - user interface: . maximize/minimize window don't crash lfm anymore . dialogs appear at bad position after terminal is resized . handle window resize in Tree mode . refresh display after canceling completion dialog . "the size of the right pane does not fill the last column in terminal if their number is odd" [Andrey Skvortsov] . fix crash when "df" shows entries in two different lines (device name is too large, f.e. in linux lvm2 volumes) . if you try to enter a directory with insufficient permissions, after the error message is closed the cursorline refreshes to the first line - compress: . added -i flag (--ignore-zeros) flag to tar [Andrey Skvortsov] . standard tar needs - for flags - vfs: . vfs.py: regenerate_file, if user stops process, tempfile can't be deleted - find/grep: . escape special chars (- \ ( ) [ ]) in patterns . don't crash when find/grep returns no results . bug when matches occur in binary files - pyview: . goto line 0 in pyview showed a blank screen . crash in file info if filename is too long Version 1.0 was never released in public Best regards, I?igo Serna From bborcic at gmail.com Wed Sep 5 07:57:42 2007 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 05 Sep 2007 13:57:42 +0200 Subject: So what exactly is a complex number? In-Reply-To: References: Message-ID: <46de99ee$1_5@news.bluewin.ch> Roy Smith wrote: > Boris Borcic wrote: >> Complex numbers are like a subclass of real numbers > > I wouldn't use the term "subclass". Really you should name yourself as the author when you butcher someone else's prose to such a degree. Suppose I had written "Complex numbers are like an afghan beauty that has little chance to seduce you unless you first get to see her eyes despite the burkha she is usually wearing". Would you find it reasonable to cut this down to "Complex numbers are like an afghan beauty" and then criticize the result as if the word "like" hadn't survived this treatment ? > It certainly doesn't apply in the same > sense it applies in OOPLs. For example, you can't say, "All complex > numbers are real numbers". In fact, just the opposite. > But, it's equally wrong to say, "real numbers are a subclass of complex > numbers", at least not if you believe in LSP > (http://en.wikipedia.org/wiki/Liskov_substitution_principle). Well, some edulcorated-analogical version of that principle was precisely what I had in mind when I wrote what I wrote - not what you cite and much less "just the opposite" of the latter, that you here adress. What makes complex numbers magical to use is precisely that you can port to them without change (most of) the algebraic procedures that you first learn on the real number field. And manipulate them technically while neglecting that they are not really real numbers, except when convenient because (a) things will work uniformly using complex numbers where real numbers would present exceptions and (b) they allow more powerful results. And that's what LSP is about, is it not ? > For example, > it is true that you can take the square root of all complex numbers. It is > not, however, true that you can take square root of all real numbers. (a) note that with the subclass relation put in the order I had chosen, this would not contradict LSP (b) and nevertheless : >>> x = -1.0 >>> type(x) >>> import cmath >>> cmath.sqrt(x) 1j >>> > > Don't confuse "subset" with "subclass". Don't confuse myself with yourself, thanks :) Or are you going to say that you would have launched into the same diatribe if I had proposed a subclassing relation that wasn't counter the grain viz the purported subset relation ? > The set of real numbers *is* a > subset of the set of complex numbers. It *is* unfortunate that learning mathematics using sets allows to neglect the fundamental difference between the identity of physical objects and the identity of mathematical objects. The latter we only ever reach "up to isomorphism". There is a natural embedding of real numbers into complex numbers, but there is also a natural embedding of real numbers into surreal numbers. The two embeddings aren't compatible. So which should be promoted to "*being*", and why ? > It is *not* true that either reals > or complex numbers are a subclass of the other. What I had written : "Complex numbers are like a subclass of real numbers that elegantly extends the usual arithmetic operations to provide access to trigonometric functions and related goodies. This then allows you to think of trigonometric problems as simple arithmetic problems." Boris Borcic From arkanes at gmail.com Tue Sep 4 16:56:29 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 4 Sep 2007 15:56:29 -0500 Subject: function call In-Reply-To: <46ddc12c$0$24997$426a74cc@news.free.fr> References: <1188937059.459609.61850@57g2000hsv.googlegroups.com> <46ddc12c$0$24997$426a74cc@news.free.fr> Message-ID: <4866bea60709041356x21d7c204w87a44e7496b643b1@mail.gmail.com> On 9/3/07, Bruno Desthuilliers wrote: > ianar? a ?crit : > > Hey all, > > > > Is there a way of printing out how a function was called? In other > > words if I do the following: > > > > def someFunction(self): > > self.someOtherFunction(var1, var2) > > > > > > I would get something like "someOtherFunction: called by: > > someFunction, args are: var1, var2" > > > > Thanks in advance > > > You may be able to solve this using a decorator (to avoid polluting your > code with this) and the infamous sys._getframe() hack. > -- Every reasonable use case for this (and several unreasonable ones) that I've encountered (and some that I've just imagined) can be better addressed with a trace function (sys.set_trace) than by trying to do this at the point of call. From kenneth.m.mcdonald at sbcglobal.net Sun Sep 23 01:26:22 2007 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Sun, 23 Sep 2007 00:26:22 -0500 Subject: Python plugins for netbeans 6 IDE? Message-ID: <46F5F8FE.2020208@sbcglobal.net> Do any such exist? And do you find them worthwhile? I couldn't see any browsing the netbeans pages, but that doesn't mean they're not out there... Thanks, Ken From tjreedy at udel.edu Tue Sep 11 17:42:58 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Sep 2007 17:42:58 -0400 Subject: Python.org mirror References: Message-ID: |Could you inform me about the options to become an officiel python.org mirror? The main python.org site maintainers do not necessarily read this group/list. If no response here, try webmaster at python.org From grante at visi.com Thu Sep 20 10:40:04 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Sep 2007 14:40:04 -0000 Subject: Python and RTF References: <1190271676.160077.99270@w3g2000hsg.googlegroups.com> Message-ID: <13f51i4adkseae5@corp.supernews.com> On 2007-09-20, Rufman wrote: > Does anyone have a good rtf library for python, pyRTF is the only one I found. > have exprience with pyRTF Yes. > or a link to a good tutorial? Just the examples that come with pyRTF. FWIW, I've added support for EMF graphics and enhanced the scaling options for graphics: http://groups.google.com/group/comp.lang.python.announce/browse_thread/thread/c56ccb0f65eae5da/e9997d47b4303547 -- Grant Edwards grante Yow! Uh-oh!! I'm having at TOO MUCH FUN!! visi.com From trekker182 at gmail.com Sat Sep 15 21:29:37 2007 From: trekker182 at gmail.com (Shawn Minisall) Date: Sat, 15 Sep 2007 21:29:37 -0400 Subject: thanks everyone for your replies! Message-ID: <46EC8701.4040606@gmail.com> :) From vinay_sajip at yahoo.co.uk Wed Sep 26 02:07:03 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 25 Sep 2007 23:07:03 -0700 Subject: Overriding Logging Config FileHandler Filename In-Reply-To: References: Message-ID: <1190786823.934389.139410@50g2000hsm.googlegroups.com> On Sep 25, 9:15 pm, "Kenneth Love" wrote: > I have a Pythonloggingconfig file that contains a RotatingFileHandler > handler. In the args key, I have hard-coded the log filename. Everything > works great. > > However, I find that I now need to override this filename at application > runtime. Is there a good way to do this? > Are you using the original file name mentioned in the config file at all? Why and under what conditions do you need to switch? You could easily do this programmatically - have two handlers and when you need to, remove one from the logger and add the other. I see you are using a rotating handler, which itself does rollover to new log files every so often. Regards, Vinay Sajip From paul at boddie.org.uk Mon Sep 3 10:23:02 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 03 Sep 2007 07:23:02 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <1188826786.674057.158020@d55g2000hsg.googlegroups.com> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> <13dmctogeh19410@corp.supernews.com> <7x4picthpb.fsf@ruckus.brouhaha.com> <1188826786.674057.158020@d55g2000hsg.googlegroups.com> Message-ID: <1188829382.536724.45270@d55g2000hsg.googlegroups.com> On 3 Sep, 15:39, jwrweather... at gmail.com wrote: > Thanks for all the answers to my question. I think what I need to take > away from this is that xrange is an object Indeed, but using xrange can be faster than converting your "for" loops to "while" loops plus a counter; I converted your code to use the latter arrangement and it was noticeably slower. Perhaps the repeated invocation of each xrange object's next method is less expensive than repeatedly obtaining new incremented int objects and testing them against other int objects. > - I thought it was just some loop construct, and that maths is slow in > python - so avoid pathological looping. You'd be wise to avoid doing unnecessary work deep within nested loops in any programming language. Sadly, it's not possible for the compiler to work out that some calculations can be lifted out of the innermost loops in Python, since the various guarantees that make such operations possible in other languages are not offered by Python. > I remember the first time I tried Objective-C on OS X I used the > NSNumber class for arithmetic - the results that time were pretty > awful too! Obviously, it'd be a fairer test if you used comparable numeric types in both implementations, but a more capable numeric type would be overkill for the C implementation of this program, and a less capable numeric type doesn't exist for Python unless you're willing to use a dialect such as Pyrex (as others have shown). Paul From joshua at eeinternet.com Fri Sep 28 17:58:39 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Fri, 28 Sep 2007 13:58:39 -0800 Subject: GUI for viewing/editing python data structures? References: <1190953236.340024.131370@o80g2000hse.googlegroups.com> Message-ID: On Thursday 27 September 2007 20:20, Paddy wrote: > On Sep 26, 11:23 pm, "Joshua J. Kugler" wrote: >> A while back, I seem to remember coming across a small program that could >> view and edit python data structures via a nice expanding tree view. I'm >> now in need of something like that (to verify data is imported correctly >> into a shelve file) and having a GUI would be much simpler than trying to >> wade through the output of str(d) or repr(d). >> >> I've tried googling with the obvious keywords (gui (view OR edit) python >> data structures) but t didn't get me anywhere. >> > > The magic googling phrase is: > Python bean-editor > > Which gave http://home.gna.org/oomadness/en/editobj/index.html > > I've never used it. Could you tell me how you get on? > > - Paddy. Thank you!! This is EXACTLY what I was looking for. Should serve me well. For editing shelves, you just have to pull the data out via the key, and then edit that, since a shelf is not a true dict, just acts like one. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From tjreedy at udel.edu Thu Sep 20 14:18:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Sep 2007 14:18:03 -0400 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com><1190164166.378500.155990@o80g2000hse.googlegroups.com><1190241711.344058.238380@57g2000hsv.googlegroups.com><1190242799.954176.279440@22g2000hsm.googlegroups.com><7xps0ew0a8.fsf@ruckus.brouhaha.com><13f3roj6gdfq6b7@corp.supernews.com> <7x1wctwg6x.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7x1wctwg6x.fsf at ruckus.brouhaha.com... | funding into PyPy development, since I think I saw something about the | EU funding being interrupted. As far as I know, the project was completed and promised funds paid. But I don't know of any major follow-on funding, which I am sure they could use. From berteun at gmail.com Wed Sep 26 08:06:26 2007 From: berteun at gmail.com (Berteun Damman) Date: Wed, 26 Sep 2007 12:06:26 -0000 Subject: Tracking memory usage and object life time. Message-ID: <1190808386.571152.103710@22g2000hsm.googlegroups.com> Hello, I have programmed some python script that loads a graph (the mathemical one with vertices and edges) into memory, does some transformations on it, and then tries to find shortest paths in this graph, typically several tens of thousands. This works fine. Then I made a test for this, so I could time it, run it several times and take a look at the best time, et cetera. But it so happens that the first time the test is run, is always the fastest. If I track memory usage of Python in top, I see it starts out with around 80 MB and slowly grows to 500MB. This might cause the slowdown (which is about a factor 5 for large graphs). When I run a test, I disable the garbage collection during the test run (as is adviced), but just before starting a test I instruct the garbage collector to collect. Running the test without disabling the garbage collect doesn't show any difference though. Where possible I explicitly 'del' some of the larger data structures that have been created after I don't need them anymore. I furthermore don't really see why there would be references to these larger objects left. (I can be mistaken of course). I understand this might be a bit of a vague problem, but does someone have any idea why the memory usage keeps growing? And whether there is some tool that assists me in keeping track of the objects currently alive and the amount of memory they occupy? The best I now can do is run the whole script several times (from a shell script) -- but this also forces Python to reparse the graph input again, and do some other stuff it only has to do once. And it's also more difficult to examine values and results this way. Berteun From nytrokiss at gmail.com Wed Sep 19 14:51:33 2007 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 19 Sep 2007 11:51:33 -0700 Subject: Removing objects in a list via a wild card Message-ID: <8a6b8e350709191151n31b72bbvc3090031232d5fc8@mail.gmail.com> Hi List I have a list of files from my current directory: import os files = os.listdir(os.getcwd()) Now this list also includes some files that i don't want like my python files... How would i remove them Thanks James -- http://www.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.reiners at gmail.com Tue Sep 11 18:55:44 2007 From: paul.reiners at gmail.com (Paul Reiners) Date: Tue, 11 Sep 2007 22:55:44 -0000 Subject: Twisted Life version 1.0.0 (stable) released Message-ID: <1189551344.358346.14050@r29g2000hsg.googlegroups.com> Version 1.0.0 of Twisted Life has just been released. Twisted Life is a video game that uses a variant of Conway's Life cellular automaton as its universe. In Twisted Life, you try to navigate to the center of the Twisted Life universe without colliding into any of the malevolent, evil Life forms circling the center. I wrote this application as an entry to the PyWeek competition: http://www.pyweek.org/ You can download Twisted Life from SourceForge.net: http://sourceforge.net/projects/twisted-life/ Twisted Life is released under the GNU General Public License (GPL). From bj_666 at gmx.net Thu Sep 20 03:38:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Sep 2007 07:38:13 GMT Subject: os.popen and lengthy operations References: Message-ID: <5lemb5F7r3c0U2@mid.uni-berlin.de> On Thu, 20 Sep 2007 10:31:43 +0400, Dmitry Teslenko wrote: > I'm using os.popen to perform lengthy operation such as building some > project from source. > It looks like this: > def execute_and_save_output( command, out_file, err_file): > > import os > > def execute_and_save_output( command, out_file, err_file): > (i,o,e) = os.popen3( command ) > try: > for line in o: > out_file.write( line ) > > for line in e: > err_file.write( line ) > finally: > i.close() > o.close() > e.close() > > ... > execute_and_save_output( '', out_file, err_file) > > Problem is that script hangs on operations that take long to execute > and have lots of output such as building scripts. Your code reads from the process' stdout until there is nothin to read anymore and then from stderr. The process might output something to both. The output is buffered. And when the stderr buffer is full the process blocks until your application reads something from `e`. That's where the whole thing hangs. You wait for something on `o` and the process waits for you to read from `e` ? deadlock. You have to use threads to read both `o` and `e` or the `select` module to look which file has something to read. Ciao, Marc 'BlackJack' Rintsch From garyjefferson123 at yahoo.com Thu Sep 20 10:06:33 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: Thu, 20 Sep 2007 07:06:33 -0700 Subject: distutils, extensions, and missing headers In-Reply-To: References: <1190268535.052437.226240@v23g2000prn.googlegroups.com> Message-ID: <1190297193.864613.13890@i13g2000prf.googlegroups.com> Robert, thanks for the help! On Sep 20, 1:22 am, Robert Kern wrote: > > Use the "headers" keyword to setup() to list the header files you want installed. I've tried "headers=['header1.h', 'header2.h']" in setup() as well as in Extension(), and neither seem to get the files into the bdist or bdist_rpm tarball. Am I doing it wrong? I can't seem to find any examples that use this via google. > For other files, it depends on where you need them to go. If you want the data > files to be inside the package, you should use the "package_data" keyword. It > was introduced in Python 2.4, so if you need to support pre-2.4 Pythons, there > are recipes floating around to do so more nicely. > > http://docs.python.org/dist/node12.html > > For other things (and hopefully, you can live with package data), use "data_files": > > http://docs.python.org/dist/node13.html I also tried using data_files to get the headers included, but can't seem to get that to work either. No errors are reported for either method. Thanks, Gary From greg at cosc.canterbury.ac.nz Mon Sep 24 22:16:35 2007 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 25 Sep 2007 14:16:35 +1200 Subject: ANN: Albow 1.1 and Humerus 1.0 Message-ID: I have released an updated version of my Albow gui library for PyGame, incorporating improvements made to it for my PyWeek 5 entry, and also Humerus, a skeleton game framework built on Albow. http://www.cosc.canterbury.ac.nz/greg.ewing/python/Albow/ What is it? Albow is a rather basic, no-frills widget set for creating a GUI using PyGame. It has been developed over the course of my last three PyWeek game competition entries. I am documenting and releasing it as a separate package so that others may benefit from it, and so that it will be permissible for use in future PyGame entries. -- Gregory Ewing greg.ewing at canterbury.ac.nz From gtcopeland at gmail.com Sat Sep 1 11:06:41 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: Sat, 01 Sep 2007 08:06:41 -0700 Subject: Pygame + PyInstaller? Message-ID: <1188659201.217951.110830@r34g2000hsd.googlegroups.com> Anyone had any luck on using PyInstaller to package up Pygame? I posted to the PyInstaller group some time ago and have yet to receive a reply. Anyone have any tips to offer here? A like-solution which runs on Linux would also be welcome. When PyInstaller works, it's pretty nice. When it doesn't, it is a real pain to figure out what the heck it doesn't like. So if anyone has a less painful alternative, which runs on Linux, please let me know. Greg From aahz at pythoncraft.com Thu Sep 13 22:41:31 2007 From: aahz at pythoncraft.com (Aahz) Date: 13 Sep 2007 19:41:31 -0700 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <1i4bjb8.63ihk49vs6c8N%aleax@mac.com> <1i4bm7a.1s51u591kreqe4N%aleax@mac.com> Message-ID: In article <1i4bm7a.1s51u591kreqe4N%aleax at mac.com>, Alex Martelli wrote: >Chris Mellon wrote: >> >> and I'll punch a kitten before I accept having to read >> Python code guessing if something is a global, a local, or part of >> self like I do in C++. > >Exactly: the technical objections that are being raised are bogus, and >the REAL objections from the Python community boil down to: we like it >better the way it is now. Bringing technical objections that are easily >debunked doesn't _strengthen_ our real case: in fact, it _weakens_ it. >So, I'd rather see discussants focus on how things SHOULD be, rather >than argue they must stay that way because of technical difficulties >that do not really apply. > >The real advantage of making 'self' explicit is that it IS explicit, and >we like it that way, just as much as its critics detest it. Just like, >say, significant indentation, it's a deep part of Python's culture, >tradition, preferences, and mindset, and neither is going to go away (I >suspect, in fact, that, even if Guido somehow suddenly changed his mind, >these are issues on which even he couldn't impose a change at this point >without causing a fork in the community). Making up weak technical >objections (ones that ignore the possibilities of __get__ or focus on >something so "absolutely central" to everyday programming practice as >inspect.getargspec [!!!], for example;-) is just not the right way to >communicate this state of affairs. While you have a point, I do think that there is no solution that allows the following code to work with no marker distinguishing the local bar from the instance's bar; the only question is how you want to mark up your code: class C: def foo(self, bar): print bar, self.bar x = C() x.bar = 'abc' x.foo() >From that standpoint, there is a technical objection involved. Of course, the solution can be any of a number of different marker systems (or even choosing to have no marker and not permit a method to access both object attributes and locals of the same name), and Python has chosen to force the use of a marker for all object attributes, while also choosing to have disjoint namespaces WRT globals and locals for any one name. -- 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 http://www.lysator.liu.se/c/ten-commandments.html From steve at holdenweb.com Fri Sep 28 08:25:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 08:25:17 -0400 Subject: recipient validation with smtplib In-Reply-To: <46FCEA9E.3030700@chamonix.reportlab.co.uk> References: <46FCE387.9070601@chamonix.reportlab.co.uk> <9afea2ac0709280433n361ce4fx2a26a05de2b1b1ae@mail.gmail.com> <46FCEA9E.3030700@chamonix.reportlab.co.uk> Message-ID: Robin Becker wrote: > Tim Williams wrote: >> On 28/09/2007, Robin Becker wrote: >>> Is there a way to use smtplib to get recipient validation. I can use smtplib >>> quite happily to send emails using the locahost's sendmail, but sendmail is just >>> fire and forget, so some bad addresses eg idiot at www.dingo.zzz don't cause any >>> error in the sending application. I know some smtp setups do enforce recipient >>> validation, but it doesn't seem terribly easy to do this with sendmail. I >>> wondered if there were some way to do this in python? >> There is no way of validating *every* email address you send to using >> SMTP alone. Some servers accept every address and bounce later - as >> you have found out. So for the purpose of the SMTP client, or relaying >> server, the address is valid at sending time to those servers. >> >> Checking DNS for MX records is a possibility for removing some bad >> addresses, but it's not fool proof as the RFCs don't require MX >> records to exist for a domain to be able to receive email. If no MX >> records are present, one (and only one!) IP address returned from the >> domain's A record(s) should be tried. >> >> HTH :) > Thanks, it's at least ammunition for me to say it cannot easily be done. I found > this milter > > http://www.jmaimon.com/sendmail/callahead-milter/ > > but I think this will cause every send to be checked which is probably not what > we need. I have a client who gets many spurious web sign-ups (they are a telephone service). One of the signs of fraud is a bogus email address, so it became very important to detect these. The only way we could satisfactorily do so was to process the mailbox that received the bounces and detect a GUID in the bounce message to identify the potentially bogus accounts. This apparently works well enough to stop most scammers from making their first 'phone call. In general there is no way to tell when sending that an address is or is not valid. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From http Fri Sep 7 11:42:45 2007 From: http (Paul Rubin) Date: 07 Sep 2007 08:42:45 -0700 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> Message-ID: <7x3axq7a8a.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > def unique_id(): > n = 1234567890 > while True: > yield n > n += 1 unique_id = itertools.count(1234567890) > which is easy enough, but I thought I'd check if there was an existing > solution in the standard library that I missed. Also, for other > applications, I might want them to be rather less predictable. def unique_id(): return os.urandom(10).encode('hex') From wizzardx at gmail.com Sat Sep 8 14:22:47 2007 From: wizzardx at gmail.com (David) Date: Sat, 8 Sep 2007 20:22:47 +0200 Subject: How to insert in a string @ a index In-Reply-To: <18c1e6480709081121h21eac6d2s9d1e06a91ee8d6af@mail.gmail.com> References: <1189274564.462664.131240@22g2000hsm.googlegroups.com> <18c1e6480709081121h21eac6d2s9d1e06a91ee8d6af@mail.gmail.com> Message-ID: <18c1e6480709081122p7754d9edwbc9f5ca069e8319b@mail.gmail.com> On 9/8/07, David wrote: > > The python doesn't supports t1[keyword_index]="XYZhello" (string > > object assignment is not supported). How do I get to this problem? Any > > sugguestions? > > Build a new string var using slicing. eg: > > t1 = t1[:keyword_index] + "XYZhello" + [keyword_index] > Typo. Missed a colon. Should be: t1 = t1[:keyword_index] + "XYZhello" + [keyword_index:] From DouhetSukd at gmail.com Fri Sep 14 03:12:30 2007 From: DouhetSukd at gmail.com (DouhetSukd at gmail.com) Date: Fri, 14 Sep 2007 00:12:30 -0700 Subject: funny little 190 lines command line math tutor I wrote for my 7-year old. Message-ID: <1189753950.569402.186370@g4g2000hsf.googlegroups.com> Sadly lacking in multi-media bells and whistles. But my daughter actually likes playing with it. Coded on windows, but no reason it shouldn't work on Linux/OS X. (hopefully the indentation won't be too mangled by usenet. apologies in advance if that is the case) Enjoy. Sample session: D:\user\python>mathtester.py -1 3 -o /+ -r 2 Hello, I am your friendly computer. I have a math quiz for you Problem #1 1 + 2 = 3 Answered: 3. Correct. Problem #2 3 + 3 = 6 Answered: 6. Correct. Congratulations, you got 2 right out of 2 code: ************************************ """ mathtester.py -h for more help . HELPS YOUR KIDS TO LEARN MATH WITH INTERACTIVE PROMPTS. EXAMPLE: Hello, I am windoze, your friendly computer. I have a math quiz for you Problem #0 4 - 3 = 1 Answered: 1. Correct. Problem #1 8 - 6 = 14 Answered:14. Wrong. Correct answer: 2 This will pick two numbers, each between 0 and 10. It will either add or substract them. Any questions with solutions less than zero or greater than 20 will be rejected and re-created. You get this by running it with all defaults. i.e. c:\>python mathtester.py to get something like doing the multiplication of 1 to 3 times 10, run c:\>python mathtester -o * -1 3 -2 10 -H 30 only multiplication '*' will be used, number #1 will be between 0 and 3. number #2 will be between 0 and 10. answers greater than 30 will be rejected. """ import os, sys, optparse, random _module_doc = __doc__ class Writer: """write to file and output to console""" def __init__(self,fout): self.fout = fout def __call__(self,s,echoconsole=True): self.fout.write("\n" + s.replace("\t"," ")) if echoconsole: print s class Worker: fout = None filename = "test.txt" trivial_tolerance_percentage = 40 accepted_operators = "+-*" def formatoptions(self): """most of the work is already done by optparser""" #filter on acceptable operators. exit if none found. self.operators = [i for i in self.options.operators if i in self.accepted_operators] if not self.operators: print ERROR_MSG_OPERATORS % {"supported" : self.accepted_operators} sys.exit() #both number range limits are equal. if not self.options.numberRange2: self.options.numberRange2 = self.options.numberRange def __init__(self): self.fout = open(self.filename,"w") Worker.writer = Writer(self.fout) self.formatoptions() self.asked = self.correct = 0 self.set_asked = set() def process(self): """main loop - prints greetings, loops on questions, print result summary and exits""" try: self.writer(GREETING) [self.doTest(cntr) for cntr in range(0,self.options.repetitions)] except KeyboardInterrupt: pass self.writer(FAREWELL % vars(self)) return True def doTest(self,number): """the workhorse function. randomly picks a question + vets the solution then asks the question and checks the answer""" self.writer("\n Problem #%s" % (number+1)) while True: #pick random numbers and operator number1 = random.randint(0,self.options.numberRange) number2 = random.randint(0,self.options.numberRange2) operator = self.operators[random.randint(0,len(self.operators)-1)] if number1 < 2 or number2 < 2 and random.randint(1,100)>self.trivial_tolerance_percentage: #potentially reject trivial problems consisting of zeros and ones. continue #flip a coin and put number #1 either right or left - #remember that the number ranges can be unequal so there is a difference if random.randint(1,2) % 2: problem = "%2s %s %2s" % (number1,operator,number2) else: problem = "%2s %s %2s" % (number2,operator,number1) #use eval to get the expected solution solution = eval(problem) #solution within accepted bounds? if not, build another problem if not ((solution >= self.options.minSolution) and (solution <= self.options.maxSolution)): continue #don't ask the same question multiple times... if problem in self.set_asked: continue self.set_asked.add(problem) #answers other than digits will be ignored and the prompt will repeat while True: try: prompt = "\n\t\t" + problem + " = " self.writer(prompt,False) answer = raw_input(prompt) answer = int("%s" % (answer.strip())) except ValueError: continue break self.asked += 1 #good, or bad, answer? if (answer == solution): msg = GOOD_ANSWER % {"answer":answer} self.correct += 1 else: msg = BAD_ANSWER % locals() self.writer(msg,True) return #not exactly i18n, but it's a start GOOD_ANSWER = "\t\t\t\t\tAnswered:%(answer)2s. Correct." BAD_ANSWER = "\t\t\t\t\tAnswered:%(answer)2s. Wrong. Correct answer:%(solution)s" GREETING = "Hello, I am your friendly computer. I have a math quiz for you" FAREWELL = "\n\nCongratulations, you got %(correct)2s right out of %(asked)2s" HELP_NUMBER1 = "max value for number #1. this keeps things from getting too hard or easy. default:%s" HELP_NUMBER2 = """max value for number #2, defaults to use the same as number #1. the reason you may want to have different ranges is say doing the table of multiplications for 1 to 3 times 10""" HELP_MATH_OPERATORS = "math operators to use/ defaults: %s" HELP_REPETITIONS = "number of questions to ask [%s]" HELP_MIN_SOLUTION = "minimum solution you want [%s]. used to have simple or hard questions" HELP_MAX_SOLUTION = "maximum solution you want [%s]. used to have simple or hard questions" ERROR_MSG_OPERATORS = "no valid operators provided. supported operators: %(supported)s" def getParser(): """use optparse to prompt on the command line""" parser = optparse.OptionParser(usage = _module_doc) default = "10" parser.add_option("-1",action="store",type="int",default=default,dest="numberRange",help=HELP_NUMBER1 % (default)) parser.add_option("-2",action="store",type="int",dest="numberRange2",help=HELP_NUMBER2) default = "+-" parser.add_option("- o",action="store",dest="operators",default=default,help=HELP_MATH_OPERATORS % default) default = "20" parser.add_option("- r",action="store",type="int",dest="repetitions",default=default,help=HELP_REPETITIONS % default) default = "0" parser.add_option("- L",action="store",type="int",dest="minSolution",default=default,help=HELP_MIN_SOLUTION % default) default = "20" parser.add_option("- H",action="store",type="int",dest="maxSolution",default=default,help=HELP_MAX_SOLUTION % default) return parser def main(): worker = success = 0 try: (Worker.options, Worker.args) = getParser().parse_args(sys.argv[1:]) worker = Worker() success = worker.process() finally: if worker and worker.fout: worker.fout.close() if success : os.startfile(Worker.filename) if __name__ == "__main__": main() From srikrishnamohan at gmail.com Sat Sep 1 10:06:55 2007 From: srikrishnamohan at gmail.com (km) Date: Sat, 1 Sep 2007 19:36:55 +0530 Subject: metaclasses: timestamping instances Message-ID: Hi all, I have extended a prototype idea from Alex Martelli's resource on metaclasses regarding time stamping of instances. import time class Meta(type): start = time.time() def __call__(cls, *args, **kw): print 'Meta start time %e'%cls.start x = super(Meta, cls).__call__(*args, **kw) current_time = time.time() x._created = current_time - Meta.start Meta.start = time.time() return x class X(object): __metaclass__ = Meta class Y(X): __metaclass__ = Meta pass a = X() print 'a time stamp %e'%a._created b = Y() print 'b time stamp %e'%b._created print abs(a._created - b._created) I donot understand the difference between 1) setting __metaclass__ to 'Meta' in class Y 2) not setting __metaclass__ to Meta in class Y Why is the difference in behaviour of time stamping between 1 & 2 ? kindly enlighten regards, KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Thu Sep 20 04:13:58 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 20 Sep 2007 01:13:58 -0700 Subject: Google and Python In-Reply-To: <1190235678.019823.315850@o80g2000hse.googlegroups.com> References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> Message-ID: TheFlyingDutchman asked of someone: > Would you know what technique the custom web server uses > to invoke a C++ app No, I expect he would not know that. I can tell you that GWS is just for Google, and anyone else is almost certainly better off with Apache. > (ditto for Java and Python) CGI is supposed to be too slow > for large sites. Sort of. The more queries a site answers, the more benefit to reducing the per-request overhead. But if one thinks Google could not afford so much machine time: On average, a single query on Google reads hundreds of megabytes of data and consumes tens of billions of CPU cycles. http://labs.google.com/papers/googlecluster.html Another quote from that paper: We also produce all our software in-house [...] There's a saying in the Navy that there are three ways to do anything: the right way, the wrong way, and the Navy way. How does GWS invoke a Java app? The Google way. How does Google use Python? As their scripting-language of choice. A fine choice, but just a tiny little piece. Maybe Alex will disagree with me. In my short time at Google, I was uber-nobody. -- --Bryan From grante at visi.com Wed Sep 19 11:57:36 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 19 Sep 2007 15:57:36 -0000 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> <13f2hctdoob87e5@corp.supernews.com> Message-ID: <13f2hngbvli8v84@corp.supernews.com> On 2007-09-19, Steven D'Aprano wrote: > On Tue, 18 Sep 2007 18:09:26 -0700, TheFlyingDutchman wrote: > >> How much faster/slower would Greg Stein's code be on today's >> processors versus CPython running on the processors of the >> late 1990's? > > I think a better question is, how much faster/slower would > Stein's code be on today's processors, versus CPython being > hand-simulated in a giant virtual machine made of clockwork? That depends on whether you have the steam-driven model or the water-wheel driven model. The steam-drive one is quite a bit faster once you get it going, but the water-wheel model has a much shorter start-up time (though it is more weather dependent). -- Grant Edwards grante Yow! Hey, waiter! I want at a NEW SHIRT and a PONY TAIL visi.com with lemon sauce! From gregpinero at gmail.com Thu Sep 27 16:55:33 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Thu, 27 Sep 2007 13:55:33 -0700 Subject: How to Catch Errors in SimpleXMLRPCServer In-Reply-To: References: <1190921745.575519.53560@y42g2000hsy.googlegroups.com> Message-ID: <1190926533.435603.245530@o80g2000hse.googlegroups.com> On Sep 27, 3:55 pm, "Jeff McNeil" wrote: > Instead of register_function, use register_instance and provide a > _dispatch method in that instance that handles your exception logging. > > Pseudo: > > class MyCalls(object): > def _dispatch(self, method, args): > try: > self.getattr(self, method)(*args) > except: > handle_logging() > > server = SimpleXMLRPCServer(("localhost", 8000)) > server.register_instance(MyCalls()) > server.serve_forever() > > There might be an easier way... but this works for me. I wonder if there is something wrong with that. I get this error on calling ever method: Fault 1: 'exceptions.TypeError:cannot marshal None unless allow_none is enabled' but I can't see anywhere None would be coming from. -Greg From zentraders at gmail.com Wed Sep 12 18:02:05 2007 From: zentraders at gmail.com (Zentrader) Date: Wed, 12 Sep 2007 22:02:05 -0000 Subject: File Parsing Question In-Reply-To: References: Message-ID: <1189634525.522225.285930@k79g2000hse.googlegroups.com> Save the previous line in a variable if you want the previous line only. for line in inp: # Perform some operations with line if condition something: print prev_line print line break # I need to go back one line and use that line value --> prev_line = line If you want to do more than that, then use data=inp.readlines() or you can use data = open(myfile), "r").readlines(). The data will be stored in list format so you can access each line individually. From super.sgt.pepper at gmail.com Mon Sep 24 00:07:41 2007 From: super.sgt.pepper at gmail.com (Cristian) Date: Mon, 24 Sep 2007 04:07:41 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <46f6eb3d$0$32060$426a34cc@news.free.fr> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <1190419720.811685.145880@r29g2000hsg.googlegroups.com> <46f6eb3d$0$32060$426a34cc@news.free.fr> Message-ID: <1190606861.982113.25240@d55g2000hsg.googlegroups.com> On Sep 21, 5:21 pm, Bruno Desthuilliers wrote: > Ok, then what about classes ? They also are objects-like-any-other, > after all. So should we have this syntax too ? > > MyClass = class(ParentClass): > __init__ = function (self, name): > self.name = name > > ?-) For consistency I would suggest this, but Python already does this! Foo = type('Foo', (object, ), {'bar': lambda self, bar: bar}) I've created a new class and then binded it to name afterwards. If you can import modules without special syntax and you can create classes without special syntax, why should functions be treated any differently? From exhuma at gmail.com Tue Sep 18 11:04:29 2007 From: exhuma at gmail.com (exhuma.twn) Date: Tue, 18 Sep 2007 08:04:29 -0700 Subject: super, apply, or __init__ when subclassing? In-Reply-To: References: <1190100791.740269.62880@k79g2000hse.googlegroups.com> Message-ID: <1190127869.252585.303120@v29g2000prd.googlegroups.com> On Sep 18, 2:50 pm, "Gabriel Genellina" wrote: > En Tue, 18 Sep 2007 04:33:11 -0300, exhuma.twn escribi?: > > > This is something that keeps confusing me. If you read examples of > > code on the web, you keep on seeing these three calls (super, apply > > and __init__) to reference the super-class. This looks to me as it is > > somehow personal preference. But this would conflict with the "There > > one way to do it" mind-set. > > > So, knowing that in python there is one thing to do something, these > > three different calls must *do* domething different. But what exactly > > *is* the difference? > > There are a few typos in your examples. If you write them this way: > Example 3 was not really a typo on my side. While I was browsing around for python, I saw this in a code-fragment. So I thought this was the way to do it. Even though I thought "super(A..." does not make sense in a "semantic" way. Instead of just accepting this as a fact I probably should have trusted my gut-feeling and investigate. Nonetheless the posts (and explanations) here were really helpful for me to understand what's happening under the hood. But seeing these three variants of doing (nearly) the same was an itch I finally decided to scratch. So far I blindly used "Example 1" as it seemed to work for me. > > > > ------------ Exampel 1: ----------------------------- > > > class B(A): > > def __init__(self, *args): > > A.__init__(self, *args) > > > ------------ Exampel 2: ----------------------------- > > > class B(A): > > def __init__(self, *args): > > apply( A.__init__, (self,) + args) > > > ------------ Exampel 3: ----------------------------- > > > class B(A): > > def __init__(self, *args): > > super(B,self).__init__(*args) > > then 2 is exactly the same as 1 but using a deprecated function. And 3 is > the same as 1 only when there is single inheritance involved (and you are > using new-style classes). But see the thread "super() doesn't get > superclass" > > -- > Gabriel Genellina From tdelaney at avaya.com Mon Sep 24 06:35:36 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 24 Sep 2007 18:35:36 +0800 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190629152.3385.2.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: >> Where the heck does *this* come from? Neither Python 2.5.1 nor the >> 3.0alpha has this in `__builtin__`. > > It comes from the 'new' module: > >>>> import new >>>> help(new.function) > Help on class function in module __builtin__: > ... > > Oddly enough, the help misrepresents which module the function is > coming from. Not exactly: >>> help(type(lambda x: x)) Help on class function in module __builtin__: The function type is builtin, but it doesn't have an exposed name. `new.function` is simply a name bound to the function type. Note the help says *class* function ... Tim Delaney From thanosv at gmail.com Wed Sep 19 09:00:14 2007 From: thanosv at gmail.com (thanosv at gmail.com) Date: Wed, 19 Sep 2007 06:00:14 -0700 Subject: HTTP Protocol Client In-Reply-To: <1190196612.082912.149690@v23g2000prn.googlegroups.com> References: <1190196612.082912.149690@v23g2000prn.googlegroups.com> Message-ID: <1190206814.670422.72230@w3g2000hsg.googlegroups.com> On Sep 19, 6:10 am, welcomestocont... at gmail.com wrote: > Hi, > > I am writing http protocol to get some data from servers. If i was > using my localhost, getting replay from local and if want access other > remote sites, i am getting error. Please reply it > > My localhost client script::: > > Code: ( python ) > > import httplib > > h = httplib.HTTP('localhost',80) > > h.putrequest('GET','') > > h.putheader('User-Agent','Lame Tutorial Code') > > h.putheader('Accept','text/html') > > h.endheaders() > > errcode,errmsg, headers = h.getreply() > > print errcode,errmsg, headers > > f = h.getfile() # Get file object for reading data > > data = f.read() > > print data > > f.close() > > the Reply getting from this:::: > > 403 Forbidden Date: Tue, 18 Sep 2007 05:20:36 GMT > > Server: Apache/2.0.52 (Red Hat) > > Accept-Ranges: bytes > > Content-Length: 3985 > > Connection: close > > Content-Type: text/html; charset=UTF-8 > > And some Html script > > If I want to access other sites::: > > import httplib > > h = httplib.HTTP('http://Google.com',80) > > h.putrequest('GET','') > > h.putheader('User-Agent','Lame Tutorial Code') > > h.putheader('Accept','text/html') > > h.endheaders() > > errcode,errmsg, headers = h.getreply() > > print errcode,errmsg, headers > > f = h.getfile() # Get file object for reading data > > data = f.read() > > print data > > f.close() > > I got the error like::: > > Traceback (most recent call last): > File "c.py", line 6, in ? > h.endheaders() > File "/usr/lib/python2.3/httplib.py", line 712, in endheaders > self._send_output() > File "/usr/lib/python2.3/httplib.py", line 597, in _send_output > self.send(msg) > File "/usr/lib/python2.3/httplib.py", line 564, in send > self.connect() > File "/usr/lib/python2.3/httplib.py", line 532, in connect > socket.SOCK_STREAM): > socket.gaierror: (-2, 'Name or service not known') > > How can I access Remote sites using http protocol . I did'nt write > server script. > > Thanks And Regards > Allavarapu 1. First try setting the debug level with h.set_debuglevel(9) 2. nslookup or dig google.com 3. are you behind a firewall ? 4. why not just use urllib.urlopen ? Its a lot easier and sets up all the headers, and yes it can do POSTs. From paul at boddie.org.uk Mon Sep 17 05:51:52 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 17 Sep 2007 02:51:52 -0700 Subject: SVG to raster conversion. In-Reply-To: References: <46ED61E6.9010500@web.de> Message-ID: <1190022712.627003.180960@k79g2000hse.googlegroups.com> On 16 Sep, 19:50, "J. Cliff Dyer" wrote: > > Thanks. I can't find a gimp-python package for gimp-2.x anywhere > though. Does such a thing exist? I noticed that my copy of The GIMP has Python extensions, and looking at the package details... http://packages.ubuntu.com/feisty/graphics/gimp-python ...I can see that the gimp-python capabilities are provided by the source distribution for The GIMP itself. Perhaps you need to either install a package such as gimp-python for your operating system distribution or to configure and build The GIMP from source appropriately: I imagine that there's an --enable-python option (or something similar) for the configure script which has to find your Python installation in order for the bindings/extensions to be built. Paul P.S. For batch conversion of SVG images I've successfully used the ksvgtopng program supplied with KDE. From kar1107 at gmail.com Thu Sep 6 15:56:47 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Thu, 06 Sep 2007 12:56:47 -0700 Subject: concise code (beginner) In-Reply-To: References: <13dsvqrqivtf092@corp.supernews.com> <1189020188.842700.50950@d55g2000hsg.googlegroups.com> Message-ID: <1189108607.080926.103650@19g2000hsx.googlegroups.com> On Sep 5, 1:37 pm, James Stroud wrote: > Karthik Gurusamy wrote: > > On Sep 5, 11:17 am, James Stroud wrote: > > >> for i in xrange(number_of_reads): > >> for dev in devs: > >> try: > >> _reader = getattr(dev, 'read%d' % i) > >> _reader() > >> except Exception, e: > >> print e > >> devs.remove(dev) > > > I see in many of the solutions suggested above, the devs sequence/ > > iterator is being modified while iterating. I know it is not defined > > for interation over dictionary keys. Are they defined for other > > collections like lists? > > Good eye! My code is broke as you have noticed: > > py> r = range(5) > py> for i in r: > ... print i > ... if i % 2: > ... r.remove(i) > ... > 0 > 1 > 3 > > For longer sequences, the algorithm I've used in these cases in the past > goes something like this: > > py> r = range(10, 17) > py> print r > [10, 11, 12, 13, 14, 15, 16] > py> > py> i = 0 > py> while i < len(r): > ... j = r[i] > ... print j > ... if j % 2: > ... r.remove(j) > ... else: > ... i += 1 > ... > 10 > 11 > 12 > 13 > 14 > 15 > 16 > py> print r > [10, 12, 14, 16] > > Which would change my problematic code above to: > > for i in xrange(number_of_reads): > j = 0 > while j < len(devs): > try: > _reader = getattr(devs[j], 'read%d' % i) > _reader() > j += 1 > except Exception, e: > print e > devs.remove(dev) > > Another way is to make a copy of devs, if devs is short, which makes my > problematic code into a matter of a "typo"--maybe I can make this claim > to save some face? > > for i in xrange(number_of_reads): > for dev in devs[:]: > try: > _reader = getattr(dev, 'read%d' % i) > _reader() > except Exception, e: > print e > devs.remove(dev) > Thanks, personally I like this duplicate copy solution. It's cleaner and easier on the eye/brain. (Moreover the C like first solution assumes the collection is a sequence, which is not true for dictionary/ set like collections). That said, it may be a good future language enhancement to define a reasonable consistent behavior for an iterator over a changing collection. This occurs quite common when we walk a collection and usually delete the current item. For a sequence, what the expected behavior is quite obvious (just remove this element and go over to the next). For other collections like dictionary/set, again if the operation is delete, the expected behavior is obvious. If we are doing insertion, for sequence a well- defined behavior can be formulated (based on insert before or after current position -- if after we will see it in the walk, if before we won't see it) . For dict/set I see this isn't simple (as based on hash key we may insert ahead or later of the current 'cursor'/position. Karthik > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ From BjornSteinarFjeldPettersen at gmail.com Wed Sep 26 00:52:41 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Wed, 26 Sep 2007 04:52:41 -0000 Subject: ANN: PyPE 2.8.7 In-Reply-To: References: Message-ID: <1190782361.392001.48790@g4g2000hsf.googlegroups.com> On Sep 25, 12:37 pm, stef wrote: > Josiah Carlson wrote: > > === What is PyPE? === > > PyPE (Python Programmers' Editor) was written in order to offer a > > lightweight but powerful editor for those who think emacs is too much > > and idle is too little. Syntax highlighting is included out of the box, > > as is multiple open documents via tabs. > > sounds very good, > so now I want to try it ... > ... the windows ansi zip file is corrupted :-( > ... the unicode version crashes :-( > > This is what the log file tells: > Traceback (most recent call last): > File "pype.py", line 110, in ? > File "zipextimporter.pyc", line 78, in load_module > File "configuration.pyc", line 149, in ? > Exception: Unable to create config directory: 'G:\\.pype' > > I don't have a G-drive ;-) > > cheers, > Stef Mientki You must be doing it wrong. Works flawlessly for me (no g: drive here either) -- well, except that it doesn't have Emacs keybindings . -- bjorn From mrabens at gmail.com Mon Sep 10 17:19:25 2007 From: mrabens at gmail.com (Martoon) Date: Mon, 10 Sep 2007 14:19:25 -0700 Subject: C API (embedded Python): How to get and set named variables In-Reply-To: <%igFi.98606$Vk6.77403@newsfe07.phx> References: <1189447804.880483.175290@50g2000hsm.googlegroups.com> <%igFi.98606$Vk6.77403@newsfe07.phx> Message-ID: <1189459165.540646.305680@o80g2000hse.googlegroups.com> Thank you! Just what I needed. I came across the PyObject_*AttrString() functions earlier when searching through the docs, and I thought I was in the right area, but I didn't know what object I was supposed to set the attribute for. Now I see that it's a module object. It all makes sense now. Thanks! From hniksic at xemacs.org Tue Sep 25 09:44:25 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Sep 2007 15:44:25 +0200 Subject: sorting a list numbers stored as strings References: Message-ID: <877imeoo5i.fsf@mulj.homelinux.net> "Delaney, Timothy (Tim)" writes: > Yep - appears I must have been misremembering from another language > (dunno which) Tcl From bignose+hates-spam at benfinney.id.au Thu Sep 20 18:02:05 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 21 Sep 2007 08:02:05 +1000 Subject: Tapping into the access of an int instance References: Message-ID: <87y7f1t2qq.fsf@benfinney.id.au> "Tor Erik S?nvisen" writes: > Does anyone know how to interrupt the lookup of an integer value? AFAIK, int values *aren't* "looked up", in my understanding of that term. Can you explain what events you want to intercept? > Below is how far I've come... What I want is to tap into the access > of instance i's value 1... In many senses "instance i" *is* "value 1". What "access" do you want to intercept? Can you show some code examples of things that you would expect to trigger this "access"? Also, some similar events involving the instance that would *not* trigger the same thing. -- \ "The generation of random numbers is too important to be left | `\ to chance." -- Robert R. Coveyou | _o__) | Ben Finney From mccredie at gmail.com Tue Sep 4 18:28:20 2007 From: mccredie at gmail.com (Matt McCredie) Date: Tue, 4 Sep 2007 15:28:20 -0700 Subject: Registering a python function in C In-Reply-To: <1188861109.041382.178950@d55g2000hsg.googlegroups.com> References: <1188508874.879215.319400@i13g2000prf.googlegroups.com> <1188516423.744038.309700@z24g2000prh.googlegroups.com> <1188588784.764658.317570@r34g2000hsd.googlegroups.com> <1188592047.542946.249520@57g2000hsv.googlegroups.com> <1188861109.041382.178950@d55g2000hsg.googlegroups.com> Message-ID: <9e95df10709041528i7a6b3ec8k13db81b873341ab7@mail.gmail.com> > > Is Maya a different python build than what is contained at python.org? > > If so, I suggest you get your C program to work with the latest python > > build > > from python.org. Then see if you can get it to work with the Maya > > version. > > Ok, did that. If I write a normal C++ program and use the python > installed in my system, everything works ok and I can call the python > funtions. From within maya(where the C code is running as a plugin), > nothing happens. I tried removing my python installation so that only > the one that comes with maya is running, but then I have no python.h > or libs to compile against!! I found no help at the maya/python > newsgroup, is there anyone who has done this before??? I don't really know how maya works with python. Is it possible to just run arbitrary python code from maya? Can you get the version strings and stuff? >>>import sys >>>print sys.version That might give you a clue. It might just be that you need to compile against a different version of Python. You could always just download the different versions of Python and see if the included Python.h and Python.lib work. I would go in this order: 2.3, 2.4, 2.2, 2.5. Matt From george.sakkis at gmail.com Tue Sep 4 13:00:14 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 04 Sep 2007 17:00:14 -0000 Subject: Python is overtaking Perl In-Reply-To: References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> Message-ID: <1188925214.716404.219920@22g2000hsm.googlegroups.com> On Sep 4, 8:35 am, Jean-Paul Calderone wrote: > On Tue, 04 Sep 2007 00:32:23 -0000, Ben wrote: > >Here are the statistics from Google Trends: > > >http://benyang22a.blogspot.com/2007/09/perl-vs-python.html > > >From the graph, it seems more accurate to say that Perl is undertaking Python. > > Jean-Paul And to make it even more accurate, "Perl is undertaking Python in India", since that's where the difference in favor of Python comes from. George From iapain at gmail.com Sat Sep 1 03:17:14 2007 From: iapain at gmail.com (iapain) Date: Sat, 01 Sep 2007 07:17:14 -0000 Subject: Python Unicode to String conversion In-Reply-To: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> References: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> Message-ID: <1188631034.968347.116170@d55g2000hsg.googlegroups.com> First make sure your DB encoding is UTF-8 not the latin1 > The error I keep having is something like this: > ERREUR: S?quence d'octets invalide pour le codage ?UTF8? : 0xe02063 then try this: def smart_str(s, encoding='utf-8', errors='strict'): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. """ if not isinstance(s, basestring): try: return str(s) except UnicodeEncodeError: return unicode(s).encode(encoding, errors) elif isinstance(s, unicode): return s.encode(encoding, errors) elif s and encoding != 'utf-8': return s.decode('utf-8', errors).encode(encoding, errors) else: return s From wizzardx at gmail.com Thu Sep 27 03:57:58 2007 From: wizzardx at gmail.com (David) Date: Thu, 27 Sep 2007 09:57:58 +0200 Subject: Google and Python In-Reply-To: <004001c800d2$e96e20e0$03000080@hendrik> References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> <7xejgr68pm.fsf@ruckus.brouhaha.com> <7xps07w5g3.fsf@ruckus.brouhaha.com> <004001c800d2$e96e20e0$03000080@hendrik> Message-ID: <18c1e6480709270057j3c1ad69dn21a6d98b07a616f9@mail.gmail.com> > > It is trivial to pass a socket to a new thread or a forked child - you > > don't need this mechanism for that. It doesn't work on different > > machines though - it has to be on the same machine. > > 8< ------------- nice explanation by Nick----------------------- > > How does a very large volume site work then? - there must be some > way of sharing the load without bottlenecking it through one machine? > Large sites do load balancing (caching, dns round robin, reverse proxies, etc) over many hosts. Passing connection handles around on a single host is a different type of optimization. See this link for info on how Wikipedia handles their load-balancing: http://en.wikipedia.org/wiki/Wikipedia#Software_and_hardware From bscrivener42 at gmail.com Fri Sep 7 22:58:16 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Sat, 08 Sep 2007 02:58:16 -0000 Subject: Is a Borg rebellion possible? (a metaclass question) In-Reply-To: References: <1189168282.665210.260840@19g2000hsx.googlegroups.com> <1189180478.257790.60160@g4g2000hsf.googlegroups.com> Message-ID: <1189220296.951992.232570@k79g2000hse.googlegroups.com> On Sep 7, 1:53 pm, Steve Holden wrote: > All you really need is to create your SplinterBorgs with appropriate > group names, you don't neef subclasses at all: oops, I tried this once and the link broke. I'll try tinyurl. Dang. With that subject heading I thought this was about some post- Singularity, Python-programmed cyborgs rising up to take over the universe. See, e.g. How To Survive A Robot Uprising http://tinyurl.com/yrk5pw I am officially misled! rd From DustanGroups at gmail.com Fri Sep 7 07:47:12 2007 From: DustanGroups at gmail.com (Dustan) Date: Fri, 07 Sep 2007 11:47:12 -0000 Subject: unexpected behavior: did i create a pointer? In-Reply-To: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> Message-ID: <1189165632.401620.220530@w3g2000hsg.googlegroups.com> On Sep 7, 3:07 am, gu wrote: > hi to all! Hi! > after two days debugging my code, i've come to the point that the > problem was caused by an unexpected behaviour of python. or by lack of > some information about the program, of course! i've stripped down the > code to reproduce the problem: > > > a = {} > > for x in range(10): > for y in range(10): > a[x,y] = "0" > > copyOfA = a > > def functionA(x,y): > print a[x,y], > copyOfA[x,y] = "*" > print a[x,y],copyOfA[x,y] > > for x in range(10): > for y in range(10): > functionA(x,y) > > > > now, in the second "for" cycle and in functionA() i only 'touch' copyOfA > (altering it). as i don't touch the variable "a", i expect it not to be > affected by any change, but copyOfA acts like a pointer to a and > altering copyOfA's values result in altering the values of "a", so the > result that i expect is: > 0 0 * > 0 0 * > 0 0 * > 0 0 * > [..] > > but i get: > 0 * * > 0 * * > 0 * * > 0 * * > [..] > > what's going on? > thanks in advance. Welcome to Python! You might want to look at the documentation: http://docs.python.org/ And the tutorials: http://docs.python.org/tut/tut.html Leaping into python from another language without looking at the above documentation is not wise, since python has both a very different structure and a somewhat different philosophy from other languages. From korovev76 at gmail.com Thu Sep 20 06:01:29 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Thu, 20 Sep 2007 03:01:29 -0700 Subject: ONYX In-Reply-To: <46f1726f$0$15276$426a74cc@news.free.fr> References: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> <46f1726f$0$15276$426a74cc@news.free.fr> Message-ID: <1190282489.824709.29050@r29g2000hsg.googlegroups.com> On 19 Set, 21:02, Bruno Desthuilliers wrote: > > I don't know what's "onyx-style" xml, i'm not used to xml, so for me onyx is just a mess... http://www.onyx.com/Products/xml.asp > but if it's xml, any xml parser > will parse it, and any validating parser should be able to validate it > given the correct DTD. For example?where do I find a good validating parser? thanx again From uymqlp502 at sneakemail.com Mon Sep 3 22:43:49 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Mon, 03 Sep 2007 19:43:49 -0700 Subject: programming by contract using "decorators" Message-ID: <1188873829.158006.131900@y42g2000hsy.googlegroups.com> In the thread I started a few days ago, I was told that "programming by contract," could be done with "decorators." I was skeptical that this was a good approach, but as an exercise, I tried to code it up in a reasonably elegant form. I'd like to think I succeeded -- and I must admit that those who told me it could be done with decorators were right. My code is shown below. It shows a function called "myfunction," and another function for testing it called "myfunction_test." More detailed explanation follows the listing. Comments and feedback are welcome, of course. #!/usr/bin/env python def contract(test, check=0): "enforce programming by contract" if check: return test def null(func): def null2(*args, **keys): return func(*args, **keys) return null2 return null def getarg(args, keys, num, name): if name in keys: return keys[name] return args[num] def myfunction_test(myfunction): "contract test for function myfunction" def test(*args, **keys): x = getarg(args, keys, 0, 'x') y = getarg(args, keys, 1, 'y') z = getarg(args, keys, 2, 'z') # preconditions would go here, if there were any result = myfunction(x, y, z) # execute function assert result == x**2 + 3 * y + z # post-condition return result return test #======================================= CheckContracts = 1 @contract(myfunction_test, CheckContracts) def myfunction(x, y, z): return x**2 + 3 * y + z print myfunction(4, z=1, y=3) ------------------- end of listing --------------------- Here's what is going on. At the bottom of the listing, you will see the definition of a function called "myfunction," followed by a call of the function. It's a trivial function, but I gave it three arguments just to test passing them out of order by keyword. Just above the definition of "myfunction" is a "decorator" called "contract," which takes two arguments. The first argument specifies the name of the self-test contract function, which is "myfunction_test" in this case. The second argument is used to enable or disable the contract tests. Note that I could have just called the decorator "myfunction_test" and omitted the "contract" decorator, but I think this form, although slightly less efficient, is more readable. It also allows the enabling/ disabling logic to be put in one function rather than having to repeat it in every contract test function. Dealing with the arguments was not a trivial matter -- at least not for me. I had to experiment a bit to get it right. The "getarg" function is simply a utility for parsing the ordered and keyword arguments. It's very simple, but if something like this already exists, please let me know. Thanks. From duncan.booth at invalid.invalid Mon Sep 10 04:57:42 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Sep 2007 08:57:42 GMT Subject: Python syntax wart References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> <5ki2sdF3nr68U1@mid.individual.net> <5kk8p0F3vfqqU1@mid.uni-berlin.de> <5kkcmvF3vfqqU3@mid.uni-berlin.de> <46E50239.7050007@web.de> Message-ID: Stefan Behnel wrote: > This actually sounds somewhat pointless to me. If complex things don't > fit into one line, a good way to deal with it is not to insist on > making them a single statement. > Or make them into a single method/function call. I would post some pseudo- code replacing the TheProduct conditions with a single call to a meaningfully named method except I haven't got the faintest idea what it is trying to achieve. From michele.simionato at gmail.com Thu Sep 20 00:40:33 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 20 Sep 2007 04:40:33 -0000 Subject: Mixin classes and single/multiple inheritance In-Reply-To: <87tzpquhol.fsf@benfinney.id.au> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> <877immvye0.fsf_-_@benfinney.id.au> <1190257864.945639.199230@k79g2000hse.googlegroups.com> <87tzpquhol.fsf@benfinney.id.au> Message-ID: <1190263233.710025.109280@d55g2000hsg.googlegroups.com> On Sep 20, 5:41 am, Ben Finney wrote: > Michele Simionato writes: > > Ben Finney wrote: > > > What do you see as an appropriate use of mixin classes, and what > > > an abuse? > > > An example of fine usage of mixin is Tkinter; an example of bad > > usage if Zope 2. > > Which parts of those two very large code sets do I need to look at to > see the examples you have in mind? I was hoping you could demonstrate > with short code examples. Unfortunately you see the issue only when you program in the large. Take for instance the Plone BaseContent class; I believe its MRO contains something like 35 classes (I don't remember the exact number now) in a multiple inheritance hierarchy. Instances have some something like 400+ methods and attributes. Now try to understand from which of the parent classes the attributes came. For Tkinter things are much easier, see the effbot "Introduction to Tkinter" for a discussion of the mixin classes it uses. Then try something like inspect.getmro(Tkinter.Label) , there are only 7 classes in the hierarchy. Notice that even with single inheritance you can run in deep hierarchies (Java docet).The problem, as Guido once said, is the "inheritance is overrated". Michele Simionato From mccredie at gmail.com Mon Sep 10 14:19:30 2007 From: mccredie at gmail.com (Matimus) Date: Mon, 10 Sep 2007 18:19:30 -0000 Subject: Question about PEP 8 In-Reply-To: References: Message-ID: <1189448370.564030.13120@19g2000hsx.googlegroups.com> > will Py3K change the standard library names in order to follow PEP 8?) Just continue down the list of PEPs and you will find the answer: http://www.python.org/dev/peps/pep-3108/#modules-to-rename This covers built-in modules. It doesn't cover 3rd party modules, like wx. Most likely you will still see pep8 violations in non-standard modules. As for following or not following pep8 in conjunction with 3rd party modules. Just make your code look nice. Don't go out of your way to follow pep8 if it means that there will be a mix of styles that will be confusing. If you are overloading a class that is part of wx I would use the same style that wx uses. The reasoning being that people who might use that class would probably see it as just another wx class, and expect it to look and behave a certain way. Don't dissapoint them. Matt From mensanator at aol.com Sun Sep 16 15:05:29 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 16 Sep 2007 12:05:29 -0700 Subject: Try this In-Reply-To: <13eqsdfsfvsa16f@corp.supernews.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> Message-ID: <1189969529.652871.19280@50g2000hsm.googlegroups.com> On Sep 16, 1:10?pm, Dennis Lee Bieber wrote: > On Sun, 16 Sep 2007 01:46:34 -0700, GeorgeRXZ > declaimed the following in comp.lang.python: > > > Then Open the Notepad and type the following sentence, and save the > > file and close the notepad. Now reopen the file and you will find out > > that, Notepad is not able to save the following text line. > > > Well you are speed > > > This occurs not only with above sentence but any sentence that has > > > 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) > > I tried. I also opened the saved file in SciTE... > And the text WAS there... > > It is Notepad that can not properly render what it, > itself, saved. C:\Documents and Settings\mensanator\My Documents>type huh.txt Well you are speed Yes, file was saved correctly. But reopening it shows 9 unprintable characters. If I copy those to a new file (huh1.txt): C:\Documents and Settings\mensanator\My Documents>type huh1.txt ????????? But wait...the new file is 20 characters, not 9. 09/16/2007 01:44 PM 18 huh.txt 09/16/2007 01:54 PM 20 huh1.txt C:\Documents and Settings\mensanator\My Documents>dump huh.txt huh.txt: 00000000 5765 6c6c 2079 6f75 2061 7265 2073 7065 Well you are spe 00000010 6564 ed Here's what it's actually doing: C:\Documents and Settings\mensanator\My Documents>dump huh1.txt huh1.txt: 00000000 fffe 5765 6c6c 2079 6f75 2061 7265 2073 .~Well you are s 00000010 7065 6564 peed From pyth0nc0d3r at gmail.com Fri Sep 14 17:59:50 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 14 Sep 2007 16:59:50 -0500 Subject: Just bought Python in a Nutshell In-Reply-To: References: <1189784843.896396.108960@g4g2000hsf.googlegroups.com> <59f9c5160709141412q1098a4cbi989b6eed2f2cc899@mail.gmail.com> Message-ID: Wow I just got it, and its nice doesn't even look used god damn. :D. On 9/14/07, Lamonte Harris wrote: > > Lol, you bought it, dude theres not one left imho. When I bought it, it > still said 1 More left Lol...mines should be her no less then a hour -.-... > Taking SO LONG. > > On 9/14/07, Danyelle Gragsone wrote: > > > > Luckily that site still had one left .. so i brought it :D. I can > > always use another good and CHEAP book. > > > > Danyelle > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Tue Sep 18 20:59:02 2007 From: python at rcn.com (Raymond Hettinger) Date: Tue, 18 Sep 2007 17:59:02 -0700 Subject: Sets in Python In-Reply-To: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> Message-ID: <1190163542.585160.16230@w3g2000hsg.googlegroups.com> On Sep 18, 5:39 pm, sapsi wrote: > I recently tried using the set function in Python and was surprised to > find that > > a=[ 1, 2,3, [1,2] ] > > doesn't work with 'set', throwing TyperError (unhashable exception). I > found out that this is because lists can't be hashed. > So,this implies 'a' cannot be a set in python which i think is quite > unfortunate, after all 'a' does look like a mathematical set. This is written as: a = set([1, 2, 3, frozenset([1, 2])]) > This is not related, but is there i neat way (without pop and list > comprehension) to convert a set into a list? list(a) Raymond From stef.mientki at gmail.com Thu Sep 13 18:25:54 2007 From: stef.mientki at gmail.com (stef mientki) Date: Fri, 14 Sep 2007 00:25:54 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <46e9b09c$0$7685$9b4e6d93@newsspool2.arcor-online.net> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> <5ktfb5F5ctrvU1@mid.individual.net> <46e98e01$0$30383$9b4e6d93@newsspool4.arcor-online.net> <46e9921e$0$26251$426a74cc@news.free.fr> <46e995d1$0$16120$9b4e6d93@newsspool1.arcor-online.net> <46e9b09c$0$7685$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <46E9B8F2.9090506@gmail.com> >>> Certainly, but again: Such main people are not the intended audience. >>> The code is for people that know how to read these equations. I think >>> a general rule of (any form of) writing is to write with your audience >>> in mind. I always do that and happily, that audience is usually naked. >>> >>> >>> >>> >> Wouldn't Mathematica, Maple or MathCad be a far better choice ? >> >> > Well, those cost money ... > > Indeed, so I wondered why there isn't open source alternative (at least I didn't find one). some Latex derivate + wxPython + Python could do the job > Hey, why am *I* arguing here at all? This isn't my thread! > Well, I guess the scientist in me felt tickled. > Well, i'm on the sideline too ;-) cheers, Stef From tec at knology.net Tue Sep 11 09:22:19 2007 From: tec at knology.net (Tim) Date: Tue, 11 Sep 2007 06:22:19 -0700 Subject: memcpy In-Reply-To: <5knhtpF4b65dU6@mid.uni-berlin.de> References: <1189449530.171049.323230@22g2000hsm.googlegroups.com> <5klnsbF3vfqqU10@mid.uni-berlin.de> <1189512598.410810.224340@y42g2000hsy.googlegroups.com> <5knhtpF4b65dU6@mid.uni-berlin.de> Message-ID: <1189516939.394375.248830@d55g2000hsg.googlegroups.com> On Sep 11, 8:01 am, Marc 'BlackJack' Rintsch wrote: > On Tue, 11 Sep 2007 05:09:58 -0700, Tim wrote: > > On Sep 10, 3:31 pm, Marc 'BlackJack' Rintsch wrote: > >> On Mon, 10 Sep 2007 11:38:50 -0700, Tim wrote: > >> > How do I memcpy from a pointer to an array of floats in python? > > >> > I get errors: NameError: global name 'row' is not defined > > >> Well than the (global) name `row` is not defined. Quite clear message, > >> isn't it? ;-) > > >> > I want to be able to get the row[i] array element. In C I would > >> > normally place the address of row as the first argument. > > >> > cdll.msvcrt.memcpy( row, pData, 256 ) > > >> > If I define row as the following I also get the following error: > > >> > row = ones( TOTAL_PARAMETER_ENTRIES, dtype=float ) > > >> > ArgumentError: argument 1: : Don't know > >> > how to convert parameter 1 > > >> You don't give enough information so we have to guess. For example I > >> guess the `ones()` function comes from one of the packages `numeric`, > >> `numarray` or `numpy`!? > > >> This function returns a Python object. You can't use arbitrary Python > >> objects with `ctypes`. `memcpy` expects a pointer not an object. > > > Can I initialize something in Python that I can get access to it's > > pointer? > > "It's pointer"? Then you have a pointer to a structure that represents > the Python object but still no idea what data is at that pointer. This is > an implementation detail of the Python version and of the particular > object. > > > Here is what I would like to write: > > > shared_memory_pointer = windll.kernel32.MapViewOfFile(hMapObject, > > FILE_MAP_ALL_ACCESS, > > 0, 0, TABLE_SHMEMSIZE) > > > memcpy( self.data, shared_memory_pointer, my_size ) > > I haven't tested but it should be possible to declare the return type of > `windll.kernel32.MapViewOfFile()` as ``ctypes.POINTER(ctypes.c_double * > 256)`` and then do: > > test_data = numpy.ones(1000) > shared_memory_pointer.contents[0:256] = test_data[0:256] > > Ciao, > Marc 'BlackJack' Rintsch- Hide quoted text - > > - Show quoted text - Is this what you mean? Python did not like the word c_types in front of POINTER. Do you know why? How can I re-declare a function's return type if it is declared somewhere else? test_data = numpy.ones(1000) shared_memory_pointer = POINTER(c_float*256) shared_memory_pointer = windll.kernel32.MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE) test_data[0:256]= shared_memory_pointer.contents[0:256] print 'data:', test_data[0] From bignose+hates-spam at benfinney.id.au Tue Sep 18 01:24:21 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 18 Sep 2007 15:24:21 +1000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> Message-ID: <87zlzkzgu2.fsf@benfinney.id.au> Evan Klitzke writes: > On Tue, 2007-09-18 at 14:15 +1000, Ben Finney wrote: > > Why does the documentation of 'super' say that it returns the > > superclass when *that's not true*? It doesn't return the > > superclass, it returns the next class in the MRO, whether that's a > > superclass or not. > > The next class in the MRO _is_ a superclass. Maybe not the way > you've defined it in your own code, but certainly of the new class > you created with MI. If I define a class hierarchy as follows:: class A(object): pass class B(object): pass class C(A): pass class D(B): pass is it true to say that "D is a superclass of A"? No, because they're entirely unrelated except that they inherit from 'object'. The superclass of 'A' is 'object'. How about this: class E(C, D): pass In this instance, the MRO now has D following A; but the superclass of 'A' is still 'object'. You seem to be saying that now suddenly D *is* a superclass of A. That's certainly not what users will think of when they think "superclass" though. > > Actually, even that's not true. The error message "AttributeError: > > 'super' object has no attribute 'bazfunc'" makes it clear that > > 'super' actually returns not the superclass, but a 'super' object, > > whatever that's supposed to be. > > No, super really does return a class. What makes you think that > super returns a special sort of object? >>> super(A) , NULL> >>> super(A).__class__ What I expect, incidentally, is that a function documented as "returns the superclass of 'type'" would actually return that class (in this case, the type 'object'), not an object of 'super' type. > > After reading the rest of the article, I'm amazed that 'super' as > > currently implemented is in Python at all. I agree with the author > > that it's useless unless *everyone* uses it for *everything*, and > > even then it's pretty limited. > > I don't see what the problem is. If you don't use super, then you can > break the inheritance chain I don't want to break the inheritance chain. I want the superclass, not the "next class in the MRO". Orthogonally to that, I think it's madness to write a function for "return the next class in the MRO for 'type'" and document it as "return the superclass of 'type'". Am I mistaken in thinking that "superclass of foo" is equivalent to "parent class of foo"? If so, I'd lay heavy odds that I'm not alone in that thinking. -- \ "Laugh and the world laughs with you; snore and you sleep | `\ alone." ?anonymous | _o__) | Ben Finney From surye80 at gmail.com Tue Sep 18 19:42:38 2007 From: surye80 at gmail.com (Vince Castellano) Date: Tue, 18 Sep 2007 23:42:38 -0000 Subject: Custom PYTHONPATH not being seen by -m Message-ID: <1190158958.441168.307740@q3g2000prf.googlegroups.com> Hello, I am running RHEL5, with Python 2.4.3. I do not experience this problem on my other machines, which are 2.5. The following should demonstrate my issue: [16:38][vince:~]$ python -m srctools.symbol_replace -h python: module srctools.symbol_replace not found [16:40][vince:~]$ python Python 2.4.3 (#1, Dec 11 2006, 11:38:52) [GCC 4.1.1 20061130 (Red Hat 4.1.1-43)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import srctools.symbol_replace >>> srctools.symbol_replace >>> [16:41][vince:~]$ echo $PYTHONPATH /usr/local/pymodules Thank you, Vince From http Thu Sep 20 10:57:55 2007 From: http (Paul Rubin) Date: 20 Sep 2007 07:57:55 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190263363.496695.83300@57g2000hsv.googlegroups.com> Message-ID: <7xwsulv0y4.fsf@ruckus.brouhaha.com> "Chris Mellon" writes: > No. Python has threads, and they're wrappers around true OS level > system threads. What the GIL does is prevent *Python* code in those > threads from running concurrently. Well, C libraries can release the GIL if they are written for thread safety, but as far as I know, most don't release it. For example I don't think cElementTree releases the GIL, and it's a huge CPU consumer in some of the code I run, despite being written in C pretty carefully. Also, many of the most basic builtin types (such as dicts) are implemented in C and don't release the GIL. > Very, very few operations are CPU bound these days, and even fewer of > the ones were Python is involved. The largest benefits to the desktop > user of multiple cores are the increase in cross-process performance > (multitasking), not single applications. If you add up all the CPU cycles being used by Python everywhere, I wonder how many of them are on desktops and how many are on servers. > Python is not especially fast in terms of pure CPU time, so > if you're CPU bound anyway moving your CPU bound code into C (or > something else) is likely to reap far more benefits - and sidestepping > the GIL in the process. If moving code into C is so easy, why not move all the code there instead of just the CPU-bound code? Really, coding in C adds a huge cost in complexity and unreliability. Python makes life a lot better for developers, and so reimplementing Python code in C should be seen as a difficult desperation measure rather than an easy way to get speedups. Therefore, Python's slowness is a serious weakness and not just a wart with an easy workaround. > In short, I think any problem that would be directly addressed by > removing the GIL is better addressed by other solutions. It does sound like removing the GIL from CPython would have very high costs in more than one area. Is my hope that Python will transition from CPython to PyPy overoptimistic? From bronger at physik.rwth-aachen.de Thu Sep 6 01:04:55 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 06 Sep 2007 07:04:55 +0200 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? References: <46DEFD2E.5050205@sbcglobal.net> <87tzq898e2.fsf@wilson.homeunix.com> <87ejhc8z23.fsf@wilson.homeunix.com> Message-ID: <87y7fk75ag.fsf@wilson.homeunix.com> Hall?chen! Alan Isaac writes: > Torsten Bronger wrote: > > [...] > >> Their only flaw is that they are not "virtual" (in C++ speak). >> In other words, you can't pass a "self" parameter to them. > > http://www.kylev.com/2004/10/13/fun-with-python-properties/ Thanks, I knew the possibility of using another level of indirection vir explicit __set and __get methods but I haven't seen a solution with lambda yet. I think on ActiveState's Python Cookbook site there was a quite longish solution, too. Then I formulate it more precisely: The "self" parameter is passed to the setters and getters, however, it is not used for calling the "correct" ones. "Correct" seems to be in the eye of the beholder: The Python designers apparently intentionally chose this odd "semi-static" behaviour of "property". But I think a fully virtual behaviour would fit better into the Python mentality, it is easier to explain, and it has more use cases. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From martinmichel at ame-electroplating.com Sun Sep 16 11:54:34 2007 From: martinmichel at ame-electroplating.com (Martin M.) Date: Sun, 16 Sep 2007 15:54:34 -0000 Subject: Parsing problems: A journey from a text file to a directory tree Message-ID: <1189958074.670245.17910@n39g2000hsh.googlegroups.com> Hi everybody, Some of my colleagues want me to write a script for easy folder and subfolder creation on the Mac. The script is supposed to scan a text file containing directory trees in the following format: [New client] |-Invoices |-Offers |--Denied |--Accepted |-Delivery notes As you can see, the folder hierarchy is expressed by the amounts of minuses, each section header framed by brackets (like in Windows config files). After the scan process, the script is supposed to show a dialog, where the user can choose from the different sections (e.g. 'Alphabet', 'Months', 'New client' etc.). Then the script will create the corresponding folder hierarchy in the currently selected folder (done via AppleScript). But currently I simply don't know how to parse these folder lists and how to save them in an array accordingly. First I thought of an array like this: dirtreedb = {'New client': {'Invoices': {}, 'Offers': {'Denied': {}, 'Accpeted': {}}, 'Delivery notes': {}}} But this doesn't do the trick, as I also have to save the hierarchy level of the current folder as well... Argh, I really don't get my head around this problem and I need your help. I have the feeling, that the answer is not that complicated, but I just don't get it right now... Your desperate, Martin From timr at probo.com Tue Sep 11 03:58:33 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 11 Sep 2007 07:58:33 GMT Subject: Using a time duration to print out data where every 2 seconds is a pixel References: <1189427545.322679.260970@r29g2000hsg.googlegroups.com> <1189436278.456311.128260@22g2000hsm.googlegroups.com> Message-ID: <6hice3hjf9r8tv6ru5pm7rhldge0cd3pra@4ax.com> cjt22 at bath.ac.uk wrote: >Thanks however I am still having a problem using the time module for >arithmetic > >My string times are of values such as 09:55:17 > >and I have code such as: > >>from time import * >>startPoint = strptime(step.sTime, "%H:%S:%M") >>finishPoint = strptime(step.fTime, "%H:%S:%M") Your conversion strings cannot be correct. Sure, there are international differences in rendering dates and times, but not even in Eastern WhereTheHeckIsStan do they encode hours, then seconds, then minutes. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mal at egenix.com Fri Sep 28 14:52:14 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 28 Sep 2007 20:52:14 +0200 Subject: OCBC connection In-Reply-To: References: <1191000128.112881.111790@r29g2000hsg.googlegroups.com> Message-ID: <46FD4D5E.9040704@egenix.com> On 2007-09-28 20:07, Steve Holden wrote: > kyosohma at gmail.com wrote: >> On Sep 28, 9:57 am, "Sugrue, Sean" wrote: >>> I'm trying to make an odbc connection to postgresql which is on a server >>> using python. >>> Does anyone have a code snippet to make a basic connection with a select >>> query? >>> >>> Sean >> Sean, >> >> This appears to be what you're looking for: >> >> http://www.devx.com/opensource/Article/29071 >> >> See also Python Database spec and module page: >> >> http://www.python.org/topics/database/ >> > Mike: > > This doesn't address the ODBC part of the inquiry. I was actually going > to respond saying I wasn't aware of an ODBC driver for PostgreSQL > (though I'd be surprised if there wasn't one). There is one: http://www.postgresql.org/ftp/odbc/versions/ and it works quite well with mxODBC on all supported platforms. Here's a step-by-step guide for the Windows installation: http://www.sparxsystems.com/EAUserGuide/setupapostgresqlodbcdriver.htm Note that you should add these settings to your odbc.ini section for the PostgreSQL data source in order to avoid problems with BLOBs: # Fetch BYTEA and TEXT as LongVarXXX column types: ByteaAsLongVarBinary = 1 TextAsLongVarchar = 1 Alternatively, you can try the OpenLink driver: http://uda.openlinksw.com/odbc/st/odbc-postgres-st/ If you're on Max OS, you should have a look at the ActualTech drivers: http://www.actualtechnologies.com/product_opensourcedatabases.php Regards, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 28 2007) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From __peter__ at web.de Mon Sep 24 11:29:27 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Sep 2007 17:29:27 +0200 Subject: strange behavious of the logging module? References: <1190643051.084144.230220@o80g2000hse.googlegroups.com> Message-ID: Vinay Sajip wrote: > On Sep 24, 8:03 am, Peter Otten <__pete... at web.de> wrote: >> >> It would still be a good idea to file a bug report. > > Not sure where the bug is. The script below, when called, prints > "Information" to the console and "INFO some_func Information" to > mc_rigid.log, as I would expect. (Python 2.5.1) I get $ python vinaj.py Information $ cat mc_rigid.log INFO info Information Maybe a platform issue (I'm on Ubuntu 7.04)? It seems Logger.findCaller() gets puzzled by the following discrepancy: >>> logging.info.func_code.co_filename 'logging/__init__.py' >>> logging._srcfile '/usr/lib/python2.5/logging/__init__.py' I don't think I have messed with paths manually on that machine, by the way. Peter From rt at nospam.com Fri Sep 21 17:17:48 2007 From: rt at nospam.com (Richard Townsend) Date: Fri, 21 Sep 2007 22:17:48 +0100 Subject: Resolving windows shortcut to url References: <46f422d8$0$3030$e4fe514c@dreader31.news.xs4all.nl> <46f428ce$0$3030$e4fe514c@dreader31.news.xs4all.nl> Message-ID: <8ec8f3db0bpda3k6s8sh6f0m0o3aock1jt@4ax.com> On Fri, 21 Sep 2007 22:29:37 +0200, Ivo wrote: >Ivo wrote: >> Richard Townsend wrote: >>> If I have a windows shortcut to a URL, is there a way to get the URL >>> in a Python app? >>> >>> I found some code that uses pythoncom to resolve shortcuts to local >>> files, but I haven't found any examples for URLs. >>> >>> The PyWin32 help mentions the PyIUniformResourceLocator Object, but I >>> couldn't find an example of how to use it. >>> >> do you mean a *.lnk file or a *.url file? > >for a link (*.lnk) file: > > >from win32com.shell import shell >import pythoncom >import os, sys > >class PyShortcut(object): > def __init__(self): > self._base = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, > None, > >pythoncom.CLSCTX_INPROC_SERVER, > shell.IID_IShellLink) > > def load(self, filename): > >self._base.QueryInterface(pythoncom.IID_IPersistFile).Load(filename) > > def save(self, filename): > >self._base.QueryInterface(pythoncom.IID_IPersistFile).Save(filename, 0) > > def __getattr__(self, name): > if name != "_base": > return getattr(self._base, name) > > >if __name__=="__main__": > lnk = PyShortcut() > lnk.load("path to your shortcut file including the .lnk extention >even if you don't see it in windows") > print "Location:", lnk.GetPath(shell.SLGP_RAWPATH)[0] Hi Ivo, I belive it is *.lnk files I'm interested in. For example: C:\Documents and Settings\All Users\Start Menu\Programs\Development\Winpdb\winpdb-homepage.lnk points to http://www.digitalpeers.com/pythondebugger/ However, your code is returning an empty string for location. lnk.GetPath(shell.SLGP_RAWPATH) returns the tuple: ('', (0, , , , 0L, 0L, 0L, 0L, '', '')) Regards, Richard Townsend From arkanes at gmail.com Mon Sep 17 14:32:36 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 17 Sep 2007 13:32:36 -0500 Subject: Try this In-Reply-To: <46EEC55A.9070602@holdenweb.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> <1190008502.986300.286280@22g2000hsm.googlegroups.com> <1190051875.433350.150820@50g2000hsm.googlegroups.com> <46EEC55A.9070602@holdenweb.com> Message-ID: <4866bea60709171132o3a4210d2x21c76859b4056114@mail.gmail.com> On 9/17/07, Steve Holden wrote: > "Cretin" (in the sense of possessing sub-normal intelligence, as I do > not know whether or not you have a thyroid deficiency) because you do > not seem to be able to think of the needs of the larger community, and > respond to argument with non-sequitur and evasion. > > Plus, you annoyed me. I should have restrained myself. Sorry. I'm just adding to the noise here to comment that this rant is causing this thread to display a dozen or so ads for thyroid medication in gmail, which I find rather amusing. From rrr at ronadam.com Fri Sep 21 03:32:00 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 21 Sep 2007 02:32:00 -0500 Subject: Python 3K or Python 2.9? In-Reply-To: <1190053757.091035.221570@22g2000hsm.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1190013827.107324.111820@w3g2000hsg.googlegroups.com> <1190053757.091035.221570@22g2000hsm.googlegroups.com> Message-ID: <46F37370.9040809@ronadam.com> TheFlyingDutchman wrote: > I am not talking about the way it does it, but rather, the way it > could do it or... could have done it. That requires no knowledge of > how the interpreter currently does it unless I am proposing something > that no interpreter in the world could ever do. Yes, there are a couple of things that could have been changed. But from what I can tell there are a number of reasons why things where chosen to be the way they are. Two of those reasons is to make the core C code smaller and easier to maintain and also to make it easier to understand how things work. Exposing the inner workings as visible python code vs hidden C code helps both of those. Another benefit of exposing more of the class machinery of Pythons objects as python code, is it makes it possible to modify more of how things work directly with python code. A good way to see how this works is studying how descriptors and properties work. http://users.rcn.com/python/download/Descriptor.htm You will find there is much more of python written in python than it may first seem. In some cases the built in classes and modules are written in C, yet they still work as if they are written in Python. So if you can find a way to do things like removing self in python in such a way that it doesn't require adding more to the Core interpreter, then it might be considered. What I've found is as my skills improve, I take more advantage of being able to modify and/or introspect how things work. This allows more choices on how I might solve a particular problem. I also think there a lots of improvements that could be made to other parts of python such as the libraries that would be of much more practical benefit. Regards, Ron From stodge at gmail.com Sun Sep 16 15:05:38 2007 From: stodge at gmail.com (Stodge) Date: Sun, 16 Sep 2007 19:05:38 -0000 Subject: Saving parameters between Python applications? Message-ID: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> I'm trying to do the following. I have a Python application that is run: python app1.py --location=c:\test1 What I want to do is save the location parameter, so I can then do (in the same window): python app2.py And have app2.py automatically have access to the value of "location". Now, the difficult part is, that in another window I want to do: python app1.py --location=c:\test2 python app2.py And have app2.py automatically get c:\test2 as the location. So the two windows (consoles) are isolated from each other. I thought I could use os.environ, but that doesn't save the variable for applications that are run afterwards in the same window. Any suggestions? Thanks From michele.simionato at gmail.com Mon Sep 3 03:33:41 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 03 Sep 2007 07:33:41 -0000 Subject: How does super() work? In-Reply-To: References: Message-ID: <1188804821.692585.138560@r29g2000hsg.googlegroups.com> > En Fri, 31 Aug 2007 17:58:24 -0300, Lamonte Harris > escribi?: > > > I've searched Google, and other search engines to try to find out how > > super() works. Can someone explain in short detail how super() works? I > > may and may not need to know this information, but it is good to know. You may also look at my ACCU lectures on advanced Python: http://www.phyast.pitt.edu/~micheles/oxford-lectures.zip From dimitri.pater at gmail.com Wed Sep 5 15:14:08 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Wed, 5 Sep 2007 21:14:08 +0200 Subject: StringIO MySQL data blob Image problem In-Reply-To: References: <46DEAAAB.8040008@timgolden.me.uk> Message-ID: ---------- Forwarded message ---------- From: dimitri pater Date: Sep 5, 2007 9:13 PM Subject: Re: StringIO MySQL data blob Image problem To: Tim Golden > Well, I'm mystified. Not by your results: that exactly what I > expected to get, but because you're doing everything *except* > manipulating an image and putting it into a PDF via ReportLab. > Dear Tim, you are right of course, I have been trying to put the StringIO in a temp file: cfoto=StringIO cfoto.write(result[0][1].tostring()) dfoto=cfoto.getvalue() fileFoto=open('temp.jpg','wb') fileFoto.write(dfoto) and indeed, the blob from MySQL is saved as an image! however, foto= Image('temp.jpg') and inserting foto into a table results in: x = struct.unpack('B', image.read(1)) error: unpack str size does not match format oh, well... still needs some work BTW: I used 'local' images before (I mean they did not originate from a DB), that worked well in Reportlab's tables. Thanks, I am getting there (I think) -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org From lorestar at gmail.com Mon Sep 17 19:50:45 2007 From: lorestar at gmail.com (Lorenzo Stella) Date: Mon, 17 Sep 2007 16:50:45 -0700 Subject: can Python be useful as functional? Message-ID: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Hi all, I haven't experienced functional programming very much, but now I'm trying to learn Haskell and I've learned that: 1) in functional programming LISTS are fundmental; 2) any "cycle" in FP become recursion. I also know that Python got some useful tool such as map, filter, reduce... so I told: "let's try some FP-style programming with Python!". I took a little example of Haskell: listprimes :: Integer -> [Integer] listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)] where sieve [] = [] sieve (p:xs) = p : sieve (filter (\x -> mod x p > 0) xs) and I tried to "translate" it in Python: def sieve(s): if s == []: return [] else: return [s[0]] + sieve(filter((lambda x: x % s[0] > 0), s[1:])) def listprimes(n): return sieve(range(2,n)) These should be almost the same: listprimes actually lists prime integers up to n-1. The result is: Haskell implementation works well, maybe it's not the better way to do it, but it does what I wanted. Python implementation gives me RuntimeError: maximum recursion depth exceeded in cmp My question is: how can we call a language "functional" if it's major implementation has a limited stack? Or is my code wrong? LS From zzbbaadd at aol.com Wed Sep 5 02:09:20 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 04 Sep 2007 23:09:20 -0700 Subject: list index() In-Reply-To: <871wdd92vk.fsf@benfinney.id.au> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <5jn9qgFdmbcU3@mid.uni-berlin.de> <1188886461.236237.168230@y42g2000hsy.googlegroups.com> <871wdd92vk.fsf@benfinney.id.au> Message-ID: <1188972560.323189.33880@d55g2000hsg.googlegroups.com> > > I explain it by noting that list.index and dict.get serve totally > different purposes. The former returns the index given a value; the > latter returns a value given a key. And the former raises an exception if the value is not found, while the latter returns None if the value is not found. > > There are many areas of poor symmetry in the language and libraries; > it isn't particularly clever or difficult to find them if one > looks. Doing so doesn't appear to illustrate any point I see relevant > in this thread. It has been stated in this thread, that in Python, exceptions are used differently than in other languages. Rather than just use them for catastrophic errors that can't be dealt with, Python raises exceptions on routine and survivable situations such as an item not found in a list. It was mentioned that an exception is more Pythonic than returning a "not found" value. Someone pointed out that find() in str was a contradiction to this since it doesn't throw an exception but returns a "not found" value, and the response was that it was believed that find() would be removed from the language (if so, it does not currently show up on the "removed list" as has_key() and a few others do - http://docs.python.org/dev/3.0/whatsnew/3.0.html) and was only there for "historical reasons". I don't believe the poster was trying to illustrate a point already mentioned in the thread, but to give a contradiction to statements in the thread. He was asking the question - why doesn't dict.get() throw an exception on not found if that is the Pythonic way? From blackmh at gmail.com Wed Sep 5 04:07:44 2007 From: blackmh at gmail.com (Kveldulv) Date: Wed, 05 Sep 2007 08:07:44 -0000 Subject: Catching gtk.STOCK_SIGNALS Message-ID: <1188979664.773081.156720@57g2000hsv.googlegroups.com> Hi all, I made simple GUI with Glade, window and toolbar with one button that calls dialog with stock yes or no buttons. It's loaded with: def callDialog(self, widget): self.wTree = gtk.glade.XML(self.gladefile, "yesorno") self.dlg = self.wTree.get_widget("yesorno") and it works. Now, I want to call other dialog named dlg1 if gtk.RESPONSE_YES, how do I do that? I went through pygtk tutoral and tried various ways but can't figure it out... I'm probably missing something trivial here. tia From ldo at geek-central.gen.new_zealand Sat Sep 8 22:41:04 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 09 Sep 2007 14:41:04 +1200 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> Message-ID: In message <13drijhfqlvlk96 at corp.supernews.com>, Steven D'Aprano wrote: > Any cryptographer worth his salt (pun intended) would be looking to close > that vulnerability BEFORE an attack is made public, and not just wait for > the attack to trickle down from the NSA to the script kiddies. Except that the NSA's reputation has taken a dent since they failed to anticipate the attacks on MD5 and SHA-1. From pavlovevidence at gmail.com Fri Sep 21 23:44:00 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 21 Sep 2007 23:44:00 -0400 Subject: Getting rid of bitwise operators in Python 3? Message-ID: <46f49740$0$32514$4c368faf@roadrunner.com> Anyone with me here? (I know the deadline for P3 PEPs has passed; this is just talk.) Not many people are bit-fiddling these days. One of the main uses of bit fields is flags, but that's not often done in Python because of keyword arguments and dicts, which are lot more versatile. Another major use, talking to hardware, is not something oft done in Python either. It seems like this occasional usage wouldn't justify having built-in operators on its own. And with the int/long unification, it makes a bit less sense to think of integers as a bit field. Python has these operators because of its heritage, but Python continues to move away from the bad habits of its ancestors (integer division and so on), and I wonder if this isn't another one. Of course I'm not suggesting to get rid of bitwise operations altogether; just make them builtin functions: "x & 1" becomes "bitwise_and(x,1)" and so on. Is it worth it to make such a change? It would remove a lot of operators (11 by my count), vastly simplifying syntax, Which, IMHO, is no small thing. New numerical types would have fewer operations to support. And let's face it: unlike arithmetic opertaions, there's not a lot of different meanings for bit operations. And it would also, um, make new special characters available *cough*. Obviously, how widespread their usage is would matter. But keep in mind it would also be easy to convert the code automatically, because the Python parser could reliably find all bitwise operations reliably. (The problem would be types that overloaded them to be something other than bitwise operations: I'm looking at you, set. That could very well be a deal breaker. I've never approved of things with completely different meanings being deliberately overloaded to have the same spelling; this is one reason why.) If anyone says, "But that takes away an easy test for oddness (x&1)!", or, "But you can multiply powers of two using left shift! Isn't that cool?", I'm not buying it. Those are gimmicks. Arithmetic operations should be done with arithmetic operators. The bitwise operators make the code much less readable, especially to people unfamiliar with this usage. the-above-pun-was-intended-ly yr's, Carl Banks From mensanator at aol.com Sun Sep 16 18:53:53 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 16 Sep 2007 15:53:53 -0700 Subject: Try this In-Reply-To: <1189981681.745195.18130@y42g2000hsy.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> Message-ID: <1189983233.709832.124290@19g2000hsx.googlegroups.com> On Sep 16, 5:28?pm, John Machin wrote: > On Sep 17, 7:54 am, "mensana... at aol.com" wrote: > > > > > > > On Sep 16, 2:22?pm, Steve Holden wrote: > > > > mensana... at aol.com wrote: > > > > On Sep 16, 1:10?pm, Dennis Lee Bieber wrote: > > > >> On Sun, 16 Sep 2007 01:46:34 -0700, GeorgeRXZ > > > >> declaimed the following in comp.lang.python: > > > > >>> Then Open the Notepad and type the following sentence, and save the > > > >>> file and close the notepad. Now reopen the file and you will find out > > > >>> that, Notepad is not able to save the following text line. > > > >>> Well you are speed > > > >>> This occurs not only with above sentence but any sentence that has > > > >>> 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) > > > >> I tried. I also opened the saved file in SciTE... > > > >> And the text WAS there... > > > > >> It is Notepad that can not properly render what it, > > > >> itself, saved. > > > > > C:\Documents and Settings\mensanator\My Documents>type huh.txt > > > > Well you are speed > > > > > Yes, file was saved correctly. > > > > But reopening it shows 9 unprintable characters. > > > > If I copy those to a new file (huh1.txt): > > > > > C:\Documents and Settings\mensanator\My Documents>type huh1.txt > > > > ????????? > > > > > But wait...the new file is 20 characters, not 9. > > > > > 09/16/2007 01:44 PM 18 huh.txt > > > > 09/16/2007 01:54 PM 20 huh1.txt > > > > > C:\Documents and Settings\mensanator\My Documents>dump huh.txt > > > > huh.txt: > > > > 00000000 5765 6c6c 2079 6f75 2061 7265 2073 7065 Well you are spe > > > > 00000010 6564 ed > > > > > Here's what it's actually doing: > > > > > C:\Documents and Settings\mensanator\My Documents>dump huh1.txt > > > > huh1.txt: > > > > 00000000 fffe 5765 6c6c 2079 6f75 2061 7265 2073 .~Well you are s > > > > 00000010 7065 6564 peed > > > > One word: Unicode. > > > > The "open" and "save" dialogs allow you to specify an encoding. > > > And the encoding specified was ANSI. > > > > If you > > > specify Unicode the you will get what you see above. > > > And if you specify ANSI _before_ you click the file name, > > the specification switches to Unicode and has to then > > be manually switched back to ANSI. > > > > If you specify ANSI > > > you will get the text you entered. > > > It's still a bug in the "open" dialog. > > It's more like a bug/feature in its encoding detector. It is NOT a feature. If I save something as ANSI, there is no excuse for it not to re-open in ANSI. > I can get it to > switch to Unicode only if there's an even number of characters AND the > line is NOT terminated by CRLF -- add/remove one alpha character, or > hit the enter key at the end of the line, and it won't detect it as > Unicode when you open it again. > > You only get the BOM (0xfffe) if you are silly enough to save it while > it's open in Unicode mode. That was a test. I wasn't so stupid as to save to the original file, but to make a copy. > > > > > > By the way, this has precisely what to do with Python? > > > I've been known to use Notepad to create Python > > source code. > > Your source code would have to be trivially short to trigger the > strange behaviour. Makes you wonder what other edge cases aren't handled properly. Makes you wonder why Microsoft doesn't employ professional programmers. From surekap at gmail.com Thu Sep 13 10:37:47 2007 From: surekap at gmail.com (Prateek) Date: Thu, 13 Sep 2007 07:37:47 -0700 Subject: Possible suggestion for removing the GIL In-Reply-To: <5ksb3mF5828oU1@mid.uni-berlin.de> References: <1189657576.772108.136550@d55g2000hsg.googlegroups.com> <5ksb3mF5828oU1@mid.uni-berlin.de> Message-ID: <1189694267.608577.288290@r34g2000hsd.googlegroups.com> On Sep 13, 1:36 pm, "Diez B. Roggisch" wrote: > Prateek wrote: > > Hi, > > > Recently there was some talk on removing the GIL and even the BDFL has > > written a blog post on it. > > I was trying to come up with a scalable and backwards compatible > > approach for how to do it. > > > I've put my thoughts up in a blog post - and I'd really like to hear > > what the community thinks of it. > > Mainly it revolves around dedicating one core for executing > > synchronized code and doing context switches instead of acquiring/ > > releasing locks. > > Where is the gain? Having just one core doesn't give you true parallelism - > which is the main reason behind the cries for a GIL-less Python. > > Diez Diez, I was talking of dedicating one core for synchronized code. In the case of a threaded app on two cores, one core would be dedicated to synchronized code and the other would run non-sync code (effectively behaving like a single threaded machine). However, on machines with n cores where n > 2 cores, we would have n-1 cores available to run code in parallel. Prateek From gherzig at fmed.uba.ar Thu Sep 20 17:01:38 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 20 Sep 2007 18:01:38 -0300 Subject: Python Regex Question In-Reply-To: <1190316811.760038.145850@50g2000hsm.googlegroups.com> References: <1190316811.760038.145850@50g2000hsm.googlegroups.com> Message-ID: <46F2DFB2.3040901@fmed.uba.ar> joemystery123 at gmail.com wrote: >I need to extract the number on each >i.e 49.950 from the following: > > 49.950  > >The actual number between:  49.950  can be any number of >digits before decimal and after decimal. > > ######.####  > >How can I just extract the real/integer number using regex? > > > If all the td's content has the  [value_to_extract]  pattern, things goes simplest [untested] / Message-ID: cesco wrote: > l = ['string1', 'string2', 'string3'] l2=[l[:i+1] for i in range(len(l))] From strombrg at gmail.com Sun Sep 30 18:02:34 2007 From: strombrg at gmail.com (Dan Stromberg) Date: Sun, 30 Sep 2007 22:02:34 GMT Subject: notify when process finishes (on unix) References: <1191161510.764656.244540@57g2000hsv.googlegroups.com> Message-ID: <_1VLi.1737$hI7.787@newssvr17.news.prodigy.net> On Sun, 30 Sep 2007 11:54:38 -0700, Michael Bentley wrote: > On Sep 30, 2007, at 7:11 AM, bahoo wrote: >> I'd like to write a script that sends me an email when a unix (Linux) >> process ends running (or CPU drops below some threshold). Could anyone >> point me to the relevant functions, or show me an example? > > man at. http://stromberg.dnsalias.org/~strombrg/notify-when-up2.html From gagsl-py2 at yahoo.com.ar Tue Sep 4 15:13:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Sep 2007 16:13:17 -0300 Subject: Undeterministic strxfrm? References: Message-ID: En Tue, 04 Sep 2007 07:34:54 -0300, Tuomas escribi?: > Python 2.4.3 (#3, Jun 4 2006, 09:19:30) > [GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import locale > >>> def key(s): > ... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8') > ... return locale.strxfrm(s.encode('utf8')) > ... > >>> first=key(u'maupassant guy') > >>> first==key(u'maupassant guy') > False > >>> first > '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 > $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79' > >>> key(u'maupassant guy') > '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 > $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5' > >>> > > May be this is enough for a sort order but I need to be able to catch > equals too. Any hints/explanations? I can't use your same locale, but with my own locale settings, I get consistent results: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> import locale py> locale.setlocale(locale.LC_COLLATE, 'Spanish_Argentina') 'Spanish_Argentina.1252' py> def key(s): ... return locale.strxfrm(s.encode('utf8')) ... py> first=key(u'maupassant guy') py> print repr(first) '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02 \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01' py> print repr(key(u'maupassant guy')) '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02 \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01' py> print first==key(u'maupassant guy') True Same thing with Python 2.4.4 -- Gabriel Genellina From fakeaddress at nowhere.org Sat Sep 15 07:56:32 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 15 Sep 2007 04:56:32 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: References: <13ec37dri08s7a3@corp.supernews.com> Message-ID: J. Cliff Dyer wrote: > Bryan Olson wrote: >> Scott David Daniels wrote: >> >>> C, which was designed as a "high level assembly language," does not >>> tightly define the results of / and % for negative numbers. Instead >>> it defines the result for positive over positive, and constrains the >>> result for the others. >>> >> Not true. Here it is again: >> >> When integers are divided, the result of the / operator is >> the algebraic quotient with any fractional part discarded.(87) >> If the quotient a/b is representable, the expression >> (a/b)*b + a%b shall equal a. >> [...] >> 87) This is often called ??truncation toward zero??. >> >> [International Standard ISO/IEC 9899:1999, Section 6.5.5 >> Multiplicative operators, Paragraph 6 and footnote 87] >> > But C was around for a long time before the 1999 standard. C89, > commonly called ANSI C, is still very commonly used in compilers, and > K&R C goes back to 1972. Is truncation toward 0 the standard for K&R C > as well? Looks like you have a good point there. I do not have a copy of the C89 standard, but do I have editions of Harbison&Steele that reflect the 1989 standard, and they confirm your suspicion that the results of the '/' and '%' operators on integer operants were not uniquely defined in cases where an operand could be negative. Describing the '/' operator: For integral operands,, if the mathematical quotient is is not an exact integer, then the result will be one of the integers closest to the mathematical quotient of the operands. Of those two integers, the one closer to 0 must be chosen if both operands are positive Furthermore: It is always true that (a/b)*b + a%b is equal to a if b is not 0 Quoted from: S. P. Harbison and G. L. Steele. /C: A Reference Manual, Third Edition/, Prentice Hall, 1991; Section 7.6.1, page 187. So Arnau Sanchez and Scott David Daniels were correct with respect to C89 and older standards, and many implementations have not yet adopted the 1999 standard that strictly defines the results of / and %. -- --Bryan From gherzig at fmed.uba.ar Thu Sep 6 16:25:40 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 06 Sep 2007 17:25:40 -0300 Subject: parsing long `To' and 'Cc' from email Message-ID: <46E06244.80308@fmed.uba.ar> Hi all. Im trying to develop yet another email filter. Just for fun for now. Im having a little trouble parsing long 'To' and 'Cc' headers. Sometimes p.e. the 'To' header comes like 'account1 at site.com, account at site2.com' others comes like '"My self" , "My brother" ', other times a \r\t comes inside the `To' header. And any combination of the above mentioned (and shurely more) can ocur. the email.* package dont seems to parse that kind of headers `correctly'. What i want is to get a list with all the email address in the `To' header. Someone know if there is a more sofisticated parser for doing this? Thanks! Gerardo From mbratcher at cclpcitrus.com Fri Sep 28 11:56:18 2007 From: mbratcher at cclpcitrus.com (Mark Bratcher) Date: Fri, 28 Sep 2007 11:56:18 -0400 Subject: Emailing the attachment created with the Quick Screenshots Script(Python + PIL) Message-ID: <000001c801e8$1eb8ff20$eafca8c0@tfccorp.intra> The quick screenshots script works great for the project I'm working on and I'm trying to modify it to include emailing the JPG file it generates. I retrieved both scripts from the Python Archives. The modified script is pasted below and the errors below that. My goal is to have the latest date stamped file emailed to me. If someone can see where I've gone wrong, it would be greatly appreciated. """ Simple script to capture your screen, save it named with today's date and then open it to allow editing and markup (circle problems, etc) Created by Greg Pinero (gregpinero at gmail.com) Spring 2005 To run this you'll need: >Python Imaging Library (PIL) -http://www.pythonware.com/products/pil/ >Python 2.3 or later - http://www.python.org >Windows? """ import os import sys import time import Image import ImageGrab #--------------------------------------------------------- #User Settings: SaveDirectory=r'C:\Downloads\Python\Attachments' ImageEditorPath=r'C:\WINDOWS\system32\mspaint.exe' #Here is another example: #ImageEditorPath=r'C:\Program Files\IrfanView\i_view32.exe' #--------------------------------------------------------- img=ImageGrab.grab() saveas=os.path.join(SaveDirectory,'ScreenShot_'+time.strftime('%Y_%m_%d%_%H_ %M_%S')+'.jpg') img.save(saveas) editorstring='"start"%s" "%s"'% (ImageEditorPath,saveas) #Just for Windows right now? #Notice the first leading " above? This is the bug in python that no one will admit... os.system(editorstring) # Import smtplib for the actual sending function import smtplib # Here are the email package modules we'll need from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart COMMASPACE = ', ' # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'TEST' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = ("Mark Bratcher") msg['To'] = COMMASPACE.join("Mark Bratcher") msg.preamble = 'TEST' # Assume we know that the image files are all in JPG format for file in "c:\downloads\python\Attachments\*.jpg": # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. fp = open(file, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP() s.connect() s.sendmail(me, family, msg.as_string()) s.close() The errors I'm receiving in the Python Shell are: >>> Traceback (most recent call last): File "C:\Downloads\Python\screenshooter.pyw", line 54, in fp = open('C:\Downloads\Python\Attachments\*.jpg', 'rb') IOError: [Errno 2] No such file or directory: 'C:\\Downloads\\Python\\Attachments\\*.jpg' >>> Traceback (most recent call last): File "C:\Downloads\Python\screenshooter.pyw", line 54, in fp = open('\Downloads\Python\Attachments\*.jpg', 'rb') IOError: [Errno 2] No such file or directory: '\\Downloads\\Python\\Attachments\\*.jpg' >>> Traceback (most recent call last): File "C:\Downloads\Python\screenshooter.pyw", line 54, in fp = open('*.jpg', 'rb') IOError: [Errno 2] No such file or directory: '*.jpg' >>> Traceback (most recent call last): File "C:\Downloads\Python\screenshooter.pyw", line 51, in for file in jpgfiles: NameError: name 'jpgfiles' is not defined >>> Traceback (most recent call last): File "C:\Downloads\Python\screenshooter.pyw", line 54, in fp = open(file, 'rb') IOError: [Errno 2] No such file or directory: 'c' >>> Traceback (most recent call last): File "C:\Downloads\Python\screenshooter.pyw", line 54, in fp = open(file, 'rb') IOError: [Errno 2] No such file or directory: 'c' >>> Traceback (most recent call last): File "C:\Downloads\Python\screenshooter.pyw", line 54, in fp = open(file, 'rb') IOError: [Errno 2] No such file or directory: 'c' Mark Bratcher Consolidated Citrus, LP 4210-250 Metro, Parkway Fort Myers, FL 33916 239-275-4060 ext 219 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kskuhlman at gmail.com Fri Sep 7 16:06:07 2007 From: kskuhlman at gmail.com (Ken Kuhlman) Date: Fri, 07 Sep 2007 20:06:07 -0000 Subject: Best way to do attribute docstrings? Message-ID: <1189195567.238990.54440@57g2000hsv.googlegroups.com> What's the best method for annotating attributes with a docstring? I'm looking to be able to introspect my class & get the comments back out. The technique I'm using is a little hoaky, but works.. basically I create subclasses of the builtin types that I want to be able to use & then instantiate them in my attribute assignments. This gives me an object that I can tweak the __doc__ attribute on. An example of what my code looks like is included below. I saw that PEP 224 [1] was trying to meet this need, but got rejected because the proposed syntax wasn't clear enough. Thanks! -Ken [1] http://www.python.org/dev/peps/pep-0224/ attr_doc.py:: # Subclass str so we can modify instance's attributes (like __doc__) class _(str): pass # Boolean gave me extra fits that I don't understand, but this technique works class MyBool(int): def __str__(self): return `self.__int__() > 0` def __repr__(self): return self.__str__() def bool_func(val): def blah(): return MyBool(val) return blah true = bool_func(True) false = bool_func(False) class Animal(object): four_legs = true() four_legs.__doc__ = "Animal has four legs" favorite_food = _('cheese') favorite_food.__doc__ = "Animal's favorite food" has_fur = true() has_fur.__doc__ = "Animal has fur" print Animal.four_legs.__doc__, '::', Animal.four_legs print Animal.favorite_food.__doc__, '::', Animal.favorite_food print Animal.has_fur.__doc__, '::', Animal.has_fur ------ This gives the expected results: Animal has four legs :: True Animal's favorite food :: cheese Animal has fur :: True From aboudouvas at panafonet.gr Mon Sep 3 06:19:52 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 03 Sep 2007 03:19:52 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <87tzqc9jda.fsf@benfinney.id.au> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1188803759.498517.198900@g4g2000hsf.googlegroups.com> <87tzqc9jda.fsf@benfinney.id.au> Message-ID: <1188814792.025874.191320@d55g2000hsg.googlegroups.com> I was wondering (and maybe i still do) about this GIL "problem". I am relatively new to Python (less than a year) and when i started to think about it i said: "Oh, this IS a problem". But when i dig a little more, i found that "Ah, maybe it isn't". I strongly believe that the best usage of multiple cores processor will be achieved if programming languages are modified to support this on their "hearts". Code blocks that would be identified by the compiler and run in parallel and such things. Laboratories are working on these stuff but i do not expect something in the very-near future. So, as i mentioned above, there are solutions for that right now ("parallel python" and others) that enabled us with little effort to spawn a new python interpreter, thus allowing the OS to schedule it on a different core and do the job this way relatively cheap. I wouldn't recommend going to IronPython despite the fact that the CLR better utilize MP. The reason for this is that i would NEVER give up the freedom that CPython gives me by exchange "better" usage of the MP and platform lock-in. From w.greg.phillips at gmail.com Wed Sep 12 18:43:41 2007 From: w.greg.phillips at gmail.com (w.greg.phillips at gmail.com) Date: Wed, 12 Sep 2007 15:43:41 -0700 Subject: Generating HTML In-Reply-To: References: <9e2f512b0709112133l41ce5ef1g815962a81becf6b9@mail.gmail.com> <46e79b40$0$28082$426a74cc@news.free.fr> Message-ID: <1189637021.632184.33790@g4g2000hsf.googlegroups.com> On Sep 12, 1:16 pm, Evan Klitzke wrote: > Can you compile Mako templates? This is one thing that I really like > about Cheetah, and it wasn't clear to me from the Mako site if this is > possible. First line of the Mako home page: """Mako is a template library written in Python. It provides a familiar, non-XML syntax which compiles into Python modules for maximum performance.""" Greg From carsten at uniqsys.com Fri Sep 7 15:00:10 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 07 Sep 2007 15:00:10 -0400 Subject: Is a Borg rebellion possible? (a metaclass question) In-Reply-To: <1189180478.257790.60160@g4g2000hsf.googlegroups.com> References: <1189168282.665210.260840@19g2000hsx.googlegroups.com> <1189180478.257790.60160@g4g2000hsf.googlegroups.com> Message-ID: <1189191610.3367.93.camel@dot.uniqsys.com> On Fri, 2007-09-07 at 15:54 +0000, Andr? wrote: > Unfortunately, it fails. Here's what I tried, followed by the > traceback > class SplinterBorg(object): > _shared_states = {} > def __new__(cls, *a, **k): > group = k.pop("group","BORG") > obj = object.__new__(cls, *a, **k) > obj.__dict__ = cls._shared_states.setdefault(group,{}) > return obj > > class MyClass(SplinterBorg): > def __init__(self, name): > self.name = name >[...] > Traceback (most recent call last): > File "test.py", line 15, in > b1 = MyClass('b', group="B") > TypeError: __init__() got an unexpected keyword argument 'group' Indeed, if you have an __init__ method that shouldn't see the "group" argument, you need a metaclass after all so you can yank the "group" argument between __new__ and __init__. The following code seems to work, but it's making my brain hurt: class SplinterBorgMeta(type): def __call__(cls, *args, **kwargs): inst = cls.__new__(cls, *args, **kwargs) kwargs.pop("group",None) inst.__init__(*args,**kwargs) return inst class SplinterBorg(object): __metaclass__ = SplinterBorgMeta _shared_states = {} def __new__(cls, *a, **k): group = k.pop("group","BORG") obj = object.__new__(cls, *a, **k) obj.__dict__ = cls._shared_states.setdefault(group,{}) return obj class MyClass(SplinterBorg): def __init__(self, name): self.name = name The alternatives, as Steve just pointed out, would be not to subclass SplinterBorg or to provide an __init__ method that expects a "group" argument. HTH, -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Mon Sep 3 02:38:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Sep 2007 03:38:35 -0300 Subject: advice about `correct' use of decorator References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> <46C5C9AE.5020508@fmed.uba.ar> <1187792001.935204.42330@e9g2000prf.googlegroups.com> <740c3aec0708230520h6a92a29ar180efed41730f563@mail.gmail.com> <740c3aec0708290332k3c125d9el16250939e22ea8c4@mail.gmail.com> Message-ID: En Wed, 29 Aug 2007 07:32:21 -0300, BJ?rn Lindqvist escribi?: > On 8/24/07, Gabriel Genellina wrote: >> En Thu, 23 Aug 2007 09:20:21 -0300, BJ?rn Lindqvist >> escribi?: >> >> > def check_user_logged_in(func): >> > def f(*args, **kwargs): >> > if global_state.the_user.is_logged_in: >> > return func(*args, **kwargs) >> > return show_login_page() >> > return f >> >> I think there is a semantic problem, perhaps we are not talking >> about the same thing. I'm considering the software complexity AS >> PERCEIVED BY THE PROGRAMMER, looking at the interactions between a >> program and a programmer who is working on some task; some people >> would say "cognitive complexity" to make it clear. > > There is no semantic problem. You are just mistaken in your belief > that the complexity that the user of the decorator has to deal with is > different from the complexity in implementing the decorator. But they ARE different. That's the whole point of abstractions, code reuse, layered design... Designing a simple interfase on top of a complex system is very common. Nobody writes X-Window code, as nobody writes a raw event loop for Windows anymore: there are very good GUI toolkits, even portable frameworks, that put an abstract layer on top of that so the programmer has a much simple and coherent view. The complexity is behind the scenes. >> Which API is more complex: one in which you can play a movie with >> just a single call like PlayMovie(Title), or one on which you must >> call a zillion functions to firtly initialize the stream format, >> configure the display, disable undesired user interfase elements, >> locate the movie file, load it in chunks, etc.? The first one is >> certainly much simpler to use (simpler = less complex), and maybe >> internally it calls the same functions as the second one, but nobody >> cares. > > "nobody cares" is your guess. I'd bet that the caller of the PlayMovie > function cares a lot: Is the movie played full screened? Which > encodings are supported? Can you set the title of the movie window? Is > streaming supported? Does it even work on windows? Which URI schemes > does it support? And so on and so on. > > That is why no video decoding API:s have a PlayMovie(Title) function > and why I haven't seen a single 3d engine with a > MakeReallyCoolDoomCloneFPSGame() function. (yet!). What about urlopen? Using a single call one can be authenticated and retrieve any file in the other side of the planet. I consider it a simple interfase, altough it does complex things. Would you say it is better to use plain sockets everywhere? Or, since sockets are abstractions themselves, would you say it is better to use lower level primitives instead? Each time you descend a level, you have to use many simpler functions - but their combination is more complex. > "hiding details" only works if the client programmer really doesn't > care about the details. Why should he care? Isn't "hiding implementation details" a good design principle? When I use urlopen, I don't even care of the underlying socket implementation. I don't care which interfase the request is sent thru. I don't care if the answer got fragmented and some packets had to be reassembled. urlopen gives me something that looks like a file, and I just read() from it. >> Back to your example, the fact that a decorator builds a higher order >> function, does NOT make it more complex - because the programmer does >> not >> see that. In fact, hiding the details makes it simpler. > > Yes, the programmer does see that. The example decorator I posted > requires about a zillion preconditions to work correctly and will fail > in weird ways when those preconditions are not satisfied. The > programmer is interested in the crazy failures he or she will > experience. I dare you to try and implementing the code both as a > decorator and as a function, then write the unit tests and > documentation. The complexity of those three items together > (implementation + tests + documentation) will be much higher for the > decorator choice because the complexity of the decorator > implementation is a bit higher than using a plain old function. Testing the decorator is as hard as testing any other function. Testing the decorated functions might involve *only* checking if the decorator is actually used for those functions. Going to your posted example, I don't see the difference - I should say, I don't see the advantage. Using a decorator hides some implementation details and reduces coupling between modules, both good things on "my" book; your function with no decorator does quite the opposite, and doesn't look like good coding style (on "my" book, of course). > Note also that it is extremely rare to see well-documented or > well-tested code, which means that the programmer WILL have to analyze > the implementation which means that implementation complexity matters > a lot. In any case, that would require testing and analyzing ONE function (the decorator) instead of inspecting a zillion repetitions of the same code that, when being wrong, have to be located and fixed on all those places. Really, I still can't understand how you can defend such silly things - unless we are talking about different things. -- Gabriel Genellina From rschroev_nospam_ml at fastmail.fm Mon Sep 17 04:10:40 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 17 Sep 2007 08:10:40 GMT Subject: Try this In-Reply-To: References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> Message-ID: <4EqHi.109510$aG7.5661996@phobos.telenet-ops.be> BJ?rn Lindqvist schreef: > On 9/16/07, GeorgeRXZ wrote: >> Well you are speed > > That's an awesome party trick! But before I mail this to everyone at > the office, must have a better sentence. Well you are speed is to > gibberish. Something microsoft+evil... hm.. "This app can break" is the sentence used when I first heard about this bug. Perhaps not evil enough, but it does sound more sensible. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From devondejohn at comcast.net Mon Sep 3 15:57:56 2007 From: devondejohn at comcast.net (devondejohn at comcast.net) Date: Mon, 03 Sep 2007 12:57:56 -0700 Subject: Let's Unite Against Jews and Mongrels! In-Reply-To: <46DAD433.1030503@comcast.net> References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> <1188300284.507909.126770@57g2000hsv.googlegroups.com> <46D40BFE.2020301@comcast.net> <1188744204.822322.198360@57g2000hsv.googlegroups.com> <46DAD433.1030503@comcast.net> Message-ID: <1188849476.067121.119110@r34g2000hsd.googlegroups.com> On Sep 2, 9:18 am, "Richard B. Gilbert" wrote: > Zentrader wrote: > > On Aug 28, 4:50 am, "Richard B. Gilbert" > > wrote: > > >>>Unless, of course, someone has a working "Killbot". If anyone has such > > >>a thing, please kill that "MI5victim" moron as well! > > > I reported MI5victim to s... at uce.gov and it appears to be gone, as > > well as the "free air conditioner"'s posts. (Thanks Steve Holden for > > the reminder that it doesn't have to be personal e-mail spam in order > > to be reported). If the OP posts again, report it. Something like 75% > > of internet mail is spam. > > MI5victim was alive and (I won't say well!!) a week ago. It remains to > be seen if he's gone. And if you believe that reporting spam to > s... at uce.gov actually has any effect on spam, you must believe in the > Tooth Fairy as well! > > There will be spam as long as there are morons who will send the > spammers money for whatever they're peddling! I still get two or three > "Spanish Prisoner" a/k/a "401" scams each week (this is the one where > somebody has $30,000,000 US and will share it with you if only you will > send him a little of your money)! The US government does seem to have > cracked down on the "Pharmacy" spam and the internet "pharmacies" that > were behind it. > > Remember, it costs essentially nothing to send spam to 30,000,000 people > and if the spammer gets 0.5% response, he's ahead of the game! HEY! NOBODY BASHES THE TOOTH FAIRY! From jon+usenet at unequivocal.co.uk Fri Sep 14 06:32:24 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 14 Sep 2007 10:32:24 GMT Subject: smtp debugging methods References: Message-ID: On 2007-09-14, Sean Nakasone wrote: > I'm having trouble with sending smtp mail. It's hanging after the > smtplib.SMTP() line. It doesn't works from home but not from work. What's > the best way to debug this? > > # Here's the error >>>> server = smtplib.SMTP("smtp.gmail.com",465) smtp.gmail.com port 465 is SSL only. Try port 587 instead. From grante at visi.com Sat Sep 1 00:24:22 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 01 Sep 2007 04:24:22 -0000 Subject: Looking for Delaunay triangulation module... References: <13dge9m2339ka68@corp.supernews.com> Message-ID: <13dhqbm42tr1i7b@corp.supernews.com> On 2007-09-01, Lawrence D'Oliveiro wrote: > In message <13dge9m2339ka68 at corp.supernews.com>, Grant Edwards wrote: > >> So for lack of a delaunay module, I'm stuck trying to port my >> application to Win32. > > Why not run it under Cygwin? :) :) I'm hoping there is an easier way than trying to build a half-dozen large Python extensions (and their supporting libraries) under Cygwin. It looks like VTK might do the trick. I can do the triangulation, I just can't figure out how to get the data out of the object containing the results. VTK isn't very Python-friendly at all. -- Grant Edwards grante Yow! LOOK!!! I'm WALKING at in my SLEEP again!! visi.com From thomas.david.vaughan at gmail.com Tue Sep 11 19:50:07 2007 From: thomas.david.vaughan at gmail.com (tvaughan) Date: Tue, 11 Sep 2007 23:50:07 -0000 Subject: __getattr__ and static vs. instantiated Message-ID: <1189554607.559487.224410@b32g2000prf.googlegroups.com> Hi, Let's say I have: class Persistable(object): __attrs__ = {} def __getattr__(self, name): if name in self.__attrs__: return self.__attrs__[name]['value'] else: return Object.__getattr__(self, name) def __setattr__(self, name, value): if name in self.__attrs__: self.__attrs__[name]['value'] = value else: Object.__setattr__(self, name, value) And the I have: class Person(Persistable): __storm_table__ = 'person' id = Int(primary=True) __attrs__ = { 'name': { 'lang': 'en', 'value': Unicode(), }, } def __init__(self): self.id = int(random.random() * 1000) I can do this: person = Person() person.name = 'Jane Smith' But I cannot do: Person.name = 'Jane Smith' or use Person.name in a Storm query like: Person.name == 'Jane Smith' __getattr__ is only called when using an instantiated class, and never, it seems, in a static case. Why? How do I work around this? Thanks. -Tom P.S. This is Python 2.5 on Ubuntu Feisty x86. From ivonet at gmail.com Fri Sep 21 16:04:12 2007 From: ivonet at gmail.com (Ivo) Date: Fri, 21 Sep 2007 22:04:12 +0200 Subject: Resolving windows shortcut to url In-Reply-To: References: Message-ID: <46f422d8$0$3030$e4fe514c@dreader31.news.xs4all.nl> Richard Townsend wrote: > If I have a windows shortcut to a URL, is there a way to get the URL > in a Python app? > > I found some code that uses pythoncom to resolve shortcuts to local > files, but I haven't found any examples for URLs. > > The PyWin32 help mentions the PyIUniformResourceLocator Object, but I > couldn't find an example of how to use it. > do you mean a *.lnk file or a *.url file? From madzientist at gmail.com Tue Sep 11 13:18:43 2007 From: madzientist at gmail.com (madzientist) Date: Tue, 11 Sep 2007 10:18:43 -0700 Subject: Python code-writing for the blind. Was (Re: newbie: stani's python editor if-else) In-Reply-To: <46e6aa30$0$22433$426a74cc@news.free.fr> References: <1189484688.520933.25000@22g2000hsm.googlegroups.com> <46e6aa30$0$22433$426a74cc@news.free.fr> Message-ID: <1189531123.283413.160870@22g2000hsm.googlegroups.com> Thanks, everybody, for the very very useful and kind responses. There is a second reason why I asked the question about automatic de- indenting. I am teaching myself Python partly so I can then help my technically astute, but blind friend learn programming. For the many reasons that Pythonistas like to cite often, I thought Python would be a good choice to learn programming, and that perhaps the indentation problem would be solved by the use of an intelligent editor. But now I am not so sure, though I will try Emacs. Is there anyone here with experience in such issues ? Maybe for her sake, I should switch to learning Perl ;) ;) More seriously, the added issue is that SPE uses spaces, not a single tab to indent the lines, and I believe it is extremely tedious to use screen-readers to keep track of blank spaces at the beginning of each line. I have not tried it myself yet, but I will soon. Is Python a bad choice for the blind programmer, as a result of a tight linkage between visual aspects of the code and its function ? I wish the site blindprogramming.com weren't so lifeless... Thanks, Suresh From uymqlp502 at sneakemail.com Sun Sep 2 01:05:35 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Sat, 01 Sep 2007 22:05:35 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> Message-ID: <1188709535.459572.22130@r34g2000hsd.googlegroups.com> On Sep 1, 4:25 am, Bryan Olson > Design-by-contract (or programming-by-contract) shines in large > and complex projects, though it is not a radical new idea in > software engineering. We pretty much generally agree that we want > strong interfaces to encapsulate implementation complexity. > That's what design-by-contract is really about. > > There is no strong case for adding new features to Python > specifically for design-by-contract. The language is flexible > enough to support optionally-executed pre-condition and > post-condition checks, without any extension. The good and bad > features of Python for realizing reliable abstraction are set > and unlikely to change. Python's consistency and flexibility > are laudable, while duck-typing is a convenience that will > always make it less reliable than more type-strict languages. Excellent points. As for "no strong case for adding new features to Python specifically for design-by-contract," if you mean adding something to language itself, I agree, but I see nothing wrong with adding it to the standard libraries, if that is possible without changing the language itself. Someone please correct me if I am wrong, but I think PEP adds only to the libraries. From ldo at geek-central.gen.new_zealand Sat Sep 22 03:03:24 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 22 Sep 2007 19:03:24 +1200 Subject: Writing Object Data to Disk References: Message-ID: In message , Amit Kumar Saha wrote: > I would like to know if "Pickling" the class object is the only way of > writing it to disk for persistent storage. Wouldn't it be better to use a language-independent data representation that wasn't tied to Python? Also tying your external data representation to your internal program structure (objects) makes it harder to change the program in future. From Caseyweb at gmail.com Thu Sep 27 17:55:34 2007 From: Caseyweb at gmail.com (Casey) Date: Thu, 27 Sep 2007 21:55:34 -0000 Subject: getopt with negative numbers? In-Reply-To: References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <1190915197.390247.313590@57g2000hsv.googlegroups.com> Message-ID: <1190930134.780005.68510@22g2000hsm.googlegroups.com> On Sep 27, 2:21 pm, "J. Clifford Dyer" wrote: > If you can access the argument list manually, you could scan it for a negative integer, and then insert a '--' argument before that, > if needed, before passing it to getopt/optparse. Then you wouldn't have to worry about it on the command line. > > Cheers, > Cliff Brilliant! # Look for the first negative number (if any) for i,arg in enumerate(sys.argv[1:]): # stop if if arg[0] != "-": break # if a valid number is found insert a "--" string before it which # explicitly flags to getopt the end of options try: f = float(arg) sys.argv.insert(i+1,"--") break; except ValueError: pass From bj_666 at gmx.net Fri Sep 14 08:04:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Sep 2007 12:04:51 GMT Subject: recursion References: Message-ID: <5kvbn3F5h7l3U1@mid.uni-berlin.de> On Fri, 14 Sep 2007 13:40:17 +0200, Gigs_ wrote: > sorry i think that i express wrong. having problem with english > > > what i mean is how python knows to add all thing at the end of recursion Because you have written code that tells Python to do so. ;-) > >>> def f(l): > if l == []: > return [] > else: > return f(l[1:]) + l[:1] > > > f([1,2,3]) > > recursion1 f([2,3]) + [1] > > recursion2 f([3]) + [2] or [2, 1]? > > recursion3 f([]) + [3] or [3, 2, 1] Both alternatives in recursion 2 and 3 are wrong. You have to simply replace the function invocation by its result which gives: f([1, 2, 3]) r1 f([2, 3]) + [1] r2 f([3]) + [2] + [1] r3 f([]) + [3] + [2] + [1] r4 [] + [3] + [2] + [1] And now the calls return: r3 [3] + [2] + [1] r2 [3, 2] + [1] r1 [3, 2, 1] > i dont get all this > > >>> def f(l): > if l == []: > print l > return [] > else: > return f(l[1:]) + l[:1] > > >>> f([1,2,3]) > [] > [3, 2, 1] # how this come here? how python save variables from each > recursion? There is not just one `l` but one distinct `l` in each call. Ciao, Marc 'BlackJack' Rintsch From super.sgt.pepper at gmail.com Fri Sep 21 18:07:55 2007 From: super.sgt.pepper at gmail.com (Cristian) Date: Fri, 21 Sep 2007 22:07:55 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190411282.060772.289270@y42g2000hsy.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> Message-ID: <1190412475.772358.109810@n39g2000hsh.googlegroups.com> On Sep 21, 2:48 pm, chris.monsa... at gmail.com wrote: > There are already anonymous functions in Python. > > lambda x, y, z: x + y + z > > is the same as: > > def _(x, y, z): return x + y + z > > As for the method stuff, check out staticmethod(). If you assign > staticmethod() to an object, it will be treated as a > normal function and not as a "method." > > I have my own personal opinions about how methods should be in Python, > but, whatever. It's weird to deal with stuff like this: > > x.y = re.match # Assign a function to an attribute of a class, but it > doesn't work because you can't assign anything but methods! > x.y = staticmethod(re.match) # Ugly True, there is lambda, but that is very limited. It might be useful for key arguments, but not much else. It doesn't solve the teaching problem of "See, functions are just like any other data type. You can assign it to a variable." It would be a footnote if it's mentioned at all. My hope is to subtly reinforce the notion that functions are data and can be passed around. The current function declaration doesn't help with this. Creating a function and assigning it to a name is exactly what Python does, why not have it come out in the syntax? It's not necessary, yes, but I think it would be helpful for teaching purposes. Again, it's not necessary as much as it's more intuitive and obvious what's going on. This helps a beginner sort out the process from the syntax without taking it on faith. They can see the class declaration and see "I'm defining just another attribute to this class only this time it happens to be method". There is nothing functionally lacking in Python. I'm just curious if there's anything Python can do syntax-wise to help a person better grasp programming ideas and Python's inner workings. From json.barnes at gmail.com Tue Sep 25 23:25:46 2007 From: json.barnes at gmail.com (Jason M Barnes) Date: Tue, 25 Sep 2007 23:25:46 -0400 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: <833263a00709252025n47b1ed28pacfc0371a6792d11@mail.gmail.com> Warning: Religion follows: On 9/25/07, Lawrence D'Oliveiro wrote: > In message , A.T.Hofkamp wrote: > > > On 2007-09-25, Lawrence D'Oliveiro > > wrote: > > > >> Why does it "choose" to modify your position when you exit insert mode? > > > > Try to insert 1 character in the middle of a line. You'll end up at the > > same position. Now press 'j' (one line down), then '.' (do it again). > > I believe that's why. > > > > Great when you have nicely formatted columns of code underneath each > > other. > > It's strange, but in nearly 30 years of writing code in dozens of different > languages, I've never felt the urge to line up my code in columns. Never. > (Apart from assembly language, which I suspect you don't want to hear > about.) > > > The cost of that power is a command/insert mode and a steep learning > > curve. > > That's another issue, that of ROI. Having learnt the vi/vim keystrokes, what > does that enable you to do? Use vi/vim, and that's it. Whereas I've found > other situations where subsets of Emacs keystrokes are recognized, such as > anything that uses GNU readline (including the Python console--see, this IS > relevant to Python after all), and pico/nano. These are all extra goodies > that are to be found on the way up the Emacs learning curve. Off the top of my head, I can think of a few vim commands that have come in handy. I can search through a webpage in Firefox by using the same '/' search command that vim has. The movement keys (h,j,k,l) are the same as in any paging program I've ever used. Not to mention that I learned regexes by learning 's/regex/replacement' first :-) > > > For example, ever wondered why you on earth you need CTL-C and CTL-V to > > copy/paste? Why not simply select with the mouse, then right-click to > > paste? > > Or better still, why not allow both? > > >> And the downside is that the largest single proportion of those commands > >> end up being variations on "enter insert mode". Because most of the > >> keystrokes you enter during an editing session are in fact text to be > >> input into the file, not commands to manipulate that text. So in a modal > >> editor, having to > > > > Depends on what you are doing. When entering new code, yes. When > > maintaining code, no (lots of small changes). > > Making lots of small changes is even worse--it means you're jumping into > insert mode for shorter times, more frequently. If you're making lots of small changes, then you shouldn't be jumping into insert mode at all, IMO. > > And that's when you discover something else: that how you delete text in > vi/vim differs, depending on whether it's something you just inserted while > currently in insert mode, or whether it was there from before you last > entered insert mode: in the former case, you use backspace to delete, in > the latter case, you can't use backspace, you have to use "X". What does > backspace do when not in insert mode? It just moves you through the text. > What does the forward-delete key do? In both modes, it actually deletes > text! Actually, vim always deletes the same way regardless of when it was inserted -- one of the many *improvements* over vi. That's my religion anyway ;-), but I thought this was a python mailing list ;-) Jason > > At least with Emacs, text is text--it doesn't matter when it was inserted, > it still behaves the same way. > -- > http://mail.python.org/mailman/listinfo/python-list > From wizzardx at gmail.com Sat Sep 8 15:26:14 2007 From: wizzardx at gmail.com (David) Date: Sat, 8 Sep 2007 21:26:14 +0200 Subject: Using struct timeval in python In-Reply-To: <1189273504.153216.60470@22g2000hsm.googlegroups.com> References: <1189273504.153216.60470@22g2000hsm.googlegroups.com> Message-ID: <18c1e6480709081226k4d1d10baxbec668462ada95a1@mail.gmail.com> On 9/8/07, sapsi wrote: > Hi, > I am using a library (pcapy) that returns a timeval object T= > (seconds,microseconds) where microseconds is always < 1e6. > Is there a Python class that can handle timeval structs? Specifically, > I wish to subtract two T (defined above) objects, taking into account > the large values of T[0] and T[1] (esp T[0])? > > At one point, I would have to step in, since T[0] rolls back to zero > (after some time). The Pythonic way would be to convert directly to a datetime (or perhaps timedelta) object as soon as you receive your (seconds, microseconds) tuple. Then you can subtract etc easily and interoperate nicely with the rest of the standard python library. But if you want to keep it in tuple format then you will probably need to roll your own. eg: subclass tuple and override the __sub__ method. Just make sure you handle negative values correctly (ie, what (seconds,microseconds) you should end up with when you subtract a later timval from an earlier timeval). Alternatively you could convert to and from datetime as you need to (perhaps subclassing and adding methods for easier conversion), but that would be more expensive. From bdesth.quelquechose at free.quelquepart.fr Sun Sep 9 10:53:58 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 09 Sep 2007 16:53:58 +0200 Subject: creating really big lists In-Reply-To: <1189531096.198401.76590@50g2000hsm.googlegroups.com> References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> <46e5b1b4$0$30530$426a74cc@news.free.fr> <1189531096.198401.76590@50g2000hsm.googlegroups.com> Message-ID: <46e6feb8$0$25583$426a34cc@news.free.fr> Dr Mephesto a ?crit : > On Sep 8, 8:06 pm, Bruno Desthuilliers > wrote: > >>Dr Mephesto a ?crit : >> >> >>>Hi! >> >>>I would like to create a pretty big list of lists; a list 3,000,000 >>>long, each entry containing 5 empty lists. My application will append >>>data each of the 5 sublists, so they will be of varying lengths (so no >>>arrays!). >> >>>Does anyone know the most efficient way to do this? >> >>Hem... Did you consider the fact that RAM is not an unlimited resource? >> >>Let's do some simple math (please someone correct me if I'm going off >>the road): if a Python (empty) list object required 256 bits (if I refer >>to some old post by GvR, it's probably more - 384 bytes at least. Some >>Python guru around ?), you'd need (1 + (3000000 * 5)) * 256 bits just to >>build this list of lists. Which would make something around 3 Gb. Not >>counting all other needed memory... >> >>FWIW, run the following code: >> >># eatallramthenswap.py >>d = {} >>for i in xrange(3000000): >> d[i] = ([], [], [], [], []) >> >>And monitor what happens with top... > > > Unused ram is wasted ram :) Indeed. But when your app eats all RAM and swap and brings the system down, users are usually a bit unhappy !-) > I tried using MySQL, and it was to slow. Possibly. > and I have 4gb anyway... *You* have 4gb. Yes, fine. But: 1/ please take time to re-read my post - the 3 gb is based on a very optimistic estimation (256 bits) of the size of an empty list. If you choose the (probably much closer to reality) estimate of 384 bits, then you need (1 + (3000000 * 5)) * 384, which makes =~ 5 gb. More than what *you* have. BTW, please remember that your OS and the Python interpreter are going to eat some of these 4 gb, and that you intend to actually *store* something - objects references - in these lists. Even if you do have a few shared references, this means that you'll have to have RAM space for *at least* 3000000 * 5 *more* Python objects (which make *1* object per list...). Which will *at minima* use about the same amount of RAM as the list of lists itself. Which take us to something like 10 gb... for *1* object per list. I of course suppose you plan to store much more than 1 object per list !-) 2/ now ask yourself how many users of your application will have enough RAM to run it... So IMVHO, the question is not how to build such a list in less than x minutes, but how to *not* build such a list. IOW, do you *really* need to store all that stuff in RAM ? From bignose+hates-spam at benfinney.id.au Tue Sep 4 02:50:11 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 04 Sep 2007 16:50:11 +1000 Subject: parameter list notation References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> Message-ID: <87y7fm9b6k.fsf@benfinney.id.au> TheFlyingDutchman writes: > In looking at some of the functions I see this prototype: > def create(self,*fields,**kw): > > I am not clear on what the * and the ** are for or what they > represent. It would seem, then, that you haven't followed the exercises in the Python tutorial very thoroughly. Please work your way through the whole tutorial, with the document and an interactive Python prompt side by side. Run each exercise, read the accompanying text, experiment until you understand what it does; then move onto the next, and so on. This will give you a grounding in the fundamentals of the language that will be of great assistance to you, and to us. -- \ "It's not what you pay a man, but what he costs you that | `\ counts." -- Will Rogers | _o__) | Ben Finney From emin.shopper at gmail.com Fri Sep 21 16:03:09 2007 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Fri, 21 Sep 2007 16:03:09 -0400 Subject: which python mode to use in emacs Message-ID: <32e43bb70709211303s9e14825v4fa3c75b3a4b9540@mail.gmail.com> Dear Experts, There seem to be multiple versions of python modes for emacs? Could someone point me to the mainterers of either the "official" one or the one that is being maintained most vigorously? I've tried both python.el and python-mode.el. Both seem to have various minor foibles which I'd be happy to help fix and improve but the EmacsWiki page about python mode seems to imply that one or both or no longer maintained or acceprting patches. Thanks, -Emin -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Sep 22 15:27:20 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Sep 2007 15:27:20 -0400 Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> <13f99fediasg3ae@corp.supernews.com> <46f4c171$0$26367$4c368faf@roadrunner.com> <13fa49vie86ii1d@corp.supernews.com> Message-ID: <46f57841$0$15333$4c368faf@roadrunner.com> On Sat, 22 Sep 2007 12:57:35 +0000, Grant Edwards wrote: > On 2007-09-22, Carl Banks wrote: >> Of course it would be. The reason I mention it is that automatic >> convertibility is a key factor in whether a change can make it into >> Python 3. > > It matters not whether fugly code is automatically generated or manually > generated. It's still hard to read and maintain. By my understanding, it really doesn't matter that much. The transition tool's purpose is to allow a subset of 2.x code to run on 3.x, so that developers don't have to maintain separate codebases to support both. The 3.x code that is produced isn't intended to be read or maintained. So no big deal if it's a little ugly. (But there's still tracebacks to read and regressions to debug, so I guess it can't be too ugly.) Carl Banks From munncha at gmail.com Sun Sep 23 15:10:03 2007 From: munncha at gmail.com (Kurtis Heimerl) Date: Sun, 23 Sep 2007 12:10:03 -0700 Subject: Preemption in python In-Reply-To: <1190572311.5703.4.camel@thinkpad> References: <9a4753250709221928s5768b15emecfd71a0f476cce@mail.gmail.com> <1190572311.5703.4.camel@thinkpad> Message-ID: <9a4753250709231210l701a2cccge014732c79a5fdf9@mail.gmail.com> I ran a brief program to just test the threading properties of my VM, it seems to be preempting that application. Are there any interesting locks in the gtk package that I might not be playing well with? The reader thread that only runs on a blocking call is at the end of my response. I'll explain a bit more. This thread is spawned, I also have the main thread running a gtk windowed gui. The gui has it's own threads to deal with button presses and such. The problem is that the gui never seems to let anyone else run. Only on button presses that cause blocking calls ( ossaudiodev.audio.read for instance) does the reader thread print anything. Likewise, this thread blocks the GUI thread. There's really just no preemption at all going on, and it's exceedingly strange. The GIL locking could be part of my problem. I'm not explicitly releasing any locks, I have not used the lock interface at all. That shouldn't cause the behavior I'm seeing though right? class ReaderThread( threading.Thread ): def __init__(self, dtn): self.dtn = dtn threading.Thread.__init__(self) def run(self): print("RUNNING") while(True): bundle = api.recv(self.dtn.handle, DTN_PAYLOAD_MEM, 10) if(bundle): print("RECEIVED BUNDLE") else: print("NO BUNDLE") Thanks for the help, I really appreciate it. I'm totally blocked on this without you folk's help. On 9/23/07, Evan Klitzke wrote: > > On Sat, 2007-09-22 at 19:28 -0700, Kurtis Heimerl wrote: > > Hi, I'm developing my first python application, a multi-threaded cell > > phone gadget on ubuntu 7.10. I've just split off my first thread, and > > I've noticed something extremely strange: There doesn't seem to be any > > preemption. There are currently two threads, one that pings a storage > > service to see if there are messages available, and the other that > > runs the gtk windows. If I do not explicitly yield either one, it runs > > forever. I'm assuming this is a setting somewhere, but that's a very > > strange default behavior. > > > > How do I get this to go about preempting these threads? Any advice > > would be helpful. Thanks! > > I'm far from an expert in threaded Python applications, but threading > ought to work out of the box. By default the Python interpreter will > switch threads every 100 bytecode instructions > (http://docs.python.org/api/threads.html). > > Note that if you are synchronizing around a lock, you may need to sleep > before trying to reacquire the the lock to completely exit the critical > section. A good overview of this (and the Python threading model) can be > found at http://linuxgazette.net/107/pai.html > > -- > Evan Klitzke > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bborcic at gmail.com Wed Sep 5 08:17:08 2007 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 05 Sep 2007 14:17:08 +0200 Subject: So what exactly is a complex number? In-Reply-To: <7xk5r7dm53.fsf@ruckus.brouhaha.com> References: <7xk5r7dm53.fsf@ruckus.brouhaha.com> Message-ID: <46de9e7d$1_7@news.bluewin.ch> Paul Rubin wrote: > Also, for > example, the derivative of a complex valued function means something > considerably stronger than the derivative of a real valued function. I vaguely remember (it has been decades) an amazingly beautiful russian doll system of four of five theorems, the first hypothesizing a function of a complex variable with a property that IIRC appeared somewhat weaker than differentiability, and the latter theorems not hypothesizing anything more, but pushing the consequence further to ever stronger properties. From deets at nospam.web.de Sat Sep 15 03:32:17 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 15 Sep 2007 09:32:17 +0200 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189833002.694934.284960@57g2000hsv.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> <1189753968.917636.310120@19g2000hsx.googlegroups.com> <1189800045.642278.313860@o80g2000hse.googlegroups.com> <1189833002.694934.284960@57g2000hsv.googlegroups.com> Message-ID: <5l1g4nF60aluU1@mid.uni-berlin.de> Mark Summerfield schrieb: > On 14 Sep, 21:23, James Stroud wrote: >> Mark Summerfield wrote: >>> I guess I'll have to rename my module (although unfortunately, my book >>> has just gone into production and I have a (simpler) example of what I >>> considered to be an ordered dict, so I will be adding to the >>> terminology confusion). That notwithstanding, given that it is a >>> sorteddict, how is the API? >> I must think the API good because I have been implementing, in parallel >> with this discussion, my own "OrderedDict" with a very similar API (this >> is part of a larger project where I recently found the need to have a >> well-implemented ordered dict). The only real omission I see is to allow >> instantiating a "sorted dict" with an optional cmp function--to allow >> the generalization of such features as case-independence, etc. > > I tend to create different orderings by munging the keys rather than > by having optional cmp functions (as you'll see in the sorteddict.py > docstring). I've now put sorteddict on PyPI (with docs & tests): > http://pypi.python.org/pypi/sorteddict The advantage of a passed cmp-function is that the context of usage hasn't to be aware of any change in semantics. Yet for better performance, the cmp-function might be a tad to slow, better use a key-function like for sorted/sort. Additionally, I'd change the parameter names of the keys()-method to start/end and make more clear if end is inclusive or not. The first/secondindex-names are pretty horrible IMHO, because the essentially enumerate parameters. Who wants to work with a method foo(arg1, arg2, arg3) ? :) Diez From mail at timgolden.me.uk Wed Sep 12 10:56:51 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 12 Sep 2007 15:56:51 +0100 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189608231.151112.147550@y42g2000hsy.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> Message-ID: <46E7FE33.60209@timgolden.me.uk> Charles Fox wrote: > Thanks guys -- yeah these two stategies (short s.varname; and explicit > rescoping, a=self.a etc) are more or less what I was using. That's > still kind of annoying though. > > The s.varname approach still makes numerical code much harder to read. > > I had a nasty bug with the boilerplate approach when forgetting to > reassign some of the variables back to members (self.a=a). And that's > a lot of boilerplate you need -- I thought the python way was to > minimize redundant code? (Ditching header files and curley brackets > was a main reason for me coming here). > > I see the argument for making self explicit -- what would be wrong > with just .a instead of self.a though? That's still explicit but much > easier to read. (I think I've seen that somewhere else, is it C#?) Charles, while you are quite right to air your ideas, do bear in mind that this issue has been thrashed out again and again on this group and in other forums. I hope you have at least read the FAQ: http://www.python.org/doc/faq/general/#why-must-self-be-used-explicitly-in-method-definitions-and-calls and PEP 3099: http://www.python.org/dev/peps/pep-3099/ If you take the trouble to search the archives of this list alone for, say, explicit+self, you'll see that there are quite strong arguments (and argumentors) on both sides. In that sort of situation the status quo tends to hold sway. (And in this case, GvR has only recently responded to similar comments by Bruce Eckels -- a couple of heavyweights -- in a way which makes it unlikely that this is going to change). I think it's one of those things which comes down, fairly enough, to: we do things this way and it works for us; other languages do other things and it works for them. TJG From BjornSteinarFjeldPettersen at gmail.com Sat Sep 29 15:58:04 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sat, 29 Sep 2007 12:58:04 -0700 Subject: Program inefficiency? In-Reply-To: <1191094332.393736.231390@w3g2000hsg.googlegroups.com> References: <1191094332.393736.231390@w3g2000hsg.googlegroups.com> Message-ID: <1191095884.449018.59860@22g2000hsm.googlegroups.com> On Sep 29, 9:32 pm, stdazi wrote: > On Sep 29, 6:07 pm, Michael.Coll-Ba... at VerizonWireless.com wrote: > > > You did not mention the OS, but because you are using > > "pathname\editfile.txt", it sounds like you are using an MS OS. From > > past experience with various MS OSes, I found that as the number of > > files in a directory increases the slower your process runs for each > > file. > > how so? Not entirely sure why, but some of the ms docs allude to the fact that there is a linked list involved (at least for fat-style disks). -- bjorn From aleax at mac.com Sun Sep 9 11:59:08 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 9 Sep 2007 08:59:08 -0700 Subject: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute References: <1189173455.525144.326300@y42g2000hsy.googlegroups.com> <87k5r2zhd6.fsf@kip.sateh.com> <1189319685.273092.31830@r34g2000hsd.googlegroups.com> <87ejh86vrl.fsf@kip.sateh.com> Message-ID: <1i460vg.1lrus8jsdn4qN%aleax@mac.com> Stefan Arentz wrote: > Miki writes: > > > > steps.sort(key = lambda s: s.time) > > This is why attrgetter in the operator module was invented. > > from operator import attrgetter > > ... > > steps.sort(key=attrgettr("time")) > > Personally I prefer the anonymous function over attrgettr :) However, Python disagrees with you...: brain:~ alex$ python -mtimeit -s'from operator import attrgetter; L=map(complex,xrange(999))' 'sorted(L, key=lambda x:x.real)' 1000 loops, best of 3: 567 usec per loop brain:~ alex$ python -mtimeit -s'from operator import attrgetter; L=map(complex,xrange(999))' 'sorted(L, key=attrgetter("real"))' 1000 loops, best of 3: 367 usec per loop A speed-up of 35% is a pretty clear indicator of what _Python_ "prefers" in this situation:-). Alex From stef.mientki at gmail.com Sun Sep 9 17:05:24 2007 From: stef.mientki at gmail.com (stef mientki) Date: Sun, 09 Sep 2007 23:05:24 +0200 Subject: Python syntax wart In-Reply-To: References: Message-ID: <46E46014.3040401@gmail.com> James Stroud wrote: > Lawrence D'Oliveiro wrote: > >> The one thing I don't like about Python syntax is using backslashes to >> continue lines. Yes, you can avoid them if you can include parentheses >> somehow, but this isn't always possible. >> >> Possible: >> >> if ( >> quitting >> and >> len(client["to_write"]) == 0 >> and >> len(client["read"]) + client["to_read"] == 0 >> ) : >> close_client(client, "shutting down") >> #end if >> >> Not possible: >> >> for \ >> Link \ >> in \ >> GetEachRecord \ >> ( >> "links", >> ("from_episode",), >> "to_episode = %s", >> [EpisodeID], >> "order by when_created" >> ) \ >> : >> out.write \ >> ( >> "

Back to episode %d\n" >> % >> ( >> LinkToMe({"ep" : Link["from_episode"]}), >> Link["from_episode"] >> ) >> ) >> #end for >> >> > > > I usually write my code in a way that can be understood by looking at > it, with self-documenting names, clear organization, and lines that fit > under 72 characters (if I can help it). But if you insist on making perl > noise, go 'head. > > Interesting thread, in automatically converting another language to Python, the brackets idea might come in very handy. "Self-documenting names", yes I'm used to that too, but Python itself doesn't promote that ... ... as "case-sensitive" seems to me a contradiction with "self-documenting-names" ;-) cheers, Stef Mientki From gagsl-py2 at yahoo.com.ar Wed Sep 26 03:36:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Sep 2007 04:36:40 -0300 Subject: Hello Gabriel cant help noticing you References: <41607.51503.qm@web27811.mail.ukl.yahoo.com> Message-ID: En Wed, 26 Sep 2007 03:35:25 -0300, hrishy escribi?: > I couldnt help but to write this mail. > > I am not a python programmer just a shell script coder > and i am planning to learn some decent python and > raise my level from a shell script junkie to a Python > gentleman the way you explain things and show it in > code is simply amazing. Thanks! I feel somewhat embarrassed now :"> Glad to see you find my posts useful. > I particularly liked the way you explained that > Regular expression stuff to parse that XML i am just > awestruck. Thanks again! But parsing XML is not a good example of RE usage, so I don't like it so much. -- Gabriel Genellina From aine_canby at yahoo.com Thu Sep 27 09:42:03 2007 From: aine_canby at yahoo.com (aine_canby at yahoo.com) Date: Thu, 27 Sep 2007 06:42:03 -0700 Subject: Confusion regarding constructor as default value In-Reply-To: <1190898221.833936.40480@57g2000hsv.googlegroups.com> References: <1190898221.833936.40480@57g2000hsv.googlegroups.com> Message-ID: <1190900523.963182.306590@r29g2000hsg.googlegroups.com> On 27 Sep, 15:03, aine_ca... at yahoo.com wrote: > Why are the following different? > > def AddRow(self, rowName, tableRow=TableRow(ReleaseDate(""), > ExpiryDate(""))): > # check to see if the row already exists, if not add it to the > container > > if not self.dict.has_key(rowName): > self.dict[rowName] = tableRow > > def AddRow(self, rowName, tableRow): > # check to see if the row already exists, if not add it to the > container > > if not self.dict.has_key(rowName): > self.dict[rowName] = TableRow(ReleaseDate(""), ExpiryDate("")) > > It seems that when I use the first function that I'm getting duplicate > objects in self.dict > > Thanks for your help, > > Aine. I've just tried the following: Function A: def AddRow(self, rowName, tableRow=TableRow(ReleaseDate(""), ExpiryDate(""))): print tableRow if not self.dict.has_key(rowName): self.dict[rowName] = tableRow Function B: def AddRow(self, rowName, tableRow=None): if tableRow==None: tableRow = TableRow(ReleaseDate(""), ExpiryDate("")) # check to see if the row already exists, if not add it to the container print tableRow if not self.dict.has_key(rowName): self.dict[rowName] = tableRow Function A is giving: same! same! same! same! Function B is giving: So at least I know know what is causing the problem. But I'm still not understanding why I can't use TableRow() as the default value in order to geterate new instances. How would you implement this? Thanks, Aine. From garyrob at mac.com Fri Sep 7 12:19:47 2007 From: garyrob at mac.com (Gary Robinson) Date: Fri, 7 Sep 2007 12:19:47 -0400 Subject: getting the current function In-Reply-To: mailman.159.1189093808.2658.python-list@python.org Message-ID: <20070907121947211621.e552cc95@mac.com> > This all seems a bit too complicated. Are you sure you want to do > this? Maybe you need to step back and rethink your problem. In version 2.1 Python added the ability to add function attributes -- see http://www.python.org/dev/peps/pep-0232/ for the justifications. A counter probably isn't one of them, I just used that as a quick example of using thisfunc(). I've just never liked the fact that you have to name the function when accessing those attributes from within the function. And I thought there might be other uses for something like thisfunc(). -- Gary Robinson CTO Emergent Music, LLC garyrob at mac.com 207-942-3463 Company: http://www.goombah.com Blog: http://www.garyrobinson.net From ianare at gmail.com Tue Sep 4 16:17:39 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: Tue, 04 Sep 2007 13:17:39 -0700 Subject: function call Message-ID: <1188937059.459609.61850@57g2000hsv.googlegroups.com> Hey all, Is there a way of printing out how a function was called? In other words if I do the following: def someFunction(self): self.someOtherFunction(var1, var2) I would get something like "someOtherFunction: called by: someFunction, args are: var1, var2" Thanks in advance - ianar? From grante at visi.com Thu Sep 6 14:49:19 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 06 Sep 2007 18:49:19 -0000 Subject: library to launch program in linux References: <1189103678.484278.321650@r34g2000hsd.googlegroups.com> Message-ID: <13e0itfgm0ida1c@corp.supernews.com> On 2007-09-06, idzwan.nizam at gmail.com wrote: > I'm a new user. What library should I use so that I can launch > program in linux using python? Thank you in advance. subprocess -- Grant Edwards grante Yow! Hello, GORRY-O!! at I'm a GENIUS from HARVARD!! visi.com From martin at v.loewis.de Tue Sep 4 17:40:14 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 04 Sep 2007 23:40:14 +0200 Subject: FCGI app reloading on every request In-Reply-To: References: <46DCDE59.8060109@animats.com> Message-ID: <46DDD0BE.9080509@v.loewis.de> > Anything executable in the > cgi-bin directory is being launched as a CGI program. A file > named "example.foo", if executable, will launch as a CGI program. > Nothing launches with FCGI. Perhaps you have a SetHandler declaration somewhere that makes all files CGI by default? I would advise against Sethandler, and recommend AddHandler instead. Regards, Martin From pavlovevidence at gmail.com Sat Sep 29 02:19:37 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Sep 2007 02:19:37 -0400 Subject: Python 3.0 migration plans? References: Message-ID: <46fdfbf1$0$24308$4c368faf@roadrunner.com> On Fri, 28 Sep 2007 09:56:48 -0400, Stephan Deibel wrote: > Ian Dickinson wrote: >> Never would look like a good time scale to me given that a lot of the >> stuff I use is being ripped out!!!! > > Has any one actually converted any real code or significant bits of code > using the 3.0 converter (in the sandbox somewhere), and if so what kinds > of things actually failed? Well, since the converter is designed to convert 2.6 and above, and since there isn't much Python 2.6 code out there yet, I'd say nothing significant. :) Anyways, it is not designed to convert arbitrary code that's lying around: it's designed to convert a supported subset of Python 2.6+ into Python 3.0. You'd have to write "transitional Python" to use the tool. Carl Banks From shabda.raaj at gmail.com Mon Sep 10 15:27:42 2007 From: shabda.raaj at gmail.com (shabda raaj) Date: Mon, 10 Sep 2007 19:27:42 -0000 Subject: Getting error zipimport.ZipImportError: can't decompress data; zlib not available Message-ID: <1189452462.021120.199680@50g2000hsm.googlegroups.com> I have a VPS server with fedora 7. I wanted to install easy_install on this server, but I got an error saying unable to open /usr/lib/ > python2.5/config/Makefile (No such file or directory). So I installed the latest version of python from source. Now when I am trying to install libraries, I am getting an error like, "zipimport.ZipImportError: can't decompress data; zlib not available" From python.list at tim.thechases.com Sat Sep 29 21:43:50 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 29 Sep 2007 20:43:50 -0500 Subject: Optparse and help formatting? Message-ID: <46FEFF56.9090501@tim.thechases.com> I've been learning the ropes of the optparse module and have been having some trouble getting the help to format the way I want. I want to specify parts of an option's help as multiline. However, the optparse formatter seems to eat newlines despite my inability to find anything in optparse.py that does something obvious like .replace("\n", " ") to eat the newlines I stick in the help. It also seems to mung tabs. An example from my code: parser.add_option("-x", "--extended", action="callback", callback=callback_test, type="string", # required to get metavar to show in help dest="test", metavar="CONF", help="a comma-separated list of options.\n" "s=[YYYY]MMDD,n=NAME,c=COLOR\n" "s,start=[YYYY]MMDD\n" "\tstart day of period (default, current day)\n" ... ) which would accept options that looked something like test.py -x s=20070401,n=XR71,c=black (my callback_test breaks apart parser.rargs[0] to deal with the funky params). However, when I display the help, its reformatting eats the newlines in my help-string and strangely looks like it converts my tabs to spaces. Any hints on how to either work around the problem or fix it? As a side note, I couldn't find documented anywhere that if you have a "metavar" setting for a "callback" parameter, you have to specify the "type" to get the metavar to show up in the help as "-x CONF, --extended=CONF". If you don't specify the type, it will display as "-x, --extended" without the metavar, even if you specify one. Hackishly setting type="string" made the metavar appear. Thanks for any hints, -tkc (python2.4 on Debian, FWIW) From dickinsm at gmail.com Sun Sep 2 15:23:21 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 02 Sep 2007 19:23:21 -0000 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> Message-ID: <1188761001.837509.175450@50g2000hsm.googlegroups.com> On Sep 2, 7:51 am, jwrweather... at gmail.com wrote: > The resulting executable takes 0.24 seconds to run. I'm not expecting > a scripting language to run faster than native code, but I was > surprised at how much slower it was in this case. Any ideas as to what > is causing python so much trouble in the above code? Below is some code and some timings that show that Python is spending at least 1/3 of its time computing the squares: a*a, b*b and c*c. So to explain why Python is so much slower than C, it should be enough to explain what's going on with these multiplications. Here's my attempt at an explanation: To compute a*a, Python has to do the following, all at run-time (1) Find the type of a. (2) Look up the corresponding multiplication method for this type. (3) (In the multiplication method): find the type of the right-hand side, in this case a again. (4) Having established that both arguments are ints, worry about whether the result is going to overflow (in which case a long needs to be returned). (5) Do the multiplication. (6) Allocate a new Python integer to hold the result, and return it. The C code only has to do step (5), and this boils down to a single machine instruction. Mark Code and timings: (Python 2.5.1/G4.) def test(): solutions = [0] * 1000 for a in xrange(1, 1000): for b in xrange(1, 1000 - a): for c in xrange(1, 1000 - a - b): if a*a + b*b == c*c: solutions[a+b+c] += 1 return solutions def test2(): solutions = [0] * 1000 squares = [x*x for x in xrange(1000)] for a in xrange(1, 1000): for b in xrange(1, 1000 - a): for c in xrange(1, 1000 - a - b): if squares[a] + squares[b] == squares[c]: solutions[a+b+c] += 1 return solutions >>> from profile import run >>> run("l = test(); l2 = test2()") 5 function calls in 299.984 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.010 0.010 0.010 0.010 :0(setprofile) 1 0.000 0.000 299.973 299.973 :1() 1 0.000 0.000 299.984 299.984 profile:0(l = test(); l2 = test2()) 0 0.000 0.000 profile:0(profiler) 1 182.262 182.262 182.262 182.262 test.py:1(test) 1 117.711 117.711 117.711 117.711 test.py:10(test2) From afaNOSPAM at neuf.fr Thu Sep 13 18:24:15 2007 From: afaNOSPAM at neuf.fr (Amaury Forgeot d'Arc) Date: Fri, 14 Sep 2007 00:24:15 +0200 Subject: Lost in __setstate__() in C++ and swig In-Reply-To: <1884096.5YeUtxM9vj@beaureve.gmx.net> References: <1884096.5YeUtxM9vj@beaureve.gmx.net> Message-ID: Hello, Martin Drautzburg a ?crit : > I am trying to cPickle/unpickle a C++ extension class with some private > data members. I wrote __getstate__() and __setstate__ in C++ (I have > to, due to the private data). Pickling writes the following file: > > ccopy_reg > _reconstructor > p1 > (cpyramid > MidiBytes > p2 > c__builtin__ > object > p3 > NtRp4 > (S'some unknown MidiBytes' > I1 > I2 > I3 > tb. > > But when unpickling I get the following error > > TypeError: in method 'MidiBytes___setstate__', argument 1 of type > 'pyramid::MidiBytes *' > > I debugged the swig wrapper and indeed the wrapper is called with just > one tuple argument. No object seems to be present at the time. > > All the examples I've seen use python functions for __getstate__ and > __setstate__ and it seems to me that the object itself is already there > when __setstate__ is called. Unpickling an object does not use the normal path for creating the object. More precisely, the __init__ method is not called! See http://docs.python.org/dev/library/pickle.html#pickling-and-unpickling-normal-class-instances I suggest that you try to play with __getinitargs__ or __getnewargs__. By calling __init__, it will give a chance to Swig to allocate the C++ object. > > In a moment of dispair I declared __setstate__() static and have it > create and return a MidiBytes object. > > MidiBytes *MidiBytes:: __setstate__ (PyObject * aTuple) { > return new MidiBytes(); > } > > Then unpickling no longer complains about "argument 1", but the > unpickled object does not work > > >>> nn = cPickle.load(FILE) > >>> nn.len() > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/src/sound.d/pyramid/pyramid.py", line 618, in len > return _pyramid.MidiBytes_len(*args) > TypeError: in method 'MidiBytes_len', argument 1 of > type 'pyramid::MidiBytes *' This message is typical of a swig object whose __init__ method has not been called. (No later than today, I forgot to call the base.__init__ in a derived class. Maybe we should ask Swig for a better message) See above for a hint. Hope this helps... -- Amaury From m.prajwala at gmail.com Thu Sep 20 08:59:36 2007 From: m.prajwala at gmail.com (prajwala) Date: Thu, 20 Sep 2007 12:59:36 -0000 Subject: how to convert xml file to word document. Message-ID: <1190293176.702616.235480@e9g2000prf.googlegroups.com> I want to convert xml file to a word document using python. Is there any built in module available? or Is there any other way to convert xml file to word document. Please suggest me. This is very urgent now. Thanks, prajwala From steve at holdenweb.com Mon Sep 17 07:24:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Sep 2007 07:24:40 -0400 Subject: Reading text files where last line has no EOL In-Reply-To: <1190027021.235110.286450@g4g2000hsf.googlegroups.com> References: <1190027021.235110.286450@g4g2000hsf.googlegroups.com> Message-ID: <46EE63F8.8060703@holdenweb.com> BlueBird wrote: > I tried and failed to read text files where the last line does not > contain proper EOL. For my tests, I use a file that I create with the > equivalent of : > > open('toto', 'w').write( '1234\n4567\n89AB' ) > > > My reading code looks like this : > > l = f.readline() > while len(l): > self.appendLine( l ) > l = f.readline() > > The last line is not returned (89AB) is never returned. > > I tried with "for l in f" with similar results. > > I read the doc : > > In order to make a for loop the most efficient way of looping over the > lines of a file (a very common operation), the next() method uses a > hidden read-ahead buffer. As a consequence of using a read-ahead > buffer, combining next() with other file methods (like readline()) > does not work right. However, using seek() to reposition the file to > an absolute position will flush the read-ahead buffer. New in version > 2.3. > > I've tried to do a f.seek( f.tell() ) but that did not help. > > So how am I supposed to fetch that last line ? > What version of Python are you using, and on what platform? WJFFM on 2.5.1/Cygwin: >>> open('toto', 'w').write( '1234\n4567\n89AB' ) >>> for l in open('toto'): ... print l ... 1234 4567 89AB >>> You will observe that the last line is presented, but correctly does not include a trailing line feed. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From rami.mawas at gmail.com Thu Sep 13 01:12:54 2007 From: rami.mawas at gmail.com (rami.mawas at gmail.com) Date: Thu, 13 Sep 2007 05:12:54 -0000 Subject: Implementing a fixed size stack for an RPN Calculator In-Reply-To: <5kr5hoF4s6gmU3@mid.uni-berlin.de> References: <1189630522.152326.3040@d55g2000hsg.googlegroups.com> <5kr5hoF4s6gmU3@mid.uni-berlin.de> Message-ID: <1189660374.063395.71360@50g2000hsm.googlegroups.com> On Sep 12, 2:55 pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 12 Sep 2007 20:55:22 +0000, rami.ma... at gmail.com wrote: > > I have implemented an RPN calculator in python but now I would like to > > make the stack size fixed. how can I transform the user's RPN > > expression from a stack overflow to a computable expression. > > > For instance, if my stack size is 2 then the some expression can't be > > computed but could be transformed as following: > > > Non computable expression: 1 2 3 + + --> stack size of 3 is needed > > Computable expression: 1 2 + 3 + --> stack size of 2 is needed > > > How can I define a formal way of transforming the non computable > > expression to computable one. > > > My RPN only implements: + - x % > > Why does this homework assignment limit the stack so severely!? ;-) > > Ciao, > Marc 'BlackJack' Rintsch The problem is not with the stack being severely small or not, it could be 1000 but it should be fixed and that's the limitation. From tuomas.vesterinen at pp.inet.fi Wed Sep 5 04:27:36 2007 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Wed, 05 Sep 2007 08:27:36 GMT Subject: Undeterministic strxfrm? In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > I think it's not in the issue tracker - see > http://xforce.iss.net/xforce/xfdb/34060 > The fix is already in 2.5.1 > http://www.python.org/download/releases/2.5.1/NEWS.txt Thanks Gabriel, I'll try Python 2.5.1. >> Reading the rev 54669 it seems to me, that the bug is not fixed. Man >> says: >> >> STRXFRM(3): ... size_t strxfrm(char *dest, const char *src, size_t n); >> ... The first n characters of the transformed string >> are placed in dest. The transformation is based on the program?s >> current locale for category LC_COLLATE. >> ... The strxfrm() function returns the number of bytes required to >> store the transformed string in dest excluding the terminating ?\0? >> character. If the value returned is n or more, the contents of dest are >> *indeterminate*. >> >> Accordin the man pages Python should know the size of the result it >> expects and don't trust the size strxfrm returns. I don't completely >> understand the collate algorithm, but it should offer different levels >> of collate. So Python too, should offer those levels as a second >> parameter. Hovever strxfrm don't offer more parameters either except >> there is another function strcasecmp. So Python should be able to >> calculate the expected size before calling strxfrm or strcasecmp. I >> don't how it is possible. May be strcoll knows better and I should kick >> strxfrm off and take strcoll instead. It costs converting the seach key >> in every step of the search. > > > No. That's why strxfrm is called twice: the first one returns the > required buffer size, the buffer is resized, and strxfrm is called > again. That's a rather common sequence when buffer sizes are not known > in advance. > [Note that `dest` is indeterminate, NOT the function return value which > always returns the required buffer size] > OK, I made too quick conclusions of the man text without knowing the details. Tuomas From dickinsm at gmail.com Sun Sep 2 10:10:31 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 02 Sep 2007 14:10:31 -0000 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <1188740716.423349.304370@y42g2000hsy.googlegroups.com> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> Message-ID: <1188742231.470668.29910@g4g2000hsf.googlegroups.com> On Sep 2, 9:45 am, jwrweather... at gmail.com wrote: > [snip code] > > Thanks for that. I realise that improving the algorithm will speed > things up. I wanted to know why my less than perfect algorithm was so > much slower in python than exactly the same algorithm in C. Even when > turning off gcc's optimiser with the -O0 flag, the C version is still > > > 100 times quicker. Well, for one thing, you're creating half a million xrange objects in the course of the search. All the C code has to do is increment a few integers. Mark From gagsl-py2 at yahoo.com.ar Mon Sep 10 18:34:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 10 Sep 2007 19:34:47 -0300 Subject: Setting stdout encoding References: <1189416350.069995.220250@w3g2000hsg.googlegroups.com> Message-ID: En Mon, 10 Sep 2007 10:02:42 -0300, Fabio Zadrozny escribi?: >> Does someone know if there's a way to explicitly set the stdout/stderr/ >> stdin >> encoding that python should use? >> >> The encoding can be set using the C API for file objects - from Python >> code, use ctypes: >> >> > Yeap, but that would leave me with the original problem: I need to run a > script to run the original script I want to run...(and not being > compatible > with other python implementations). Isn't there any way to set that > externally (like environment variable, args to the interpreter or > anything > else like that)? You could place code like that on sitecustomize.py I think this should be fixed on Eclipse/pydev. If they replace sys.stdout with a different object - they should make sure it has the right behavior. Same for IDLE if it's broken too. -- Gabriel Genellina From steven at REMOVE.THIS.cybersource.com.au Fri Sep 7 06:40:47 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Sep 2007 10:40:47 -0000 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On Fri, 07 Sep 2007 11:46:38 +0200, Wildemar Wildenburger wrote: > gu wrote: >> hi to all! >> after two days debugging my code, i've come to the point that the >> problem was caused by an unexpected behaviour of python. or by lack of >> some information about the program, of course! i've stripped down the >> code to reproduce the problem: >> >> [snip FAQ] > > Yes, basically you *created* a pointer. That's all that python has: > pointers. No, you are confusing the underlying C implementation with Python. Python doesn't have any pointers. CPython is implemented with pointers. PyPy, being written entirely in Python, is implemented with Python objects like lists and dicts. Jython, being implemented in Java, probably isn't implemented with pointers either -- although of course the underlying Java compiler might be. IronPython and Python for .Net, I have no idea how they work. Could be magic for all I know. (Probably necromancy.) Naturally, regardless of whether you are using CPython, IronPython, PyPy or some other variety of Python, the objects available to you include ints, floats, strings, lists, dicts, sets and classes... but not pointers. Nor does it include "peek" and "poke" commands for reading and writing into random memory locations. Python is not C, and it is not Basic, nor is it Forth or Lisp or assembler, and you shouldn't hammer the round peg of Python objects into the square hole of C pointers. -- Steven. From gherron at islandtraining.com Fri Sep 28 12:01:21 2007 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 28 Sep 2007 09:01:21 -0700 Subject: Delete spaces In-Reply-To: <1190994234.526554.110870@y42g2000hsy.googlegroups.com> References: <1190994234.526554.110870@y42g2000hsy.googlegroups.com> Message-ID: <46FD2551.7010309@islandtraining.com> koutoo at hotmail.com wrote: > If I have a text file that is delimited by spaces, how do I import it > and get to comma delimited? Here is a row of data from the text file: > > 1 1 10:55:14 2 65 8.5 > 1.4+1.1 2.5 Class-2 0 > > I tried a few examples from the group and it didn't work, since the > file also has a header row and a row of seperators ( -------). The > lengths of each row is something like 130, so there are extra spaces > after the last value as well. I have tried joining and other things, > but I couldn't figure out how to get the values to come together. > Thanks. > > Kou > > After you recognize and handle the header and separator lines, the remaining lines can be handled this way: >>> l = '1 1 10:55:14 2 65 8.5' >>> f = l.split() >>> print f ['1', '1', '10:55:14', '2', '65', '8.5'] >>> ','.join(f) '1,1,10:55:14,2,65,8.5' or >>> ', '.join(f) '1, 1, 10:55:14, 2, 65, 8.5' >>> Gary Herron From jfine at pytex.org Tue Sep 18 13:11:49 2007 From: jfine at pytex.org (Jonathan Fine) Date: Tue, 18 Sep 2007 18:11:49 +0100 Subject: Metatest 0.1.0 References: <1190130384.753009.142150@i13g2000prf.googlegroups.com> Message-ID: <46F006D5.3060609@pytex.org> Kay Schluehr wrote: >> http://metatest.sourceforge.net/doc/pyconuk2007/metatest.html >From the HTML slides: > > Assertion tests are easy to write but report and run poorly. > > I tend to think this is a prejudice that leads to ever more ways to > write tests perform test discoveries, invent test frameworks etc. > > When I thought about organizing my tests for EasyExtend I was seeking > for a strategy being adapted to my own behaviour. The very first step > I made when creating a new language, modifying a grammar rule, > changing the Transformer etc. was starting an interactive shell and > typing some commands. Yes, Python is really good for that. I do it a lot also. > This is just checking out or smoke testing my > application and I wanted to reproduce it. So I recorded the > interactive shell session and replayed it as another shell session. I > enabled to set breakpoints in the logged output and implemented a > command for proceeding the replay. This is similar, I think, to what Metatest does. See http://metatest.sourceforge.net/doc/pyconuk2007/metatest.html#slide5 > Then I discovered I actually wrote an interactive test runner. I don't > have to care for all the exceptions being thrown in the session and > don't care for cleanups but just assign parts of the session as tests > using assert for getting an overview at the end. The only additonal > command I implemented was raises to capture the side-effect of raising > an exception. Sounds interesting. Is this code, or examples of its use, available? > So I'm going to argue here that there isn't anything particular about > writing/coding a test ( planning tests, specifying tests, reviewing a > testspecification etc. are another issue ). Instead you can keep a > seemingly unrelated practice and turn it into a test by a tiny > signification. I'm all in favour of making tests easier to write, easier to run, and the outputs easier to understand. I've submitted a feature request for command line use of Metatest (something I've been thinking of a while): http://sourceforge.net/tracker/index.php?func=detail&aid=1797187&group_id=204046&atid=988038 Here's how I'd like the feature to look (from the above URL): === Python 2.4.1a0 (#2, Feb 9 2005, 12:50:04) [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from metatest.py.mymod import plus >>> import metatest >>> plus(2, 3) == 6 >>> metatest.immediate = True # New command >>> plus(2, 3) == 6 TestError: Expected '6', got '5' >>> === OK. So now here's a problem. We can create stuff like the above that states clearly (I hope) what is required. How can we write a test for this sort of behaviour? So that's another feature request. While I'm in favour of using Metatest to write tests for Metatest (eating your own dogfood), I'm more interested in real world examples. But I've added second feature request, that Metatest be able to test Metatest. http://sourceforge.net/tracker/index.php?func=detail&aid=1797202&group_id=204046&atid=988038 -- Jonathan From exhuma at gmail.com Mon Sep 24 11:29:13 2007 From: exhuma at gmail.com (exhuma.twn) Date: Mon, 24 Sep 2007 08:29:13 -0700 Subject: (pyqt) Parameters when connecting a signal to a method? In-Reply-To: <5lq0vhF9gj62U1@mid.uni-berlin.de> References: <1190644558.386647.88270@22g2000hsm.googlegroups.com> <5lq0vhF9gj62U1@mid.uni-berlin.de> Message-ID: <1190647753.019994.212890@d55g2000hsg.googlegroups.com> On Sep 24, 4:47 pm, "Diez B. Roggisch" wrote: > exhuma.twn wrote: > > Some code: > > > ---------------------------------------------------------------------- > > > def foobar(w): > > print w > > > QtCore.QObject,connect( my_line_edit, > > QtCore.SIGNAL("returnPressed()"), foobar ) > > > ---------------------------------------------------------------------- > > > How can I get this to work so "foobar" prints out the sender of the > > signal (i.e. my_line_edit)? > > I _think_ there is a way to get the signals sender in Qt itself. But I'm > unsure how to get that. > > Alternatively, you can use a closure to create a reference: > > def foobar(source, w): > print w > > def slotgen(source, slot): > def _slot(*args): > return slot(*((source,) + args)) > return _slot > > my_slot = slotgen(my_line_edit, foobar) > > QtCore.QObject,connect( my_line_edit, > QtCore.SIGNAL("returnPressed()"), my_slot ) > > However, be careful to keep a reference to my_slot around! Otherwise, it > will be garbage collected! > > diez Thanks diez. This works :) Although, I still have to digest *what* this closure does, but I will leave this as an exercise to myself. ;) From gagsl-py2 at yahoo.com.ar Sun Sep 23 17:21:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 23 Sep 2007 18:21:45 -0300 Subject: Preemption in python References: <9a4753250709221928s5768b15emecfd71a0f476cce@mail.gmail.com> <1190572311.5703.4.camel@thinkpad> <9a4753250709231210l701a2cccge014732c79a5fdf9@mail.gmail.com> Message-ID: En Sun, 23 Sep 2007 16:10:03 -0300, Kurtis Heimerl escribi?: > I'll explain a bit more. This thread is spawned, I also have the main > thread > running a gtk windowed gui. The gui has it's own threads to deal with > button > presses and such. The problem is that the gui never seems to let anyone > else > run. Only on button presses that cause blocking calls ( > ossaudiodev.audio.read for instance) does the reader thread print > anything. Google for "python gtk threading tutorial" -- Gabriel Genellina From http Sat Sep 1 02:35:42 2007 From: http (Paul Rubin) Date: 31 Aug 2007 23:35:42 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188589721.367781.322150@z24g2000prh.googlegroups.com> Message-ID: <7xabs6gaf5.fsf@ruckus.brouhaha.com> Russ writes: > The idea here is that errors in the self-testing code are unlikely > to be correlated with errors in the primary code. Hence, you get a > sort of multiplying effect on reliability. For example, if the > chance of error in the primary code and the self-test code are each > 0.01, the chance of an undetected error is approximately 0.01^2 or > 0.0001. But I think you give a lot of that back when you turn the checks off. The errors you detect when the checks are enabled are only the ones that result from your test data. Turn off the checks and expose the application to data from a potentially different distribution, and you're back where you started. From BjornSteinarFjeldPettersen at gmail.com Sun Sep 16 19:35:10 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 16 Sep 2007 23:35:10 -0000 Subject: adding a static class to another class In-Reply-To: References: Message-ID: <1189985710.946694.219420@g4g2000hsf.googlegroups.com> On Sep 17, 1:14 am, "Nathan Harmston" wrote: > HI, > > I m trying to start an api in a similar way to the djangic way of > Class.objects.all(). Ie objects is a "Manager" class. > > So: > > class Foo(object): > def __init__(self): > self.test = "NEE" > > class Manager(object): > def __init__(self): > pass > def all(self): > return "COCONUTS" > > Because of how some of the code is set up I cant use > metaclasses........so I try to use a decorator: > > def addto(instance): > def decorator(f): > import new > f = new.instancemethod(f, instance, instance.__class__) > setattr(instance, "objects", f) > return f > return decorator > > class Manager(object): > @addto(Foo) > def __init__(self): > ............. > > however this only binds the init method to the Foo.objects, so not > what I want. If I try using classmethod...then it just says the > Foo.objects doesnt exist. > > Does anyone have any ideas how I can accomplish this using decorators? > And also preventing more than one Manager instance instantiated at one > time. > > Many Thanks in advance, > > Nathan You want to use descriptors (classes that implement __get__, __set__, __del__). Google for the particulars. -- bjorn From michele.simionato at gmail.com Wed Sep 19 07:36:51 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 19 Sep 2007 11:36:51 -0000 Subject: super() doesn't get superclass In-Reply-To: <87fy1a6h3b.fsf@mulj.homelinux.net> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <87fy1a6h3b.fsf@mulj.homelinux.net> Message-ID: <1190201811.727402.172330@k79g2000hse.googlegroups.com> On Sep 19, 1:16 pm, Hrvoje Niksic wrote: > Your arguments against the superclass term seem to assume that there > is only a single superclass to a particular class. If you say "the" superclass, then you also assume it is unique. But the big issue is that the order of the methods depends on the second argument to super, the instance, so there is no useful concept of the superclass of the first argument of super. I rest my case. Michele Simionato From bjorn.kempen at gmail.com Sat Sep 15 17:24:18 2007 From: bjorn.kempen at gmail.com (buffi) Date: Sat, 15 Sep 2007 21:24:18 -0000 Subject: problems using pythom tempfile module In-Reply-To: <1189890699.807384.258580@o80g2000hse.googlegroups.com> References: <1189890699.807384.258580@o80g2000hse.googlegroups.com> Message-ID: <1189891458.583774.171030@22g2000hsm.googlegroups.com> On Sep 15, 11:11 pm, "samir.... at googlemail.com" wrote: > Hello everyone, > > I'm trying to test the tempfile module with the following script, > which basically creates a temporary file, fills the file with some > test data and prints it. > > import tempfile > > t = tempfile.TemporaryFile() > t.write("lalalala") > t.flush() > print t.read() > > Unfortunately, the print statement gives me an empty string. Can > somebody tell me what I'm doing wrong ? > > regards Samir Do a t.seek(0) before you do the read to "rewind" the file and then it should work. From steve at REMOVE-THIS-cybersource.com.au Fri Sep 21 19:33:35 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 21 Sep 2007 23:33:35 -0000 Subject: Calling constructor but not initializer References: <13f7kmfhe19lb7b@corp.supernews.com> Message-ID: <13f8l6fs0ukfu57@corp.supernews.com> On Fri, 21 Sep 2007 10:47:02 -0400, Steve Holden wrote: [snippity-doo-dah] >> but of course __init__ is automatically called. >> >> >> Any suggestions for doing something like this? >> >> > Easy: use a method whose name is something other than __init__, then > don't bother to implement __init__. Note that __new__ shouldn't call > __init__ anyway, that's done by the instance creation mechanism. *stares at post* You know, I must have been REALLY tired last night, because that is extraordinarily obvious. Even more obvious is not to use __new__ at all, and just wrap the body of the __init__ in an "if instance should not be empty" clause. Thanks to everyone for answering my stupid question without laughing. -- Steven. From michael at stroeder.com Wed Sep 5 03:07:25 2007 From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=) Date: Wed, 05 Sep 2007 09:07:25 +0200 Subject: FCGI app reloading on every request In-Reply-To: References: <46DCDE59.8060109@animats.com> Message-ID: John Nagle wrote: > > Tried putting this in the .htaccess file: > > > SetHandler fcgid-script > Options ExecCGI > allow from all > > > > ErrorDocument 403 "File type not supported." > > > Even with that, a ".foo" file gets executed as a CGI script, > and so does a ".fcgi" file. It's an Apache configuration problem. Are you sure that the server configuration allows overriding this in the .htaccess file? Ciao, Michael. From tdelaney at avaya.com Mon Sep 24 01:19:41 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 24 Sep 2007 13:19:41 +0800 Subject: I could use some help making this Python code run faster usingonly Python code. In-Reply-To: <1190491371.189556.177790@d55g2000hsg.googlegroups.com> Message-ID: Python Maniac wrote: > Some benchmarks showing the effectiveness of using Psyco: > > scramble: 4.210 > scramble_listcomp: 2.343 > scramble_gencomp: 2.599 > scramble_map: 1.960 > scramble_imap: 2.231 > scramble_dict: 2.387 > scramble_dict_map: 0.535 > scramble_dict_imap: 0.726 > scramble_translate: 0.010 > > Now with Psyco... > psyco.bind(scramble)... > scramble: 0.121 4.088 34.670x faster > scramble_listcomp: 0.215 2.128 10.919x faster > scramble_gencomp: 2.563 0.036 1.014x faster > scramble_map: 2.002 -0.043 0.979x slower > scramble_imap: 2.175 0.056 1.026x faster > scramble_dict: 0.199 2.188 11.983x faster > scramble_dict_map: 0.505 0.029 1.058x faster > scramble_dict_imap: 0.728 -0.001 0.998x slower > scramble_translate: 0.009 0.001 1.111x faster > > Overall, Psyco helped my little process of converting 20 MB worth of > ASCII into what may not look like the original at 6x faster than > without Psyco. One thing you should notice with the above results: Psyco made your initial, totally unoptimised algorithm the fastest of all (except for translate, which is in a different league of course - but is much more limited in what it can do). The other algorithms are already heavily working in C code (dicts, etc), but the initial algorithm provided lots of opportunities for Psyco to hook in and use the runtime behaviour. So, before trying to optimise, see if Psyco gives you the performance you need. Tim Delaney From imageguy1206 at gmail.com Fri Sep 7 07:35:34 2007 From: imageguy1206 at gmail.com (imageguy) Date: Fri, 07 Sep 2007 04:35:34 -0700 Subject: py2exe - change name of exe created Message-ID: <1189164934.544314.170020@w3g2000hsg.googlegroups.com> I have a setup script like this; setup(windows = [{"script":"myprogram.py", "icon_resources":[(0,"nabbitt.ico")], "other_resources": [(24,1,manifest)]} ], name = "Nabbitt ver 0.1", data_files = [("",rootdata)], zipfile = None, options = {"py2exe": { "compressed" : 1, "dll_excludes": ["w9xpopen.exe"], #should also exclude MSVCR71.dll "bundle_files": 3 # 1=Single .exe, 2=.exe with pythonXX.dll } }, ) From tim.couper at scivisum.co.uk Sat Sep 1 06:20:19 2007 From: tim.couper at scivisum.co.uk (Tim Couper) Date: Sat, 01 Sep 2007 11:20:19 +0100 Subject: So what exactly is a complex number? In-Reply-To: <46d92f54$0$4533$9b4e6d93@newsspool3.arcor-online.net> References: <451mq4-les.ln1@ozzie.tundraware.com> <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> <46d92f54$0$4533$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <46D93CE3.2040404@scivisum.co.uk> .. FWIW the fundamental difference in using complex number to represent purely vector information is that the algebra of complex numbers is such that the product of two of the imaginary components has a result in the real range (and a product of a real and imaginary components is in the imaginary range, etc); so what you are modelling should have this behaviour if you're using complex numbers to represent it; otherwise a vector representation could be more appropriate. So in areas of physics where complex number representations are used, rather than vector, it's because this this algebra *is* appropriate. Now, if you're modelling entities that has up to 2 numeric components, which dos not have this "complex number" behaviour, and you're at most going to add and subtract these, then the representation of this as vector or complex number model are indeed identical. This could, however, be considered a special, or at least a simple, case. Dr Tim Couper CTO, SciVisum Ltd www.scivisum.com Wildemar Wildenburger wrote: > Lawrence D'Oliveiro wrote: > >> In message <46d89ba9$0$30380$9b4e6d93 at newsspool4.arcor-online.net>, Wildemar >> Wildenburger wrote: >> >> >>> Tim Daneliuk wrote: >>> >>>> One of the most common uses for Complex Numbers is in what are >>>> called "vectors". In a vector, you have both an amount and >>>> a *direction*. For example, I can say, "I threw 23 apples in the air >>>> at a 45 degree angle". Complex Numbers let us encode both >>>> the magnitude (23) and the direction (45 degrees) as a "number". >>>> >>>> >>> 1. Thats the most creative use for complex numbers I've ever seen. Or >>> put differently: That's not what you would normally use complex numbers >>> for. >>> >> But that's how they're used in AC circuit theory, as a common example. >> > > > OK, I didn't put that in the right context, I guess. The "magnitude and > direction" thing is fine, I just scratched my head at the "23 apples at > 45 degrees" example. Basically because I see no way of adding 2 apples > at 16 degrees to 4 apples at 25 degrees and the result making any sense. > Anyway, that was just humorous nitpicking on my side, don't take it too > seriously :). > > /W > From ben at benfinney.id.au Tue Sep 18 00:15:25 2007 From: ben at benfinney.id.au (Ben Finney) Date: Tue, 18 Sep 2007 14:15:25 +1000 Subject: super() doesn't get superclass Message-ID: <8764281uea.fsf@benfinney.id.au> Howdy all, After banging my head against super() trying to reliably get attributes of a superclass, I gained a little enlightenment when this turned up in a search: "Python's Super is nifty, but you can't use it (Previously: Python's Super Considered Harmful)" An early paragraph stood out that made my current problems clear: One big problem with 'super' is that it sounds like it will cause the superclass's copy of the method to be called. This is simply not the case, it causes the next method in the MRO to be called. Oh. The author's right, I got that mistaken impression too. Obviously, then, I must have misread the documentation of 'super'. I went back to double-check, and was appalled to find: super(type[, object-or-type]) Return the superclass of type. [...] Why does the documentation of 'super' say that it returns the superclass when *that's not true*? It doesn't return the superclass, it returns the next class in the MRO, whether that's a superclass or not. Actually, even that's not true. The error message "AttributeError: 'super' object has no attribute 'bazfunc'" makes it clear that 'super' actually returns not the superclass, but a 'super' object, whatever that's supposed to be. After reading the rest of the article, I'm amazed that 'super' as currently implemented is in Python at all. I agree with the author that it's useless unless *everyone* uses it for *everything*, and even then it's pretty limited. One thing's for sure, it's badly misnamed, and falsely documented. Can anyone point me to a counter-argument to the above article? -- \ "The World is not dangerous because of those who do harm but | `\ because of those who look at it without doing anything." | _o__) ?Albert Einstein | Ben Finney From irstas at gmail.com Fri Sep 28 14:06:07 2007 From: irstas at gmail.com (irstas at gmail.com) Date: Fri, 28 Sep 2007 18:06:07 -0000 Subject: Can I overload the compare (cmp()) function for a Lists ([]) index function? In-Reply-To: <1191000652.430036.288400@y42g2000hsy.googlegroups.com> References: <1191000652.430036.288400@y42g2000hsy.googlegroups.com> Message-ID: <1191002767.350147.153910@57g2000hsv.googlegroups.com> On Sep 28, 8:30 pm, xkenneth wrote: > Looking to do something similair. I'm working with alot of timestamps > and if they're within a couple seconds I need them to be indexed and > removed from a list. > Is there any possible way to index with a custom cmp() function? > > I assume it would be something like... > > list.index(something,mycmp) > > Thanks! Wouldn't it be enough to get the items that are "within a couple of seconds" out of the list and into another list. Then you can process the other list however you want. Like this: def isNew(x): return x < 5 data = range(20) print data out, data = filter(isNew, data), filter(lambda x: not isNew(x), data) print out, data Why do you want to use 'index'? Your suggestion "list.index.__cmp__ = mycmp" certainly doesn't do anything good. In fact, it just fails because the assignment is illegal.. I don't think any documentation suggests doing that, so why are you even trying to do that? It's just not a good idea to invent semantics and hope that they work, in general. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Sep 20 12:49:52 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 20 Sep 2007 18:49:52 +0200 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: Message-ID: <46f2a49b$0$15456$426a74cc@news.free.fr> W. Watson a ?crit : > Is there an editor that allows one to position to put the cursor and > then by pushing some button goes to the end of the def? Emacs. And you don't even have to "push some button" (just remember the correct key sequence !-) From mbac at gpshopper.com Thu Sep 13 19:57:21 2007 From: mbac at gpshopper.com (Michael Bacarella) Date: Thu, 13 Sep 2007 19:57:21 -0400 Subject: httplib hangs in read / strace says recvfrom() Message-ID: <46E9CE61.7000706@gpshopper.com> Hi list, I'm 99% sure httplib is sporadically hanging when I call read() on the HTTPResponse object (r.status == 200). Evidence: straceing the process shows it's blocked in recvfrom() ls -la /proc/pid/fd shows the socket-id for recvfrom() file descriptor (3) lsof -n | grep socket-id shows the connection to the HTTP server (on localhost:8080) tcpdump -s 10000 -XXX -i lo port 8080 shows a response IS coming over the wire This seems to be a common problem (according to the internets) but I haven't seen a resolution or explanation posted. I've tried httplib.py from Python 2.3 and also dropped in the one from Python 2.5 with no difference. Running on Linux kernel 2.6 (CentOS's, specifically). Any responses CC me as I'm not subscribed [since Python has worked so flawlessly for me otherwise ] -- Michael Bacarella Director of Technology 1-212-488-2222 (office) 1-646-641-8662 (mobile) http://gpshopper.com/ http://slifter.com/ GPSHOPPER, LLC 307 Seventh Avenue Suite 2104 New York, NY 10001 From Graham.Dumpleton at gmail.com Thu Sep 27 19:41:47 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 27 Sep 2007 23:41:47 -0000 Subject: mod_python preprocess/filter before proxy In-Reply-To: References: Message-ID: <1190936507.059142.169060@y42g2000hsy.googlegroups.com> Yes, use PythonInputFilter directive to specify an input filter. http://www.modpython.org/live/current/doc-html/dir-filter-if.html Input filters which modify the length of the data may be an issue though when doing proxying however. If you cant work it out, possibly more appropriate to take your questions to the official mod_python mailing list referenced on the mod_python site. Graham On Sep 27, 9:26 pm, David S?nchez Mart?n wrote: > Hi! > > I've seen the message below in this python list, that seems to be > unanswered. > > I'm trying to do the pretty same thing. > > There's a way to preprocess the request with a mod_python handler and then > proxying it with mod_proxy? > > Thank you very much in advance, and sorry for trying to revive such an old > message. > > Cheers. > > > > > > >whale whale at mycameo.com > >Tue Mar 25 05:49:42 CET 2003 > > >I use Apache2.0.44 and mod_python3.0.1. > >I add ProxyPass and PythonHandler directives in httpd.conf > >## httpd.conf > >ProxyPass /test/ http://www.test.com > >ProxyPassReverse /test/ http://www.test.com > > > > AddHandler python-program .htm .html > > PythonHandler mptest > > > > >And mptest.py: > >from mod_python import apache > >def handler(req): > > req.write('Hello!!') > > return apache.OK > > >ex. My apache server iswww.server.com. > >When I browsed the local server request(ex. > >http://www.server.com/1.html), > >I received 'Hello!!' response, the python handler worked well. > >But when I browse the proxy request(ex. > >http://www.server.com/test/1.html), > >the response I received is the original content of > >http://www.test.com/1.html, not 'Hello!!'. > >The proxy requests didn't seem to be processed by mod_python handler. > >How could I pre-process the proxy request before mod_proxy module? > >Thanks a lot!! > > --- > David Sanchez Martin > Administrador de Sistemas > dsanc... at e2000.es > GPG Key ID: 0x37E7AC1F > > E2000 Nuevas Tecnolog?as > Tel : +34 902 19 61 77 > > David S?nchez Mart?n.vcf > 1KDownload > > smime.p7s > 1KDownload From arkanes at gmail.com Thu Sep 27 16:40:16 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 27 Sep 2007 15:40:16 -0500 Subject: Cross-platform time out decorator In-Reply-To: <87ejgjnarq.fsf@mulj.homelinux.net> References: <1190802115.585306.250400@o80g2000hse.googlegroups.com> <1190899882.702911.44670@w3g2000hsg.googlegroups.com> <87k5qc18gf.fsf@mulj.homelinux.net> <1190907553.425261.273400@w3g2000hsg.googlegroups.com> <87ejgjnarq.fsf@mulj.homelinux.net> Message-ID: <4866bea60709271340h5ab27afbk2cf11599a5369935@mail.gmail.com> On 9/27/07, Hrvoje Niksic wrote: > Joel writes: > > >> Note that, unlike the original alarm code, it doesn't really interrupt > >> the timed-out method, it just returns the control back to the caller, > >> using an exception to mark that a timeout occurred. The "timed out" > >> code is still merrily running in the background. I don't know if it's > >> a problem in your case, but it's an important drawback. > > > > There should be a method to stop the thread though? > > Not in Python. Thread killing primitives differ between systems and > are unsafe in general, so they're not exposed to the interpreter. On > Windows you can attempt to use ctypes to get to TerminateThread, but > you'll need to hack at an uncomfortably low level and be prepared to > deal with the consequences, such as memory leaks. If the timeouts > happen rarely and the code isn't under your control (so you have no > recourse but to terminate the thread), it might be worth it though. > -- You can use ctypes and the Python API to raise a Python exception in the thread. I don't normally mention this, because it has some limitations, but it results in essentially the same effect as the signal based method. They both have the limitation that C code can't be interrupted. From wolf_tracks at invalid.com Thu Sep 20 23:49:59 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 20 Sep 2007 20:49:59 -0700 Subject: Drawing a 640x480 Raw Image In-Reply-To: References: Message-ID: Corrected misspelling in Subject. The image here is nothing more than a 640x480 byte array. Each byte is a gra[e]yscale value. W. Watson wrote: > I'm getting a 640x480 greyscale image from a video device. I'd like to > place it on a canvas and then draw on the image. Does PIL or some image > facility allow me to do that? > -- Wayne Watson (Nevada City, CA) Web Page: From fernandofariajunior at gmail.com Mon Sep 3 19:11:49 2007 From: fernandofariajunior at gmail.com (fernando) Date: Mon, 03 Sep 2007 23:11:49 -0000 Subject: Registering a python function in C In-Reply-To: <1188592047.542946.249520@57g2000hsv.googlegroups.com> References: <1188508874.879215.319400@i13g2000prf.googlegroups.com> <1188516423.744038.309700@z24g2000prh.googlegroups.com> <1188588784.764658.317570@r34g2000hsd.googlegroups.com> <1188592047.542946.249520@57g2000hsv.googlegroups.com> Message-ID: <1188861109.041382.178950@d55g2000hsg.googlegroups.com> > Is Maya a different python build than what is contained at python.org? > If so, I suggest you get your C program to work with the latest python > build > from python.org. Then see if you can get it to work with the Maya > version. Ok, did that. If I write a normal C++ program and use the python installed in my system, everything works ok and I can call the python funtions. From within maya(where the C code is running as a plugin), nothing happens. I tried removing my python installation so that only the one that comes with maya is running, but then I have no python.h or libs to compile against!! I found no help at the maya/python newsgroup, is there anyone who has done this before??? Thanks for all the help! From jcd at sdf.lonestar.org Sun Sep 16 08:44:47 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Sun, 16 Sep 2007 08:44:47 -0400 Subject: generate list of partially accumulated values In-Reply-To: References: <1189936564.932553.148800@50g2000hsm.googlegroups.com> <1189936979.276166.103080@w3g2000hsg.googlegroups.com> <1189937183.100462.175070@o80g2000hse.googlegroups.com> <1189938119.469599.171960@w3g2000hsg.googlegroups.com> Message-ID: <46ED253F.3090109@sdf.lonestar.org> ZeD wrote: > cesco wrote: > > >> The list is composed of objects: >> l = [obj1, obj2, obj3, obj4] >> and I need to call a method (say method1) on each object as follow: >> l1 = [obj1.method1(obj2), obj2.method1(obj3), obj3.method1(obj4), >> obj4] >> > > to me it sounds a bit different from the original request, but... > > That's because it's the next problem on his homework assignment. See also the thread entitled: "generating list of sub lists. Cheers, Cliff From tokland at gmail.com Sat Sep 29 09:38:43 2007 From: tokland at gmail.com (tokland at gmail.com) Date: Sat, 29 Sep 2007 13:38:43 -0000 Subject: question about for cycle In-Reply-To: References: Message-ID: <1191073123.459709.98870@g4g2000hsf.googlegroups.com> On 29 sep, 12:04, "fdu.xia... at gmail.com" wrote: > for i in generator_a: # the first "for" cycle > for j in generator_b: > if something_happen: > # do something here ..., I want the outer cycle to break > break Do you like this? generator_ab = ((x, y) for x in generator_a for y in generator_b) for i, j in generator_ab: if condition: # do something break From NikitaTheSpider at gmail.com Thu Sep 13 11:38:56 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Thu, 13 Sep 2007 11:38:56 -0400 Subject: Generating HTML References: Message-ID: In article , "Sebastian Bassi" wrote: > Hello, > > What are people using these days to generate HTML? I still use > HTMLgen, but I want to know if there are new options. I don't > want/need a web-framework a la Zope, just want to produce valid HTML > from Python. > Best, > SB. Spyce. Works fine server side (like PHP) and also run from the command line. http://spyce.sourceforge.net/ -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From erik at myemma.com Sat Sep 15 12:26:23 2007 From: erik at myemma.com (Erik Jones) Date: Sat, 15 Sep 2007 11:26:23 -0500 Subject: how to join array of integers? In-Reply-To: <13eo0pbiab4spdf@corp.supernews.com> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <13eo0pbiab4spdf@corp.supernews.com> Message-ID: <2EE95E6A-D6D0-4742-844E-4F18265DC469@myemma.com> On Sep 15, 2007, at 11:07 AM, Grant Edwards wrote: > On 2007-09-15, Arnau Sanchez wrote: > >>>> in Python... is the method to use ",".join() ? but then it >>>> must take a list of strings... not integers... >>>> >>>> any fast method? >> >>> print ''.join([str(i) for i in [1,2,3]]) >> >> It's better to use generator comprehension instead of LC: >> >> ",".join(str(i) for i in [1, 2, 3]) >> >> Or, if you happen to like the itertools modules: >> >> from itertools import imap >> ",".join(imap(str, [1, 2, 3])) > > It's nice people have invented so many ways to spell the > builting "map" ;) > >>>> ",".join(map(str,[1,2,3])) > '1,2,3' IIRC, map's status as a builtin is going away. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From jstroud at mbi.ucla.edu Thu Sep 13 22:21:08 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 13 Sep 2007 19:21:08 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189733785.813953.77370@k79g2000hse.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <1189733785.813953.77370@k79g2000hse.googlegroups.com> Message-ID: Carl Banks wrote: > On Sep 13, 4:20 pm, James Stroud wrote: >> Mark Summerfield wrote: >>> - If an item is inserted it is put in the right place (because the >>> underlying data structure, b*tree, skiplist or whatever is >>> intrinsically ordered by < on the key) >> +1 for all your suggestions below, but -1 for the above. You suggest that >> >> myOrderedDict['key'] = value >> >> would place it in the dictionary in sorted order depending on 'key'. >> More natural to some of us (or maybe its just me) would be to append the >> key/value pair to the end of items. > > Or, maybe, like, you know, you could have two different types that > maintain two different orders? > Do you mean, like, a SortedDict and an OrderedDict like I mentioned in the post you are replying to? From grante at visi.com Mon Sep 10 15:34:21 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 10 Sep 2007 19:34:21 -0000 Subject: How do I disable warnings? Message-ID: <13eb71tjns922f9@corp.supernews.com> I've read the documentation for the warnings module, but I'm still unable to figure out how to disable a warning. I'd like to disable this warning: Warning: 'with' will become a reserved keyword in Python 2.6 AFAICT, the following should work. But, it doesn't. import warnings warnings.filterwarnings('ignore',".*'with' will become a reserved keyword.*") What am I doing wrong? -- Grant Edwards grante Yow! And then we could sit at on the hoods of cars at visi.com stop lights! From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 5 09:30:10 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 05 Sep 2007 15:30:10 +0200 Subject: Accessing Module variables from another Module In-Reply-To: <1188996919.321965.262830@k79g2000hse.googlegroups.com> References: <1188981521.735630.133060@r29g2000hsg.googlegroups.com> <46de9f7f$0$30604$426a34cc@news.free.fr> <1188996919.321965.262830@k79g2000hse.googlegroups.com> Message-ID: <46deaf5d$0$6133$426a74cc@news.free.fr> cjt22 at bath.ac.uk a ?crit : > On Sep 5, 1:22 pm, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> cj... at bath.ac.uk a ?crit : >> >>> Hi >>> I am new to Python (I have come from a large background of Java) and >>> wondered if someone could explain to me how I can access variables >>> stored in my main module to other functions within other modules >>> called >>> from this module >> (snip code) >>> I am currently just passing the variable in as a parameter >> And this is the RightThing(tm) to do. >> >>> but I thought with Python there would be a way to gain direct access >>> to >>> storeList within the modules called from the top main module? >> Yes : passing it as a param !-) >> >> For other modules to get direct access to main.storeList, you'd need >> these modules to import main in these other modules, which would >> introduce circular dependencies, which are something you usuallay don't >> want. (NB : the canonical solution to circular dependencies is to move the relevent definitions to a third module.) > Also, and while it's ok to read imported modules attributes, it's >> certainly not a good idea to mutate or rebind them IMHO, unless you're >> ok with spaghetti code. > > Cheers Bruno, I just wanted to make sure I was being consistent with > the "Python way of things" :) Then fire up your python shell and type 'import this' !-) From zentraders at gmail.com Fri Sep 14 11:00:46 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 14 Sep 2007 08:00:46 -0700 Subject: subclass of integers In-Reply-To: <1189780201.692192.291010@k79g2000hse.googlegroups.com> References: <1189780201.692192.291010@k79g2000hse.googlegroups.com> Message-ID: <1189782046.121148.65220@22g2000hsm.googlegroups.com> This would accept ints, floats, and decimal types. import decimal class Nint(int): def __add__(self, x, y): try: return x+y except: return None if __name__=='__main__': N=Nint() print N.__add__( 1, 2 ) print N.__add__( 1, None ) print N.__add__(decimal.Decimal("2"), decimal.Decimal("3")) print N.__add__(decimal.Decimal("2"), 3) From rjagodic at gmail.com Mon Sep 24 15:17:48 2007 From: rjagodic at gmail.com (Ratko) Date: Mon, 24 Sep 2007 19:17:48 -0000 Subject: Can a base class know if a method has been overridden? In-Reply-To: References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> <46f7d897$0$25150$426a74cc@news.free.fr> <1190648887.051630.168520@r29g2000hsg.googlegroups.com> <46f7e8df$0$21052$426a74cc@news.free.fr> Message-ID: <1190661468.851812.60970@50g2000hsm.googlegroups.com> On Sep 24, 12:56 pm, St?phane Larouche wrote: > What about something like: > > class A(object): > def my_method(self): > print "A.my_method" > def call_my_method(self): > if type(self).my_method == A.my_method: > print "Calling base class method." > else: > print "Calling derived class method." > self.my_method() > > class B(A): > pass > > class C(A): > def my_method(self): > print "C.my_method" > > a = A() > b = B() > c = C() > > a.call_my_method() > b.call_my_method() > c.call_my_method() > > St?phane I think it would confuse the user to have to call "call_my_method" as opposed to calling "my_method" directly. The only reason why I wanted to do this is simplicity, clarity and transparency. Thanks though. Bruno's solution does exactly what I was looking for. Ratko From pavlovevidence at gmail.com Tue Sep 18 06:22:00 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 18 Sep 2007 06:22:00 -0400 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87vea8zg61.fsf@benfinney.id.au> Message-ID: <46efb3c7$0$16468$4c368faf@roadrunner.com> On Tue, 18 Sep 2007 15:38:46 +1000, Ben Finney wrote: > Evan Klitzke writes: > >> If you're using multiple inheritance, and you're _not_ using super >> everywhere, then your code is broken anyway. > > This seems to support the notion that 'super' is unusable. If I inherit > from code that isn't under my control, and then use super(), my code is > broken. > > Therefore, to avoid writing broken code, I must either never inherit > from code not under my control, or I must never use super(). Since the > former is practically unavoidable, I must choose the latter. > > Which, naturally, compounds the problem, since when someone else uses > *my* code, they in turn must conclude that they can't use super(). I'm sorry, but you can't inherit from someone else's classes and not worry about what they're doing. Whether they use super or not is only one possible concern. It's not like the super destroyed the magical utopia where you could derive from other people's classes without worry. In any case, it's just as problematic if you don't use super and your base classes do. By your logic, your code is "broken" no matter what you do, and so the only "conclusion" you can come to is never to derive from classes that aren't under your control. (Which, frankly, isn't all that bad a conclusion. In 8 years of Python programming, I've inherited from exactly one class that wasn't under my control: Thread. It's not "practically impossible" to avoid, at least not for me.) >> Use super correctly in your own code, and you don't need to worry about >> other people using it incorrectly. > > As the article points out, when using super(), > > you must remember that super does not call your superclass. You must > be prepared to call any other class's method in the hierarchy and be > prepared to be called from any other class's method. > > So, the programmer using super() very much *does* need to worry about > other people using it correctly. Yes. Welcome to programming. Carl Banks From deets at nospam.web.de Sun Sep 2 17:12:17 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 02 Sep 2007 23:12:17 +0200 Subject: howto reload Python module? In-Reply-To: <1188764906.354022.86370@50g2000hsm.googlegroups.com> References: <1188764906.354022.86370@50g2000hsm.googlegroups.com> Message-ID: <5k0n9qF1jemiU1@mid.uni-berlin.de> dmitrey schrieb: > my Python module was changed in HDD (hardware disk drive), moreover, > changed its location (but still present in sys.path). > how can I reload a func "myfunc" from the module? (or howto reload > whole module)? > Thank you in advance, D. By using *drumroll* the reload function! diez From duncan.booth at invalid.invalid Tue Sep 4 09:06:38 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Sep 2007 13:06:38 GMT Subject: Printing lists in columns (was: TypeError: 'module object is not callable') References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> Message-ID: cjt22 at bath.ac.uk wrote: >> But watch out if the lists aren't all the same length: zip won't pad out >> any sequences, so it maynotbe exactly what is wanted here: >> >> >>> x = ['1', '2', '3'] >> >>> y = ['4', '5'] >> >>> for row in zip(x,y): >> >> print ', '.join(row) >> >> 1, 4 >> 2, 5 >> > > Unfortunately the lists will be of different sizes In that case use: from itertools import repeat, chain, izip def izip_longest(*args, **kwds): fillvalue = kwds.get('fillvalue') def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): yield counter() # yields the fillvalue, or raises IndexError fillers = repeat(fillvalue) iters = [chain(it, sentinel(), fillers) for it in args] try: for tup in izip(*iters): yield tup except IndexError: pass x = ['1', '2', '3'] y = ['4', '5'] for row in izip_longest(x,y, fillvalue='*'): print ', '.join(row) which gives: 1, 4 2, 5 3, * (izip_longest is in a future version of itertools, but for now you have to define it yourself). From arkanes at gmail.com Thu Sep 20 08:56:22 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 20 Sep 2007 07:56:22 -0500 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <1190263363.496695.83300@57g2000hsv.googlegroups.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190263363.496695.83300@57g2000hsv.googlegroups.com> Message-ID: <4866bea60709200556s4056f82fga35ee0de581fae3a@mail.gmail.com> On 9/19/07, TheFlyingDutchman wrote: > On Sep 19, 5:08 pm, "Terry Reedy" wrote: > > "Terry Reedy" wrote in message > > This is a little confusing because google groups does not show your > original post (not uncommon for them to lose a post in a thread - but > somehow still reflect the fact that it exists in the total-posts > number that they display) that you are replying to. > > > > > > This assumes that comparing versions of 1.5 is still relevant. As far as I > > know, his patch has not been maintained to apply against current Python. > > This tells me that no one to date really wants to dump the GIL at the cost > > of half Python's speed. Of course not. The point of dumping the GIL is to > > use multiprocessors to get more speed! So with two cores and extra > > overhead, Stein-patched 1.5 would not even break even. > > > > Quad (and more) cores are a different matter. Hence, I think, the > > resurgence of interest. > > I am confused about the benefits/disadvantages of the "GIL removal". > Is it correct that the GIL is preventing CPython from having threads? > No. Python has threads, and they're wrappers around true OS level system threads. What the GIL does is prevent *Python* code in those threads from running concurrently. > Is it correct that the only issue with the GIL is the prevention of > being able to do multi-threading? > This sentence doesn't parse in a way that makes sense. > If you only planned on writing single-threaded applications would GIL- > removal have no benefit? > Yes. > Can threading have a performance benefit on a single-core machine > versus running multiple processes? > A simple question with a complicated answer. With the qualifier "can", I have to say yes to be honest although you will only see absolute performance increases on a single core from special purposed APIs that call into C code anyway - and the GIL doesn't effect those so GIL removal won't have an effect on the scalability of those operations. Pure CPU bound threads (all pure Python code) will not increase performance on a single core (there's CPU level concurrency that can, but not OS level threads). You can improve *perceived* performance this way (latency at the expense of throughput), but not raw performance. Very, very few operations are CPU bound these days, and even fewer of the ones were Python is involved. The largest benefits to the desktop user of multiple cores are the increase in cross-process performance (multitasking), not single applications. Servers vary more widely. However, in general, there's not a huge benefit to faster threading when you can use multiple processes instead. Python is not especially fast in terms of pure CPU time, so if you're CPU bound anyway moving your CPU bound code into C (or something else) is likely to reap far more benefits - and sidestepping the GIL in the process. In short, I think any problem that would be directly addressed by removing the GIL is better addressed by other solutions. > > So now this question for you: "CPython 2.5 runs too slow in 2007: true or > > false?" > > I guess I gotta go with Steven D'Aprano - both true and false > depending on your situation. > > > If you answer false, then there is no need for GIL removal. > > OK, I see that. > > > If you answer true, then cutting its speed for 90+% of people is bad. > > OK, seems reasonable, assuming that multi-threading cannot be > implemented without a performance hit on single-threaded applications. > Is that a computer science maxim - giving an interpreted language > multi-threading will always negatively impact the performance of > single-threaded applications? > It's not a maxim, per se - it's possible to have lockless concurrency, although when you do this it's more like the shared nothing process approach - but in general, yes. The cost of threading is the cost of the locking needed to ensure safety, and the amount of locking is proportional to the amount of shared state. Most of the common uses of threading in the real world do not improve absolute performance and won't no matter how many cores you use. > > > > | Most people are not currently bothered by the GIL and would not want its > > | speed halved. > > > > And another question: why should such people spend time they do not have to > > make Python worse for themselves? > > > Saying they don't have time to make a change, any change, is always > valid in my book. I cannot argue against that. Ditto for them saying > they don't want to make a change with no explanation. But it seems if > they make statements about why a change is not good, then it is fair > to make a counter-argument. I do agree with the theme of Steven > D'Aprano's comments in that it should be a cordial counter-argument > and not a demand. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From zzbbaadd at aol.com Mon Sep 10 08:37:48 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 10 Sep 2007 05:37:48 -0700 Subject: Python syntax wart In-Reply-To: <5kkp28F46jjuU2@mid.individual.net> References: <1189405211.875217.176620@57g2000hsv.googlegroups.com> <5kkp28F46jjuU2@mid.individual.net> Message-ID: <1189427868.658784.168830@19g2000hsx.googlegroups.com> On Sep 10, 4:45 am, Bjoern Schliessmann wrote: > TheFlyingDutchman wrote: > > It may be that a language that doesn't have a statement terminator > > (which can be end-of-line) needs a statement continuation symbol. > > Which language could that be? I can hardly imagine making a complex > program out of one statement. > > Regards, > > Bj?rn > > -- > BOFH excuse #147: > > Party-bug in the Aloha protocol. Funny how I mentioned end-of-line but didn't include Python as one those languages that used it. I should have said "It may be that a language that doesn't have a statement terminator symbol, but instead uses end-of-line, can't avoid a statement continuation symbol. From steve at REMOVE-THIS-cybersource.com.au Sun Sep 9 04:58:21 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Sep 2007 08:58:21 -0000 Subject: Python syntax wart References: Message-ID: <13e7ddd9hgibae6@corp.supernews.com> On Sun, 09 Sep 2007 17:16:05 +1200, Lawrence D'Oliveiro wrote: > The one thing I don't like about Python syntax is using backslashes to > continue lines. Then don't use them. Put everything in one long line. Or do something like this. Instead of for Link in GetEachRecord("lots", "and", "lots", "of", "arguments"): you can do this: args = ("lots", "and", "lots", "of", "arguments") for Link in GetEachRecord(*args): > Not possible: > > for \ > Link \ > in \ > GetEachRecord \ > ( > "links", > ("from_episode",), > "to_episode = %s", > [EpisodeID], > "order by when_created" > ) \ > : > out.write \ > ( > "

Back to episode %d\n" > % > ( > LinkToMe({"ep" : Link["from_episode"]}), > Link["from_episode"] > ) > ) > #end for That is quite possibly the ugliest piece of code I've ever seen in Python. I'm impressed. Did you format it yourself or did you use a professionally written code-uglifier? Or perhaps I should say: That is quite possibly the ugliest piece of code I ' ve ever seen in Python . # end sentence But have you actually tried it before declaring it isn't possible? After writing a couple of short stub functions, then copy-and-pasting your code, it worked perfectly for me. For the record, here are the stubs I used: class Stub(object): def write(self, *args): print "Stub called" def GetEachRecord(*args): return [{"from_episode": i} for i in range(5)] def LinkToMe(*args): return "stub" out = Stub() EpisodeID = 1234 Now copy the "Not possible" code from Lawrence's original post. Make sure you adjust the indentation of the first line, i.e. there should be no white space before the "for". Paste the whole lot into your Python interpreter, and you should get "Stub called" printed five times. -- Steven. From mulkiatsch at gmail.com Sun Sep 30 12:38:45 2007 From: mulkiatsch at gmail.com (Matthias Benkard) Date: Sun, 30 Sep 2007 09:38:45 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <13frd6vtarbee75@corp.supernews.com> Message-ID: <1191170325.947900.177850@50g2000hsm.googlegroups.com> > So this has nothing to > do with freedom in /any/ sense of the word, it has to do with a > political agenda opposed to the idea of private property. Freedom is inherently political, you know. You're condemning the FSF for being political, although the FSF's stated purpose is a political one. How does that make any sense? ~ Matthias From apardon at forel.vub.ac.be Mon Sep 3 09:43:20 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Sep 2007 13:43:20 GMT Subject: How can I wait for all the threads I spawn for 5 minutes References: <1188603646.671414.272760@w3g2000hsg.googlegroups.com> Message-ID: On 2007-08-31, herman wrote: > Hi, > > In my python program, I would to like to spwan 5 threads, for the them > for 5 minutes maximum and the continue. Here is my script: > > threads = [] > > for j in range(5): > t = MyThread() > threads.append(t) > > for t in threads: > t.join(60*5) > print "thread join\n" > > # wait for 5 minutes for all the threads to complete , > and > # then continue > > But this code ends up waiting 5 minutes for **each** thread. that is > not what I want. I just want to wait for 5 minutes for all threads. > how can I do that? > > And after 5 minutes, i want to kill off all the threads I spawn > earlier, how can I do that in python. You may wish to look at this. No guarantee though. http://groups.google.com/group/comp.lang.python/browse_thread/thread/2002d29c965534cc/5833130893cee567?lnk=st&q=&rnum=2&hl=nl#5833130893cee567 From earnclick at gmail.com Sat Sep 15 04:17:26 2007 From: earnclick at gmail.com (earnclick at gmail.com) Date: Sat, 15 Sep 2007 01:17:26 -0700 Subject: Make money to share your videos Message-ID: <1189844246.297204.249090@o80g2000hse.googlegroups.com> Goodtolove.com is sharing their 50% adsense revenue with you to post videos of anything. Just keep up logging in and start posting now to make money... From ldo at geek-central.gen.new_zealand Sun Sep 9 23:05:30 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 10 Sep 2007 15:05:30 +1200 Subject: Symbolic Link References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> <1187555373.202634.163160@57g2000hsv.googlegroups.com> <1187646982.760523.195750@i38g2000prf.googlegroups.com> <1187879000.370831.118780@j4g2000prf.googlegroups.com> <1o1Fi.33230$RX.26068@newssvr11.news.prodigy.net> Message-ID: In message <1o1Fi.33230$RX.26068 at newssvr11.news.prodigy.net>, samwyse wrote: > A hard-link, OTOH, allows > direct access to the contents of a file, as long as it is on the same > filesystem. No extra steps are required, so the process runs a few > microseconds faster, and directory-level permissions can't get in the way. Hard links are best avoided, because of the confusion they can cause. From tgrav at mac.com Sat Sep 8 20:48:06 2007 From: tgrav at mac.com (Tommy Grav) Date: Sat, 8 Sep 2007 20:48:06 -0400 Subject: Organizing Code - Packages In-Reply-To: <1189296296.175857.158770@22g2000hsm.googlegroups.com> References: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> <46e17143$0$6189$426a74cc@news.free.fr> <1189183088.922537.18290@r34g2000hsd.googlegroups.com> <87r6laa0ir.fsf@rudin.co.uk> <46e1a0bc$0$7689$9b4e6d93@newsspool2.arcor-online.net> <1189280539.449868.169910@22g2000hsm.googlegroups.com> <1189296296.175857.158770@22g2000hsm.googlegroups.com> Message-ID: <5E1563B7-9C9B-4FAE-BBA6-4C1960EC7656@mac.com> On Sep 8, 2007, at 8:04 PM, xkenneth wrote: > > Code doesn't compile in python. This is pseudo code anyways. > Can't post actual code and tracebacks because the code is proprietary. > "MyModule" is pseudo code, and i forgot the arguments, the actual code > and errors are unimportant for this question. The code and traceback is important because the behavior you claim is not easily explained without more information. How are we suppose to help you make your code run, when you can't even properly explain the problem? Cheers Tommy From michele.simionato at gmail.com Wed Sep 19 01:13:12 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 18 Sep 2007 22:13:12 -0700 Subject: super() doesn't get superclass In-Reply-To: <8764281uea.fsf@benfinney.id.au> References: <8764281uea.fsf@benfinney.id.au> Message-ID: <1190178792.662623.164840@o80g2000hse.googlegroups.com> On Sep 18, 12:15 am, Ben Finney wrote: > Howdy all, > > After banging my head against super() trying to reliably get > attributes of a superclass, I gained a little enlightenment when this > turned up in a search: > > "Python's Super is nifty, but you can't use it > (Previously: Python's Super Considered Harmful)" > > > An early paragraph stood out that made my current problems clear: > > One big problem with 'super' is that it sounds like it will cause > the superclass's copy of the method to be called. This is simply > not the case, it causes the next method in the MRO to be called. > > Oh. The author's right, I got that mistaken impression too. Obviously, > then, I must have misread the documentation of 'super'. I went back to > double-check, and was appalled to find: > > super(type[, object-or-type]) > Return the superclass of type. [...] > > > > Why does the documentation of 'super' say that it returns the > superclass when *that's not true*? It doesn't return the superclass, > it returns the next class in the MRO, whether that's a superclass or > not. > > Actually, even that's not true. The error message "AttributeError: > 'super' object has no attribute 'bazfunc'" makes it clear that 'super' > actually returns not the superclass, but a 'super' object, whatever > that's supposed to be. > > After reading the rest of the article, I'm amazed that 'super' as > currently implemented is in Python at all. I agree with the author > that it's useless unless *everyone* uses it for *everything*, and even > then it's pretty limited. > > One thing's for sure, it's badly misnamed, and falsely documented. You are right, I think I even filed a documentation bug for that years ago, and I wrote an entire paper on the subject that however I never published since I never felt 100% confident with super (and I had other fishes to fry ;) I realize now that I was wrong in not publishing it. You can find the draft (warning: it is a draft, I did not check the examples there, they are likely broken) here: http://www.phyast.pitt.edu/~micheles/python/super.html It begins as follows: """ The truth about super Author: Michele Simionato Date: June 2004 Status: Draft super is a new built-in, first introduced in Python 2.2 and slightly improved and fixed in Python 2.3, which is little known to the average Python programmer. One of the reason for this fact is its poor documentation`: at the time of this writing (June 2004) super documentation is incomplete and in some parts misleading and even wrong. For instance, it was recently pointed out on comp.lang.python that the standard library (Python 2.3.4, section 2.1) still says: super(type[, object-or-type]) Return the superclass of type. If the second argument is omitted the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. super() only works for new- style classes. The first sentence is just plain wrong. super does not return the superclass. There is no such a thing as "the" superclass in a Multiple Inheritance (MI) language. Also, the sentence about 'unbound' is misleading, since it may easily lead the programmer to think about bound and unbound methods, whereas it has nothing to do with that concept. Finally, there subtle pitfalls of super which are not at all mentioned. IMNSHO super is one of the most trickiest and surprising Python constructs, so it absolutely needs a document to share light on some of his secrets: the present article aims to fix the issues with the current documentation, and tell you the "truth" about super. At least the amount of truth I have discovered with my experimentations, which is certainly not the whole truth ;) Here is the plan: first I will discuss the concept of superclass in a Multiple Inheritance (MI) world (there is no such a thing as "the" superclass!); second, I will show that super is a proxy object, able to dispatch to the right methods/attributes in the MRO; third, recall some background on how the resolution of methods works on how descriptors work and (essentially pointing out to the standard references); then I will discuss the more common invocation of super - the invocation with two arguments - and finally I will discuss the most tricky part, i.e. invoking super with just one argument and I will discuss pitfalls. Finally, a fair warning: this document is aimed to expert Pythonistas. It is not for the faint of heart ;) """ From evan at yelp.com Wed Sep 12 13:16:38 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 12 Sep 2007 10:16:38 -0700 Subject: Generating HTML In-Reply-To: <46e79b40$0$28082$426a74cc@news.free.fr> References: <9e2f512b0709112133l41ce5ef1g815962a81becf6b9@mail.gmail.com> <46e79b40$0$28082$426a74cc@news.free.fr> Message-ID: <1189617398.5630.0.camel@thinkpad> On Wed, 2007-09-12 at 09:54 +0200, Bruno Desthuilliers wrote: > Evan Klitzke a ?crit : > > It's not applicable for everything, but if you're planning on using > > Python to generate web pages you should really be using Cheetah > > templates. Very simple to use template system that is also very > > powerful, and you don't need to use it in conjunction with a heavy web > > application framework. See http://www.cheetahtemplate.org/ > > > > Same for Mako (http://www.makotemplates.org), which has IMHO a much > nicer syntax (Cheetah looks too much like line noise IMHO). Can you compile Mako templates? This is one thing that I really like about Cheetah, and it wasn't clear to me from the Mako site if this is possible. -- Evan Klitzke From BjornSteinarFjeldPettersen at gmail.com Sat Sep 29 13:58:11 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sat, 29 Sep 2007 10:58:11 -0700 Subject: sorteddict [was a PEP proposal, but isn't anymore!] In-Reply-To: References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190829592.800804.242260@50g2000hsm.googlegroups.com> <1190881576.186259.313720@57g2000hsv.googlegroups.com> <1190897445.179828.291720@y42g2000hsy.googlegroups.com> <1191078696.664214.152350@50g2000hsm.googlegroups.com> Message-ID: <1191088691.380960.151260@d55g2000hsg.googlegroups.com> On Sep 29, 7:13 pm, Duncan Booth wrote: [...] > Right now I think there are probably three dict variants needed: sorteddict > (still waiting for a convincing use case), ordereddict (lots of use cases), > and this one: stabledict. What's stabledict? I'm assuming that ordereddict is a mapping that maintains insertion order(?) The only other mapping type I use very frequently is a dict where the keys are limited to valid identifiers, and where attribute lookup (d.foo) is defined as key lookup (d['foo']). It makes lots of code easier to read (and write). In the Smalltalk collection hierarchy SortedCollection is a subclass of OrderedCollection, which implies to me that it'd be better to add an ordereddict first. -- bjorn From steve at holdenweb.com Tue Sep 11 18:02:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 18:02:54 -0400 Subject: Python Database Apps In-Reply-To: References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> Message-ID: Harry George wrote: > Tom Brown writes: > >> On Monday 10 September 2007 19:52, darien.watkins at gmail.com wrote: >>> Kindof a poll, kindof curiosity... >>> >>> What is your favorite python - database combination? I'm looking to >>> make an app that has a local DB and a server side DB. I'm looking at >>> python and sqlite local side and sql server side. >>> >>> Any suggestions???? >> I have had a lot of good luck with PostgreSQL. It is easy to install and use. >> It is also very stable. It maybe overkill for a client side database. The >> psycopg package makes interfacing to PostgreSQL very easy and there is a >> package for Linux and Windows to make cross-platform development a breeze. >> >> -Tom > > I use postgresql as well. I wonder if Pythonistas do so out of > concern for rigor, clarity, and scalability. It works fine for a > quick one-off effort and still works fine after scaling to a DBMS > server supporting lots of clients, and running 10's of GBs of data. > > If an app comes already designed for mysql, oracle, sqlite, db2, dbm, > etc I'll use those. But for my own projects, it is postgresql, with > maybe SQLAlchemy (I'm back and forth on that. Mostly stay with > straight SQL). > > Of course, as long as you write DBI2 compliant code, your app doesn't > much care which DBMS you use. The postgresql payoff is in admin > functionality and scaling and full ACID. > I also have a tendency to prefer PostgreSQL over MySQL, though I run and use both from time to time as an exercise in application portability. Don't forget, there is absolutely no need to use the same database technology for the client-side and the central repository - sqlite is hard to beat for its simplicity and ease of installations on the client side, and you could look at PostgreSQL for the repository as and when that became a practical proposition. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From aleax at mac.com Sat Sep 8 22:26:50 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 8 Sep 2007 19:26:50 -0700 Subject: Class design (information hiding) References: <42d6c$46e138d3$547078de$10495@news.chello.at> Message-ID: <1i44z4p.fbrtvc1qvlmitN%aleax@mac.com> Gregor Horvath wrote: > Alexander Eisenhuth schrieb: > > > > I'm wodering how the information hiding in python is ment. As I > > understand there doesn't exist public / protected / private mechanism, > > but a '_' and '__' naming convention. > > > > As I figured out there is only public and private possible as speakin in > > "C++ manner". Are you all happy with it. What does "the zen of python" > > say to that design? (protected is useless?) > > My favourite thread to this FAQ: > > > http://groups.google.at/group/comp.lang.python/browse_thread/thread/2c85 > d6412d9e99a4/b977ed1312e10b21#b977ed1312e10b21 Why, thanks for the pointer -- I'm particularly proud of having written """ The only really workable way to develop large software projects, just as the only really workable way to run a large business, is a state of controlled chaos. """ *before* I had read Brown and Eisenhardt's "Competing on the Edge: Strategy as Structured Chaos" (at that time I had no real-world interest in strategically managing a large business -- it was based on mere intellectual curiosity and extrapolation that I wrote "controlled chaos" where B & E have "structured chaos" so well and clearly explained;-). BTW, if you want to read my entire post on that Austrian server, the most direct URL is ... Alex From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 12 03:37:55 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 12 Sep 2007 09:37:55 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> Message-ID: <46e7974d$0$31726$426a74cc@news.free.fr> TheFlyingDutchman a ?crit : > Python user and advocate Bruce Eckel is disappointed with the > additions (or lack of additions) in Python 3: > > http://www.artima.com/weblogs/viewpost.jsp?thread=214112 > I'd say Mr Eckel fails to graps some of the great points about Python's object model - the rant about the use of 'self' is a sure clue. From stefan.behnel-n05pAM at web.de Tue Sep 18 02:56:30 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 18 Sep 2007 08:56:30 +0200 Subject: Extracting xml from html In-Reply-To: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> References: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> Message-ID: <46EF769E.4080103@web.de> kyosohma at gmail.com wrote: > I am attempting to extract some XML from an HTML document that I get > returned from a form based web page. For some reason, I cannot figure > out how to do this. > Here's a sample of the html: > > > > lots of screwy text including divs and spans > > 1126264 > Mitsubishi > Mirage DE > > > > > What's the best way to get at the XML? Do I need to somehow parse it > using the HTMLParser and then parse that with minidom or what? lxml makes this pretty easy: >>> parser = etree.HTMLParser() >>> tree = etree.parse(the_file_or_url, parser) This is actually a tree that can be treated as XML, e.g. with XPath, XSLT, tree iteration, ... You will also get plain XML when you serialise it to XML: >>> xml_string = etree.tostring(tree) Note that this doesn't add any namespaces, so you will not magically get valid XHTML or something. You could rewrite the tags by hand, though. Stefan From michele.simionato at gmail.com Tue Sep 4 00:06:56 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 04 Sep 2007 04:06:56 -0000 Subject: programming by contract using "decorators" In-Reply-To: <1188873829.158006.131900@y42g2000hsy.googlegroups.com> References: <1188873829.158006.131900@y42g2000hsy.googlegroups.com> Message-ID: <1188878816.433034.32010@d55g2000hsg.googlegroups.com> Russ wrote: > Dealing with the arguments was not a trivial matter -- at least not > for me. I had to experiment a bit to get it right. The "getarg" > function is simply a utility for parsing the ordered and keyword > arguments. It's very simple, but if something like this already > exists, please let me know. Thanks. Check out the decorator module at http://www.phyast.pitt.edu/~micheles/python/documentation.html Michele Simionato From bdesth.quelquechose at free.quelquepart.fr Sun Sep 9 11:33:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 09 Sep 2007 17:33:26 +0200 Subject: Python Database Apps In-Reply-To: References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> Message-ID: <46e707f9$0$3308$426a34cc@news.free.fr> Tom Brown a ?crit : > On Monday 10 September 2007 19:52, darien.watkins at gmail.com wrote: > >>Kindof a poll, kindof curiosity... >> >>What is your favorite python - database combination? I'm looking to >>make an app that has a local DB and a server side DB. I'm looking at >>python and sqlite local side and sql server side. >> >>Any suggestions???? > > > I have had a lot of good luck with PostgreSQL. It is easy to install and use. Well... For an experimented (or opiniated) Unix user, at least !-) But I can only second : PgSql is probably one of the best free RDBMS around - one of my previous associates (and still friend !-), who has quite a few years of experience as an Oracle DBA, consider it (pg) as mostly as good as Oracle, and eventually better on some points. My own experience with Pg for web applications is that it JustWorks(tm) - never had a single problem with it. I wish I could say so about MySQL. wrt/ sqlite, I've only used it for small web apps, and the only problem I had was a strange incompatibility bug with first PHP5 versions installed on the same machine. Since I doubt your users will have PHP5 installed on the client machines (!), this should not be a problem. And, while it may takes some time to learn, SQLAlchemy is a very great lib. From xah at xahlee.org Mon Sep 10 09:59:53 2007 From: xah at xahlee.org (Xah Lee) Date: Mon, 10 Sep 2007 06:59:53 -0700 Subject: printing list containing unicode string Message-ID: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> If i have a nested list, where the atoms are unicode strings, e.g. # -*- coding: utf-8 -*- ttt=[[u"?",u"?"], [u"???"],...] print ttt how can i print it without getting the u'\u1234' notation? i.e. i want it print just like this: [[u"?"], ...] I can of course write a loop then for each string use "encode("utf-8")", but is there a easier way? Thx. Xah xah at xahlee.org ? http://xahlee.org/ From lasses_weil at klapptsowieso.net Fri Sep 7 09:59:53 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Fri, 07 Sep 2007 15:59:53 +0200 Subject: unexpected behavior: did i create a pointer? In-Reply-To: References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <46e15959$0$16104$9b4e6d93@newsspool1.arcor-online.net> Steven D'Aprano wrote: > On Fri, 07 Sep 2007 11:46:38 +0200, Wildemar Wildenburger wrote: > >> gu wrote: >>> hi to all! >>> after two days debugging my code, i've come to the point that the >>> problem was caused by an unexpected behaviour of python. or by lack of >>> some information about the program, of course! i've stripped down the >>> code to reproduce the problem: >>> >>> [snip FAQ] >> Yes, basically you *created* a pointer. That's all that python has: >> pointers. > > No, you are confusing the underlying C implementation with Python. I do not, as I have no clue of the C implementation :). I just thought I'd go along with the analogy the OP created as that was his mindset and it would make things easier to follow if I didn't try to forcibly change that. Please note that I had intended for the word 'created' to be in quotes rather than asterisks. I bit myself after I read my mistake online but then thought "Who cares?". I should have, maybe :). And yes, I will admit that going along with that analogy isn't the best way to explain it. Grant Edwards in reply to Peter Otten makes it much clearer, I guess. /W From pavlovevidence at gmail.com Wed Sep 12 16:55:07 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Sep 2007 13:55:07 -0700 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189630374.506503.190690@r34g2000hsd.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> <1i4bnbp.1l8sr3mjdojghN%aleax@mac.com> <1189630374.506503.190690@r34g2000hsd.googlegroups.com> Message-ID: <1189630507.918811.65270@50g2000hsm.googlegroups.com> On Sep 12, 4:52 pm, Carl Banks wrote: > (The loops would necessarily be unwrapped in the actual > bytecode.) And by unwrapped, I mean unrolled. :E3 Carl Banks From mccredie at gmail.com Thu Sep 20 17:38:59 2007 From: mccredie at gmail.com (Matt McCredie) Date: Thu, 20 Sep 2007 14:38:59 -0700 Subject: re question In-Reply-To: References: Message-ID: <9e95df10709201438i2000c972gd6c63864edeb54a1@mail.gmail.com> On 9/19/07, Dan Bar Dov wrote: > I'm trying to construct a regular expression to match valid IP address, > without leading zeroes (i.e > 1.2.3.4, 254.10.0.0, but not 324.1.1.1, nor 010.10.10.1) > > This is what I come up with, and it does not work. > > r'(^[12]?\d{0,2}\.){3,3}[12]?\d{0,2}' > > What am I doing wrong? I'm not sure what affect having the "^" inside of the parens will have, but it surely isn't what you want. This part: r"[12]?\d{0,2}" will match the following strings, which I'm sure you dont' want: "" - yes it will match an empty string (Is "..." a valid IP?) "00" - It could start with a 0, as long as there are only two characters "299" - A little outside of the range you are interested in That {3,3} is better written as {3}. > Any common knowledge IP matching RE? I don't know if there is any common knowledge RE, but I came up with the following: r"((1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){3}(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)") Let us break it down: This matches an octet: r"(1\d{2}|2[0-5]\d|[1-9]\d|\d)" Which will match any ONE of the following 1\d{2} - A "1" followed by any two digits 2[0-4]\d - A "2" followed by 0,1,2,3 or 4 followed by any digit 25[0-5] - A "25" followed by 0,1,2,3,4 or 5 [1-9]\d - Any digit but 0 followed by any digit \d - Any Digit I generally discourage people from using REs. I think the folowing is much easier to read: def isip(x): octs = x.split(".") if len(octs) != 4: return False for oct in octs: if len(oct) > 1 and oct[0] == "0": return False try: if not 0 <= int(oct) < 256: return False except ValueError: return False return True Both solutions seem to work, though I used a small set of test cases. Others may have better suggestions. Matt From hemanthps at gmail.com Wed Sep 19 04:01:26 2007 From: hemanthps at gmail.com (hemanth) Date: Wed, 19 Sep 2007 01:01:26 -0700 Subject: Creating OpenOffice doc's In-Reply-To: References: Message-ID: <1190188886.834811.260350@57g2000hsv.googlegroups.com> Go to http://ooolib.sourceforge.net/ and download the Python version and unzip the file. There are a few examples illustrating various features. I have used this to create simple OO spreadsheets. Regards, Hemanth Sethuram From ricaraoz at gmail.com Wed Sep 26 16:47:58 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 26 Sep 2007 17:47:58 -0300 Subject: Delete values from a string using the index In-Reply-To: <1190838311.630506.64670@y42g2000hsy.googlegroups.com> References: <1190838311.630506.64670@y42g2000hsy.googlegroups.com> Message-ID: <46FAC57E.5090000@bigfoot.com> koutoo at hotmail.com wrote: > How do I delete or remove values from a list or string using the > index. > > If a = [1,2,3,4,5,6,7,8] and I want to get rid of 1 -5, how would I do > that? > > Thanks. > If you want to do it all at once : del a[1:4:2] From martin at v.loewis.de Sat Sep 22 13:29:26 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 22 Sep 2007 19:29:26 +0200 Subject: unicode categories -- regex In-Reply-To: <1190476650.222233.187800@57g2000hsv.googlegroups.com> References: <1190476650.222233.187800@57g2000hsv.googlegroups.com> Message-ID: <46F550F6.3030805@v.loewis.de> > So how do i include this information in regular pattern search? Any > ideas? At the moment, you have to generate a character class for this yourself, e.g. py> chars = [unichr(i) for i in range(sys.maxunicode)] py> chars = [c for c in chars if unicodedata.category(c)=='Po'] py> expr = u'[\\' + u'\\'.join(chars)+"]" py> expr = re.compile(expr) py> expr.match(u"#") <_sre.SRE_Match object at 0xb7ce1d40> py> expr.match(u"a") py> expr.match(u"\u05be") <_sre.SRE_Match object at 0xb7ce1d78> Creating this expression is fairly expensive, however, once compiled, it has a compact representation in memory, and matching it is efficient. Contributions to support categories directly in re are welcome. Look at the relevant Unicode recommendation on how to do that. HTH, Martin From iclark at mail.ewu.edu Fri Sep 21 11:38:07 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Fri, 21 Sep 2007 08:38:07 -0700 Subject: acronym program In-Reply-To: <46F3D8B5.60908@gmail.com> References: <46F3D8B5.60908@gmail.com> Message-ID: Shawn Minisall wrote: > I'm trying to write a program that gets the first letter of every word > of a phrase and prints it on screen. I'm having problems with it. I'm > thinking a for loop would be good since I don't know the exact number of > words the user is going to enter, but after that I get confused. How do > I tell python to just goto the beg of each word in the phrase and > include it in the acronym? Am I on the right track? > > for a in string.split(phrase) > acronym = phrase [0] > acronym = acronym + 1 > > thx List comprehensions[1] to the rescue! >>> phrase = 'hello there i am well how are you?' >>> acronym = [word[0] for word in phrase.split()] >>> acronym ['h', 't', 'i', 'a', 'w', 'h', 'a', 'y'] Ian [1] http://docs.python.org/tut/node7.html#SECTION007140000000000000000 From bj_666 at gmx.net Mon Sep 3 12:42:43 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Sep 2007 16:42:43 GMT Subject: TypeError: 'module object is not callable' References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> Message-ID: <5k2rs3F1t3qcU1@mid.uni-berlin.de> On Mon, 03 Sep 2007 16:13:28 +0000, christophertidy wrote: > Within my main.py file I have > > class Main(object): > stepStore = StepStore() > > @staticmethod > def createDepSteps(): > .... > stepStore.addStep([bol7, pre5]) > ....... > > @staticmethod > def processSteps(): > for step in stepStore.stepList[:]: > ...... > > Main.createDepSteps() > Main.processSteps() What's `Main` useful for? Is Java shining through again? A class with just static methods isn't a class but just a container for functions. But functions usually live in modules in Python so get rid of that class and move the functions to module level. > Trying this approach I am getting a error saying with the > processSteps() method, stepStore is undefined `stepStore` is searched in the function and then in the module. But it is defined in the class. So you have to access `Main.stepStore`. Unless you are modifying `stepStore.stepList` while iterating over it, you don't need to make a copy by the way. Ciao, Marc 'BlackJack' Rintsch From hat at se-162.se.wtb.tue.nl Wed Sep 19 08:18:30 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 19 Sep 2007 14:18:30 +0200 Subject: How can I know how much to read from a subprocess References: <1190070896.332844.23080@22g2000hsm.googlegroups.com> <1190072376.600475.254260@y42g2000hsy.googlegroups.com> <1190130585.255648.312730@q3g2000prf.googlegroups.com> Message-ID: On 2007-09-18, spam.noam at gmail.com wrote: > On Sep 18, 1:48 pm, "A.T.Hofkamp" wrote: >> On 2007-09-17, spam.n... at gmail.com wrote: >> >> > It seems that another solution is gobject.io_add_watch, but I don't >> > see how it tells me how much I can read from the file - if I don't >> > know that, I won't know the argument to give to the read() method in >> > order to get all the data: >> >> >http://www.pygtk.org/docs/pygobject/gobject-functions.html#function-g... >> >> Usually, gobject only tells you that data is there (that is all it knows). >> Therefore a read(1) should be safe. > > But even if it's fast enough, how do you know how many times you > should call read(1)? If you do it too much, you'll be blocked until > more output is available. after reading 1 byte, wait for gobject again. In other words, when gobject sends a notice, read 1 byte. When there is more, gobject will tell you (probably very often :-) ). > >> If that is too slow, consider os.read() which reads all data available (afaik, >> never tried it myself). >> > I tried it now, and it blocks just like the normal file.read(). So "os.read(handle.fileno(), 1000000)" blocks after gobject tells you there is data? That is different than I heard, but you are probably correct, I cannot easily test this. Albert From arnau at ehas.org Sat Sep 15 09:56:40 2007 From: arnau at ehas.org (Arnau Sanchez) Date: Sat, 15 Sep 2007 15:56:40 +0200 Subject: how to join array of integers? In-Reply-To: References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> Message-ID: <46EBE498.9040800@ehas.org> js escribi?: >> On 9/15/07, Summercool wrote: >> in Python... is the method to use ",".join() ? but then it must take >> a list of strings... not integers... >> >> any fast method? > print ''.join([str(i) for i in [1,2,3]]) It's better to use generator comprehension instead of LC: ",".join(str(i) for i in [1, 2, 3]) Or, if you happen to like the itertools modules: from itertools import imap ",".join(imap(str, [1, 2, 3])) From michele.simionato at gmail.com Wed Sep 12 00:50:21 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 11 Sep 2007 21:50:21 -0700 Subject: Basic GUI In-Reply-To: <1189569282.372083.264560@57g2000hsv.googlegroups.com> References: <1189569282.372083.264560@57g2000hsv.googlegroups.com> Message-ID: <1189572621.451715.280680@r34g2000hsd.googlegroups.com> On Sep 11, 11:54 pm, Don Hanlen wrote: > I could solve my problems with the following psuedo-code made into > real code: > ---- > import blah > > t = blah.fork(runthisprogram.py) > > #OK still in main > t.sendinfo(info) > info = t.receiveinfo() > ---- > #runthisprogram.py > def sendinfobacktopapa(): > ? eventhere > def getinfofrompapa(): > ? eventhere > ---- > > It seems to me that propagating events *may* be the best way to > communicate. I'm wide open, including to non-multi-process solutions. > > Thanks for your comments, I searched old posts for a while, various > other Python info-sources, and couldn't find an answer. > -- > don Have a look at the 'processing' module. Michele Simionato From evan at yelp.com Wed Sep 12 01:49:59 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 11 Sep 2007 22:49:59 -0700 Subject: 2 daemons write to a single file /w python file IO In-Reply-To: References: Message-ID: <1189576199.5842.10.camel@thinkpad> On Tue, 2007-09-11 at 21:17 -0700, Andrey wrote: > HI > > i have a newbie question about the file() function. > I have 2 daemons running on my linux box. > > 1 will record the IDs to a file - logs.txt > other 1 will open this file, read the IDs, and then "Clean up the > file" -logs.txt > > Since these 2 daemons will run every 2-5mins, I think this will crash, isn't > it? When both daemons try to write to the file at the same time. They will not crash. If you're writing a small amount of data using os.write (e.g. a line or two at a time), the writes will probably end up being atomic, and you don't have to worry about anything. This isn't guaranteed of course, but if you're not writing out large buffers you probably don't need to worry about it at all. The worst case scenario is that the writes will be interleaved (e.g. daemon 1 writes "foo", daemon 2 writes "bar", and what ends up in the file is something like "fbaroo"), there is not danger of crashing. The regular write method of file objects is buffered, so I'd imagine that is more likely to have this problem. > I am wondering if this won't crash, OR if there is some simple high-level > functions can lock the file while writing... There is a standard syscall in POSIX system that does real file locking -- it's called flock. You can access it using the fcntl module as fcntl.flock. The man page for flock has more details. Basically what you need to do is call fcntl.flock before writing to the file in each of your processes. The process will block until the lock is released. On Linux the lock will be advisory only, so if you don't use flock everywhere you can still have multiple processes with the file descriptor open and writable at once. > I also wonder if one side locked the file, what happens if the other side > try to open this locked file? raise error? so i also need to write a loop to > wait for the file to release locking? The flock call will block if the file is already locked. -- Evan Klitzke From aleax at mac.com Sun Sep 2 14:46:51 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 2 Sep 2007 11:46:51 -0700 Subject: Adding attributes stored in a list to a class dynamically. References: Message-ID: <1i3t9va.1jkz4om1sajk8pN%aleax@mac.com> Nathan Harmston wrote: > Hi, > > Sorry if the subject line of post is wrong, but I think that is what > this is called. I want to create objects with > > class Coconuts(object): > def __init__(self, a, b, *args, **kwargs): > self.a = a > self.b = b > > def spam( l ) > return Coconuts( l.a, l.b, l.attributes ) > > l in a parse line of a file which is a tuple wrapped with > attrcol......with attributes a, b and attributes (which is a list of > strings in the format key=value ie... > [ "id=bar", "test=1234", "doh=qwerty" ] ). > > I want to add attributes to Coconuts so that I can do > print c.id, c.test, c.doh > > HOwever I m not sure how to do this: > > how can i assign args, kwargs within the constructor of coconuts and > how can I deconstruct the list to form the correct syntax to be able > to be used for args, kwargs. If you want to pass the attributes list it's simpler to do that directly, avoiding *a and **k constructs. E.g.: def __init__(self, a, b, attrs): self.a = a self.b = b for attr in attrs: name, value = attr.split('=') setattr(self, name, value) You may want to add some better error-handling (this code just raises exceptions if any item in attrs has !=1 occurrences of the '=' sign, etc, etc), but I hope this gives you the general idea. Note that you'll have trouble accessing attributes that just happen to be named like a Python keyword, e.g. if you have "yield=23" as one of your attributes you will NOT be able to just say c.yield to get at that attribute. Also, I'm assuming it's OK for all of these attributes' values to be strings, etc, etc. Alex From hpepper at gmail.com Tue Sep 11 06:20:21 2007 From: hpepper at gmail.com (HowiPepper) Date: Tue, 11 Sep 2007 03:20:21 -0700 Subject: why should I learn python In-Reply-To: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: <1189506021.315340.108490@y42g2000hsy.googlegroups.com> On Sep 6, 5:32 pm, windandwaves wrote: > Can someone tell me why I should learn python? I am a webdeveloper, > but I often see Python mentioned and I am curious to find out what I > am missing out on. > > Thank you > > Nicolaas Nicholaas, There are many reasons to learn Python, and few not to. I'm another one of those "multiple language" programmers, and have worked in C/C++ (yes, both of them), Java, Pascal (and Delphi), BASIC (and it's Visual cousin), Clipper, Perl, PHP and Python (and a couple of dialects of Unix shell scripting as well). I started working in Perl back in 1998, mainly for web development. Since then, I've done just about anything possible you can do with Perl, and used it as my "Swiss army chainsaw" for practically anything I needed to do. I got a contract with IBM, back in May of 2005, and soon found out the group I worked with used Python for all of it's "discretionary" development. I started reading "A Byte of Python", and was soon hooked. I spent the next two years using Python as my exclusive scripting language. And by scripting, I mean anything from one or two line throw-aways, to major programs. Python makes it so easy to build like that! My new job, which I started several months ago, put me squarely back in the Perl realm. Now I really miss Python! I've discussed with my supervisor porting all of our Perl scripts over to Python, and he is receptive, but I'm not holding my breath :-( For now, I use Perl and shell at work, and Python (and shell) at home. Python is just so much nicer than any other language I've developed in. Once you get the swing of it (no pun intended), you will find you're way more productive, your programs turn out better and are much easier to go back to six months or a year later, and work with. Right now, I'm going through Perl hell, trying to figure out what the heck the past two guys did and why! ;-) Regards, Howard From mail at timgolden.me.uk Thu Sep 6 07:58:10 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 06 Sep 2007 12:58:10 +0100 Subject: How to do python and RESTful In-Reply-To: References: <1189022079.403495.175800@g4g2000hsf.googlegroups.com> Message-ID: <46DFEB52.3090806@timgolden.me.uk> [MarkyMarc] >> I have be looking at quixote, but is this uptodate? "plain" >> mod_python, can this make url to http put,get,delete and post? [Steve Holden] > Would you care to explain why quixote needs to be "uptodate"? Surely it > either does what you want or it doesn't? If it dies, then it hardly > matters how "up to date" it is. Are you also concerned that some parts > of Python remains unchanged since before 1.5.2, now almost tne years old? FWIW, I have used Quixote on two (v. small-scale) production websites, both started several years ago when there were fewer web toolkits in the Python universe. Every so often I consider reworking one or other of them into one of the newer (read: more recently noised about) toolkits/frameworks. But they work fine as they are, so why bother? As a matter of fact, one uses Quixote v1, the other uses v2 which occasionally throws me when I'm doing some work on both at the same time! TJG From rups77 at gmail.com Thu Sep 27 14:05:44 2007 From: rups77 at gmail.com (Recruiter-Adobe) Date: Thu, 27 Sep 2007 11:05:44 -0700 Subject: HOT!!!PYTHON DEVELOPER REQUIRED @ ADOBE SYSTEMS Message-ID: <1190916344.841925.94900@57g2000hsv.googlegroups.com> Hi PYTHON DEVELOPERS, ADOBE SYSTEMS is looking for a PYTHON DEVELOPER who can troubleshoot Python based applet which makes data base queries and populates Excel tables used to generate pivot charts, graphs and tables showing bug metrics. Isolate problem which is causing reports to crash and institute fix. This is a position through Manpower at our customer Adobe Systems, you will be employed as a Manpower's contractor. Job Responsibilities: ? Setup a new server (development environment) ? Install updated versions of both python and other plugins used for our applet. ? Import Code/applet instance. ? Remove code that uploads it to the Production Server Instance ? Eventually move the entire Production Instance over to the newer server. ? Update Code to comply with the latest Python standards Knowledge & Skills: ? Expert in Python Programming ? Experience in COM Object programming speficially Excel COM Objects ? Experience in using WebServices (SOAP) ? Win2k System Administration Experience a Plus ? Need to migrate from version 2.3 to latest version of Python Hourly Pay rate: $85-$100/hr If interested, please send a Word copy of your resumeto rbadame at manpowersj.com with your expected hourly rate, availability, visa status, best time and phone # to contact you. From hat at se-162.se.wtb.tue.nl Thu Sep 13 03:11:39 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 13 Sep 2007 09:11:39 +0200 Subject: Parallel/Multiprocessing script design question References: Message-ID: On 2007-09-13, Amit N wrote: > Hi guys, > > I tend to ramble, and I am afraid none of you busy experts will bother > reading my long post, so I will try to summarize it first: I haven't read the details, but you seem to aim for a single python program that does 'it'. A single sequential thread is not fast enough, so you want parallel execution (and yes there are a zillion ways of doing that). Why don't you start at the other end? Write a program for each task that you have, then fork/spawn/chain/whatever enough processes at OS level to eat all your data. The OS is usually much better at balancing CPU's. The Python module 'subprocess' would be your friend in that case. In addition, you can run each program independently, which will come in handy one day. Sincerely, Albert From __peter__ at web.de Wed Sep 12 05:17:14 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Sep 2007 11:17:14 +0200 Subject: Get Only the Last Items in a Traceback References: <1189562968.529414.27910@w3g2000hsg.googlegroups.com> Message-ID: Am Wed, 12 Sep 2007 02:09:28 +0000 schrieb gregpinero at gmail.com: > I'm running code via the "exec in context" statement within a much > larger program. What I would like to do is capture any possible > errors and show a pretty traceback just like the Python interactive > interpreter does, but only show the part of the traceback relating to > the code sent to exec. > > For example here is the code I'm using: > > try: > exec code > except Exception,Err: > traceback.print_exc() > > Which gives me something like this when it catches an exception: > > Traceback (most recent call last): > File "/....py", line 843, in run > semi_safe_exec.safe_eval(code.replace('\r',''),context,5) > File ".....py", line 400, in safe_eval > exec_timed(code, context, timeout_secs) > File ".....py", line 353, in exec_timed > exec code in context > File "", line 7, in ? > File "", line 5, in func2 > File "", line 2, in func1 > ZeroDivisionError: integer division or modulo by zero > > What I want to print instead is just something like: > > Traceback (most recent call last): > File "", line 7, in ? > File "", line 5, in func2 > File "", line 2, in func1 > ZeroDivisionError: integer division or modulo by zero > > Thanks in advance for the help. > > -Greg > > P.S. if it matters, for this example, code in exec code is: > > def func1(): > print 7/0 > > def func2(): > func1() > > func2() Your assessment is wrong. You only get the extra lines in the traceback if you don't immediately wrap the exec statement in a try ... except block: $ cat snip_traceback1.py import traceback def alpha(): try: beta() except Exception, e: traceback.print_exc() def beta(): gamma() def gamma(): exec s in {} s = """ def delta(): epsilon() def epsilon(): 1/0 delta() """ if __name__ == "__main__": alpha() $ python snip_traceback1.py Traceback (most recent call last): File "snip_traceback1.py", line 5, in alpha beta() File "snip_traceback1.py", line 10, in beta gamma() File "snip_traceback1.py", line 13, in gamma exec s in {} File "", line 7, in File "", line 3, in delta File "", line 6, in epsilon ZeroDivisionError: integer division or modulo by zero So the first step is to move the try ... except closer to the exec: $ cat snip_traceback2.py import traceback def alpha(): beta() def beta(): gamma() def gamma(): try: exec s in {} except Exception, e: traceback.print_exc() s = """ def delta(): epsilon() def epsilon(): 1/0 delta() """ if __name__ == "__main__": alpha() $ python snip_traceback2.py Traceback (most recent call last): File "snip_traceback2.py", line 11, in gamma exec s in {} File "", line 7, in File "", line 3, in delta File "", line 6, in epsilon ZeroDivisionError: integer division or modulo by zero You are almost there. Now let's strip off the outermost traceback: $ cat snip_traceback3.py import sys import traceback def alpha(): beta() def beta(): gamma() def gamma(): try: exec s in {} except Exception, e: etype, value, tb = sys.exc_info() traceback.print_exception(etype, value, tb.tb_next) s = """ def delta(): epsilon() def epsilon(): 1/0 delta() """ if __name__ == "__main__": alpha() $ python snip_traceback3.py Traceback (most recent call last): File "", line 7, in File "", line 3, in delta File "", line 6, in epsilon ZeroDivisionError: integer division or modulo by zero Heureka. Peter From mail at timgolden.me.uk Thu Sep 27 07:57:34 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Sep 2007 12:57:34 +0100 Subject: Cross-platform time out decorator In-Reply-To: <1190802115.585306.250400@o80g2000hse.googlegroups.com> References: <1190802115.585306.250400@o80g2000hse.googlegroups.com> Message-ID: <46FB9AAE.9070606@timgolden.me.uk> Joel wrote: > I've been using this nice timing out decorator : > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871 . The > problem is that since it relies on sigalarm, it doesn't work under > windows. Would anyone know how to do a cross-platform version? I don't think you're going to find anything straightforward. AFAIK, there's nothing on the Windows side of things which is directly equivalent to the signals business in *nix. Sure, you can mess around with timers and threads and events and so on. But it's far from being the built-in tool which the signal module gives you. TJG From rgilbert88 at comcast.net Sun Sep 2 11:18:11 2007 From: rgilbert88 at comcast.net (Richard B. Gilbert) Date: Sun, 02 Sep 2007 11:18:11 -0400 Subject: Let's Unite Against Jews and Mongrels! References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> <1188300284.507909.126770@57g2000hsv.googlegroups.com> <46D40BFE.2020301@comcast.net> <1188744204.822322.198360@57g2000hsv.googlegroups.com> Message-ID: <46DAD433.1030503@comcast.net> Zentrader wrote: > On Aug 28, 4:50 am, "Richard B. Gilbert" > wrote: > >>>Unless, of course, someone has a working "Killbot". If anyone has such >> >>a thing, please kill that "MI5victim" moron as well! > > > I reported MI5victim to spam at uce.gov and it appears to be gone, as > well as the "free air conditioner"'s posts. (Thanks Steve Holden for > the reminder that it doesn't have to be personal e-mail spam in order > to be reported). If the OP posts again, report it. Something like 75% > of internet mail is spam. > MI5victim was alive and (I won't say well!!) a week ago. It remains to be seen if he's gone. And if you believe that reporting spam to spam at uce.gov actually has any effect on spam, you must believe in the Tooth Fairy as well! There will be spam as long as there are morons who will send the spammers money for whatever they're peddling! I still get two or three "Spanish Prisoner" a/k/a "401" scams each week (this is the one where somebody has $30,000,000 US and will share it with you if only you will send him a little of your money)! The US government does seem to have cracked down on the "Pharmacy" spam and the internet "pharmacies" that were behind it. Remember, it costs essentially nothing to send spam to 30,000,000 people and if the spammer gets 0.5% response, he's ahead of the game! From robert.rawlins at thinkbluemedia.co.uk Mon Sep 24 07:23:25 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 24 Sep 2007 12:23:25 +0100 Subject: Almost There - os.kill() Message-ID: <002601c7fe9d$52ffb9c0$f8ff2d40$@rawlins@thinkbluemedia.co.uk> Hello Guys, Finally got around to sitting down to tidy up this script this morning but I'm having a small syntax problem with os.kill() to kill a process on my system. Here is the code: def killApplication(): pid = file('/var/lock/MyApplication.lock').read().strip() logging.info('Killing Application Process: %s' % pid) os.kill(pid, 15) logging.info('Application %s Killed' % pid) As you can see if rips the PID from the lock file, which works fine as I get log data which says 'Killing Application Process: 3079' exactly as I would expect it too. However when I run this script I get the following error: Traceback (most recent call last): File "/pblue/new/Alive.py", line 50, in ? main() File "/pblue/new/Alive.py", line 47, in main doCheck() File "/pblue/new/Alive.py", line 43, in doCheck killApplication() File "/pblue/new/Alive.py", line 28, in killApplication os.kill(pid, 15) TypeError: an integer is required Which would suggest its passing those arguments in as the wrong data types to the kill command. What is the best way to convert these? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From Erik-wikstrom at telia.com Sun Sep 30 07:50:07 2007 From: Erik-wikstrom at telia.com (=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?=) Date: Sun, 30 Sep 2007 11:50:07 GMT Subject: which language allows you to change an argument's value? In-Reply-To: <1191149233.346818.246170@22g2000hsm.googlegroups.com> References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> Message-ID: On 2007-09-30 12:47, Summercool wrote: > I wonder which language allows you to change an argument's value? > like: > > foo(&a) { > a = 3 > } > > n = 1 > print n > > foo(n) # passing in n, not &n > print n > > and now n will be 3. I think C++ and PHP can let you do that, using Since you know C++ can do it why do you include c.l.c++? Honestly cross- posting to groups discussing so many different groups is seldom a good idea since the languages differ too much for a useful discussion. > their reference (alias) mechanism. And C, Python, and Ruby probably > won't let you do that. What about Java and Perl? C will let you do it with pointers (it is just a syntactical difference from references in this case) and Java's references allows it. I do not know about Ruby, Python and Perl, but (AFAIK) the all have OO support so I would be surprised if they used purely value semantics. > is there any way to prevent a function from changing the argument's > value? Some languages, like C++ have the ability to make an argument const. > isn't "what i pass in, the function can modify it" not a desireable > behavior if i am NOT passing in the address of my argument? For one Being able to pass the actual object instead of a copy is highly desirable for two reasons. In most languages only one return value is allowed for a function so the ability to change parameters allows you to artificially return more without having to wrap them in constructs. The second reason is that for large objects the performance hit of having to create a copy each time you call a function can be forbidding. > thing, if we use a module, and call some functions in that module, and > the module's author made some changes to his code, then we have no way > of knowing what we pass in could get changed. Of course, if it is in As for knowing when a library function modifies an argument or not, well that is why we have documentation. > Java, Python, and Ruby, and we pass in a reference to object (not C+ > +'s meaning of alias reference) In what way does the C++ reference differ from those in Java, Python, and Ruby in this situation? -- Erik Wikstr?m From byte8bits at gmail.com Fri Sep 21 14:39:45 2007 From: byte8bits at gmail.com (byte8bits at gmail.com) Date: Fri, 21 Sep 2007 18:39:45 -0000 Subject: RE Help Message-ID: <1190399985.324448.242610@d55g2000hsg.googlegroups.com> Not specific to Python, but it will be implemented in it... how do I compile a RE to catch everything between two know values? Here's what I've tried (but failed) to accomplish... the knowns here are START and END: data = "asdfasgSTARTpruyerfghdfjENDhfawrgbqfgsfgsdfg" x = re.compile('START.END', re.DOTALL) x.findall(data) From steve at holdenweb.com Tue Sep 11 08:24:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 08:24:39 -0400 Subject: function to do dynamic import? In-Reply-To: <13ecb84p1ghrd64@corp.supernews.com> References: <13ecb84p1ghrd64@corp.supernews.com> Message-ID: bambam wrote: > import works in the main section of the module, but does > not work as I hoped when run inside a function. > > That is, the modules import correctly, but are not visible to > the enclosing (global) scope. > > Questions: > (1) Where can I read an explanation of this? > (2) Is there a work around? > > BTW, sys.modules("filename") shows that the module is > loaded, I just don't know how to use it when loaded that > way. Also, if I import again at the global scope, the module > name becomes available. > There's not much wrong with doing this, since it gives you the best of both worlds. But you mean sys.modules["filename"], don't you? >>>> def gim(): > ... exec "import gamel" > ... >>>> gim() >>>> sys.modules["gamel"] > >>>> gamel > NameError: name 'gamel' is not defined >>>> exec "import gamel" >>>> gamel > > > Whoa there! There's a lot of difference between "importing a module inside a function" and "executing an import statement inside a function". If you want to do dynamic imports then the __import__ function is what you need. Trying to use exec like that is a bad idea unless you clearly understand the relationship between the different namespaces involved. In fact, trying to use exec at all is a bad idea until you understand Python better, and even then it's not often a terrific idea. Think of exec more as a hack of last resort than the first tool to reach for to solve a problem. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From orsenthil at gmail.com Wed Sep 5 11:39:13 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Wed, 5 Sep 2007 21:09:13 +0530 Subject: PythonAlley.com In-Reply-To: <2dc0c81b0709050727q7e56e99dnf8918e7d143d53a@mail.gmail.com> References: <2dc0c81b0709050727q7e56e99dnf8918e7d143d53a@mail.gmail.com> Message-ID: <20070905153913.GD3437@gmail.com> * Shawn Milochik [2007-09-05 10:27:08]: > I bought the domain PythonAlley.com (and PerlAlley.com and > > Does anyone have any ideas as to what a wonderful use for > PythonAlley.com would be? I'd really like to do something with at If "you" don't have an idea, most likely others wont have as well. :) -- O.R.Senthil Kumaran http://uthcode.sarovar.org From info at thegrantinstitute.com Sat Sep 29 05:37:47 2007 From: info at thegrantinstitute.com (Anthony Jones) Date: 29 Sep 2007 02:37:47 -0700 Subject: Professional Grant Proposal Writing Workshop (December 2007: University of Washington, Seattle) Message-ID: <20070929023747.42F41735AAA57F03@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From amitsafe1 at gmail.com Thu Sep 13 06:55:51 2007 From: amitsafe1 at gmail.com (amit) Date: Thu, 13 Sep 2007 03:55:51 -0700 Subject: Make money to share your videos Message-ID: <1189680951.542069.25890@22g2000hsm.googlegroups.com> Make money to share your videos Goodtolove.com is sharing their 50% adsense revenue with you to post videos of anything. Just keep up logging in and start posting now to make money... From vincent.sabard at amadeus.com Thu Sep 27 10:37:06 2007 From: vincent.sabard at amadeus.com (Vincent Sabard) Date: Thu, 27 Sep 2007 16:37:06 +0200 Subject: Getting web page throught a proxy (squid) Message-ID: salut jean-paul, comment vas-tu ? vincent sabard. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zzbbaadd at aol.com Wed Sep 12 20:53:23 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 12 Sep 2007 17:53:23 -0700 Subject: Coming from Perl In-Reply-To: References: Message-ID: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> On Sep 12, 5:30 pm, Amer Neely wrote: > I'm a complete newbie with Python, but have several years experience > with Perl in a web environment. > > A question I have, if someone here is familiar with Perl, does Python > have something like Perl's 'here document'? I've just searched and read > some postings on generating HTML but they all seem to refer to various > template utilities. Is this the only way, or am I missing something? I'm > used to generating X/HTML by hand, which makes the here document in Perl > ideal for me. Also, many times a client already existing HTML code that > I can use in a script. > > -- > Amer Neely > w:www.webmechanic.softouch.on.ca/ > Perl | MySQL programming for all data entry forms. > "Others make web sites. We make web sites work!" I am not sure if this is what you are looking for, but Python has a special string with 3 quotes that I believe duplicates part of the functionality of a here document: myHmtlHeader = """ My Page """ print myHtmlHeader outputs: My Page From gagsl-py2 at yahoo.com.ar Sun Sep 9 17:17:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Sep 2007 18:17:42 -0300 Subject: os.sep and os.path.sep References: <1189352918.534864.195850@g4g2000hsf.googlegroups.com> Message-ID: En Sun, 09 Sep 2007 12:48:38 -0300, billiejoex escribi?: >>>> import os >>>> hasattr(os, 'sep') > True >>>> hasattr(os.path, 'sep') > True > > By chance I noticed it. > Are there differences (I think not...)? > IMHO, if there are no differences os.path.sep should be removed since > it may be confusing. They are the same, as documented on http://docs.python.org/lib/os-path.html#l2h-2796 And why do you think os.path.sep would be confusing? -- Gabriel Genellina From mail at microcorp.co.za Sat Sep 22 03:40:31 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 22 Sep 2007 09:40:31 +0200 Subject: Writing Object Data to Disk References: <1190443648.5838.6.camel@ubuntu-laptop> Message-ID: <017501c7fceb$f0093d80$03000080@hendrik> "Amit Kumar Saha" wrote: > I would like to know if "Pickling" the class object is the only way of > writing it to disk for persistent storage. look at marshall and shelve >...........................................................Also, do we have a concept > similar to "array of objects" in Python? The number of objects is only > known at "run-time". I would use a list - Hendrik From aahz at pythoncraft.com Thu Sep 27 22:14:23 2007 From: aahz at pythoncraft.com (Aahz) Date: 27 Sep 2007 19:14:23 -0700 Subject: Python 3.0 migration plans? References: Message-ID: In article , Steve Holden wrote: > >I wondered if a straw poll could get some idea of readers' thoughts >about when they will be migrating to 3.0 on, so I used the new widget on >Blogger to add a poll for that. > >I'd appreciate if if you would go to > > http://holdenweb.blogspot.com/ > >and register your vote on your intended migration timescale. Does this require JavaScript? If yes, count me as another "no" vote on your survey. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From welcomestocontact at gmail.com Wed Sep 19 06:11:48 2007 From: welcomestocontact at gmail.com (welcomestocontact at gmail.com) Date: Wed, 19 Sep 2007 03:11:48 -0700 Subject: HTTP Protocol Client Message-ID: <1190196708.261138.233490@e9g2000prf.googlegroups.com> Hi, I am writing http protocol to get some data from servers. If i was using my localhost, getting replay from local and if want access other remote sites, i am getting error. Please reply it My localhost client script::: Code: ( python ) import httplib h = httplib.HTTP('localhost',80) h.putrequest('GET','') h.putheader('User-Agent','Lame Tutorial Code') h.putheader('Accept','text/html') h.endheaders() errcode,errmsg, headers = h.getreply() print errcode,errmsg, headers f = h.getfile() # Get file object for reading data data = f.read() print data f.close() the Reply getting from this:::: 403 Forbidden Date: Tue, 18 Sep 2007 05:20:36 GMT Server: Apache/2.0.52 (Red Hat) Accept-Ranges: bytes Content-Length: 3985 Connection: close Content-Type: text/html; charset=UTF-8 And some Html script If I want to access other sites::: import httplib h = httplib.HTTP('http://Google.com',80) h.putrequest('GET','') h.putheader('User-Agent','Lame Tutorial Code') h.putheader('Accept','text/html') h.endheaders() errcode,errmsg, headers = h.getreply() print errcode,errmsg, headers f = h.getfile() # Get file object for reading data data = f.read() print data f.close() I got the error like::: Traceback (most recent call last): File "c.py", line 6, in ? h.endheaders() File "/usr/lib/python2.3/httplib.py", line 712, in endheaders self._send_output() File "/usr/lib/python2.3/httplib.py", line 597, in _send_output self.send(msg) File "/usr/lib/python2.3/httplib.py", line 564, in send self.connect() File "/usr/lib/python2.3/httplib.py", line 532, in connect socket.SOCK_STREAM): socket.gaierror: (-2, 'Name or service not known') How can I access Remote sites using http protocol . I did'nt write server script. Thanks And Regards Allavarapu From mickey at disney.com Mon Sep 10 21:12:13 2007 From: mickey at disney.com (Wiseman) Date: Mon, 10 Sep 2007 21:12:13 -0400 Subject: Python Problem References: Message-ID: <0pqbe3t2hha91m4oiaesqrtpkspn7n6t4r@4ax.com> Carsten. I want to thank you for your help. I could not check this until this morning. Now that I checked your answer - THANK YOU. I do have 2 installations of Python on my machine. Once I called Python with a full path - my program orked as expected. Meir From fd.calabrese at gmail.com Sun Sep 16 05:56:04 2007 From: fd.calabrese at gmail.com (cesco) Date: Sun, 16 Sep 2007 09:56:04 -0000 Subject: generate list of partially accumulated values Message-ID: <1189936564.932553.148800@50g2000hsm.googlegroups.com> Hi, I have the following list: l = [1, 2, 3, 4] and I'd like to obtain a list like the following: l_partial_sum = [1, 3, 6, 10] (that is [1, 1+2, 1+2+3, 1+2+3+4]) Is there a simple way to accomplish this? I came up with the following solution but it seems a bit too elaborated for the task: l_partial_sum = [reduce(lambda x,y:x+y, sub_l) for sub_l in [l[:i+1] for i in range(len(l))]] Any help will be appreciated. Thanks Francesco From steve at REMOVE-THIS-cybersource.com.au Fri Sep 21 21:17:48 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 22 Sep 2007 01:17:48 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> Message-ID: <13f8r9sj0b9q94e@corp.supernews.com> On Fri, 21 Sep 2007 22:07:55 +0000, Cristian wrote: > True, there is lambda, but that is very limited. It might be useful for > key arguments, but not much else. No, lambda is useful for anything that any other function is useful for, provided that you can write it as a single expression and not need to use statements. In other words, a lambda function can do anything anything any other function can, just less conveniently. (To pick one example at random, you can use print with lambda: http://northernplanets.blogspot.com/2006/07/python-using-print-with-lambda.html and while it is easy it isn't exactly convenient.) And that's basically why function definitions have the syntax they do, because trying to hammer a multi-line function definition into a single expression is painful. > It doesn't solve the teaching problem > of "See, functions are just like any other data type. You can assign it > to a variable." Is their interactive interpreter broken? >>> def parrot(colour='red'): ... return "I'm a parrot with %s plumage." % colour ... >>> bird = parrot # note the lack of brackets >>> type(bird) >>> bird('green') "I'm a parrot with green plumage." Or using lambda: >>> parrot = lambda colour: "I'm a parrot with %s plumage." % colour >>> parrot("purple") "I'm a parrot with purple plumage." > It would be a footnote if it's mentioned at all. My hope > is to subtly reinforce the notion that functions are data and can be > passed around. The current function declaration doesn't help with this. Some things just need to be learnt. I'm in favour of making languages easy for newbies to learn, but making function and method definitions harder to use just so newbies will be given a subtle reminder of something that 80% of them will never notice or use anyway is a bad trade-off. > Creating a function and assigning it to a name is exactly what Python > does, why not have it come out in the syntax? It's not necessary, yes, > but I think it would be helpful for teaching purposes. If people don't get it when you EXPLICITLY show them that functions are first-class objects, how do you expect them to notice it on their own based on the IMPLICIT similarities in syntax? -- Steven. From andrewthommo at gmail.com Mon Sep 17 20:33:17 2007 From: andrewthommo at gmail.com (Andrew Thompson) Date: Mon, 17 Sep 2007 17:33:17 -0700 Subject: Free trips around the globe!!!!!!!!!! In-Reply-To: <1190055580.004195.87900@k79g2000hse.googlegroups.com> References: <1190054010.350444.11150@19g2000hsx.googlegroups.com> <1190055580.004195.87900@k79g2000hse.googlegroups.com> Message-ID: <1190075597.165511.127820@50g2000hsm.googlegroups.com> On Sep 18, 4:59 am, lilly wrote: > On Sep 17, 2:33 pm, nutsbreak... at gmail.com wrote: > > >http://world-traveling-destinations.SPAMpot.com/ > > this is .. ..widely cross-posted *spam*. [ F'Ups set to c.l.j.p. only. ] From jjl at pobox.com Sat Sep 22 03:20:25 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 22 Sep 2007 07:20:25 GMT Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87odfxjgjy.fsf@pobox.com> <7x4phpt9nf.fsf@ruckus.brouhaha.com> Message-ID: <87wsuj4152.fsf@pobox.com> Paul Rubin writes: > jjl at pobox.com (John J. Lee) writes: >> Seriously for a moment, I read something recently (maybe here?) about >> an Apple study that claimed to show that people who perceived keyboard >> bindings as being much faster than mouseing did not, on average, take >> less time to complete the actions that were studied (they took more >> time, in fact). The plausible explanation for this was that people's >> subjective perception of time is affected by the greater mental work >> involved in typing (as opposed to mousing) for a given action. > > I think mousing takes more mental work than typing, and that's why it > subjectively seems slower even if a stopwatch shows it to be faster. [...] I'm not sure this is a matter for debate, as much as physical measurement. John From aisaac at american.edu Mon Sep 10 10:52:25 2007 From: aisaac at american.edu (Alan Isaac) Date: Mon, 10 Sep 2007 14:52:25 GMT Subject: announcement: OpenOpt and GenericOpt Message-ID: OpenOpt and GenericOpt ====================== Introducing two new optimization packages. OpenOpt and GenericOpt are 100% Python with a single dependency: NumPy. For more detail see below and also OpenOpt ------- OpenOpt is new open source optimization framework. OpenOpt is released under the BSD license. The primary author and current maintainer of OpenOpt is Dmitrey Kroshko (Optimization Department, Cybernetics Institute, Ukrainian Science Academy) OpenOpt goal: provide an open source alternative to TomOpt TOMLAB (optimization framework for MATLAB) and related optimization frameworks. Currently OpenOpt offers connections to a variety of open source solvers, primarily for unconstrained optimization. (See below.) OpenOpt provides provides connections a vraity of solvers, including those in GenericOpt, which are included. (Users will need to download other solvers; we provide URLs for the downloads.) GenericOpt ---------- GenericOpt is a toolkit for building specialized optimizers. GenericOpt is released under the BSD license. The primary author and current maintainer of GenericOpt is Matthieu Brucher GenericOpt goal: provide an open source, extensible toolit for "component-wise" construction of specialized optimizers. GenericOpt allows users who want detailed control to construct their own solvers by choosing among a variety of algorithm components (currently, most choices are among step and line-search algorithms.) Usage: see Matthieu Brucher's tutorial . Limitation: currently GenericOpt provides only unconstrained solvers. SciKits ------- The SciPy project is developing a collection of open source packages for scientific computing which are allowed to have more dependencies and more varied licenses than those allowed for SciPy proper. In contrast to SciPy, the related scikits may host any OSI-approved licensed code. See OpenOpt and GenericOpt are available together as a SciPy scikit. The provides a unified optimization framework along with a collection of solvers. However, neither depends on the other. OpenOpt Details --------------- Key feature: a unified calling interface for all solvers, a variety of pure Python solvers, and connections to numerous external solvers. Example:: from scikits.openopt import NLP p = NLP(lambda x: (x-1)**2, 4) r = p.solve('ralg') In this example, the objective function is (x-1)^2, the start point is x0=4, and 'ralg' specifies the name of solver involved. See much more detailed example here OpenOpt Connected External Solvers ---------------------------------- Non-linear problems (NLP) ~~~~~~~~~~~~~~~~~~~~~~~~~ - ALGENCAN (GPL) - lincher (BSD) (all types of constraints and 1st derivatives), - ralg (BSD) (currently unconstrained only) - scipy_tnc and scipy_lbfgsb (box-bounded, requires scipy installed, BSD) Non-smooth problems (NSP) ~~~~~~~~~~~~~~~~~~~~~~~~~ - ralg (BSD) - ShorEllipsoid (BSD) (for small-scale problems with nVars = 1..10, former for medium-scaled problems with nVars = 1...1000, requires r0) Both are unconstrained for now. Linear problems (LP) ~~~~~~~~~~~~~~~~~~~~ - lp_solve (LGPL) - glpk (GPL) - CVXOPT (GPL) (currently glpk requires CVXOPT installed) Mixed-integer problems (MILP) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - lp_solve Quadratic problems (QP) ~~~~~~~~~~~~~~~~~~~~~~~ - CVXOPT (GPL) (please note - NLP lincher solver requires QP solver, and the only one for now is CVXOPT one) Here you can look at examples for NLP , NSP , QP , LP , MILP Acknowledgements ================ Development of OpenOpt was supported by Google through the Google Summer of Code (GSoC) program, with Alan G. Isaac as mentor. Additonal mentorship was provided by Jarrod Milman. Debts to the SciPy community are many, but we would particularly like to thank Nils Wagner. Appeal ====== The primary author and current maintainer of OpenOpt is Dmitrey Kroshko. The primary author and current maintainer of GenericOpt is Matthieu Brucher. These packages are already functional and extensible, but both would profit from additional intensive development. This will require sponsorship, especially for substantial additions to OpenOpt. The use of Python for scientific programming is only nascent in the Ukraine, so really an outside sponsor is needed. Ideas or leads are very welcome. From saptarshi.guha at gmail.com Thu Sep 20 20:59:13 2007 From: saptarshi.guha at gmail.com (sapsi) Date: Thu, 20 Sep 2007 17:59:13 -0700 Subject: Python,SWIG and libjvm In-Reply-To: <1190334123.039404.318860@d55g2000hsg.googlegroups.com> References: <1190329236.398635.226020@y42g2000hsy.googlegroups.com> <1190334123.039404.318860@d55g2000hsg.googlegroups.com> Message-ID: <1190336353.243711.166640@d55g2000hsg.googlegroups.com> On Sep 20, 8:22 pm, sapsi wrote: > On Sep 20, 7:00 pm, sapsi wrote: > > > Hello, > > I'm not sure if this the correct list but here goes (and sorry for the > > noise). I've been attempting to wrap python around libhdfs. > > So far so good ( > > I should point out that libhdfs is a c library to Hadoop Distributed > FileSystem. > Thank you > Saptarshi Hmm,here goes, you need -Wl,--rpart -Wl,path-to-jvm in the LDFLAGS in the compile process. HTH Saptarshi From saptarshi.guha at gmail.com Sat Sep 8 16:25:59 2007 From: saptarshi.guha at gmail.com (sapsi) Date: Sat, 08 Sep 2007 13:25:59 -0700 Subject: Using struct timeval in python In-Reply-To: References: <1189273504.153216.60470@22g2000hsm.googlegroups.com> Message-ID: <1189283159.646802.34680@g4g2000hsf.googlegroups.com> The timedelta module did the job just fine. Thank you From cjw at sympatico.ca Mon Sep 17 20:15:44 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 17 Sep 2007 20:15:44 -0400 Subject: Use GUI for Python In-Reply-To: <1190044523.666991.273910@y42g2000hsy.googlegroups.com> References: <1190043073.093736.272750@k79g2000hse.googlegroups.com> <1190044523.666991.273910@y42g2000hsy.googlegroups.com> Message-ID: <46EF18B0.1060505@sympatico.ca> Jason wrote: > On Sep 17, 9:31 am, kou... at hotmail.com wrote: >> I am new to python as I have been a VB programmer. I am used to the >> GUI interface, and was wondering if I had to choose between a GUI for >> Python, which one should I go with? Thanks. >> >> Kou > > You need to be more specific. Do you mean that you are used to > working in an IDE environment, where you can readily access the list > of classes, methods, and such? You might be interested in Eclipse > [1], then installing the PyDev [2] plug-in to add Python support. > Wing-IDE [3] and Komodo [4] may also be very suitable (but they cost > money). > > If you mean that you want to develop programs with a GUI interface, > then you have a number of choices [5]. Most of these choices do not > work in the same way that Microsoft Studio's GUI designer works, > partly because Python isn't tied to any of them. > o wxWidgets is MFC-like > o PyQT and PyGTK are similar to their underlying interfaces > o Tkinter comes with the default Python install, and provides the > Tk widget set > o With IronPython, you can access the regular Microsoft .NET GUIs > o PythonCard and EasyGUI are supposed to be pretty easy GUIs to use > o Dabo is a full-on database/GUI/platform set to easy cross- > platform GUI and database programming. > > The links to all those can be found at link [5]. Don't be afraid if > the choices are overwhelming. You have choices. I highly recommend > that you learn Python first, then examine the different GUI systems, > keeping in mind any requirements you may have and your previous > experience. > > [1] http://www.eclipse.org/ > [2] http://pydev.sourceforge.net/ > [3] http://wingware.com/ > [4] http://www.activestate.com/products/komodo_ide/ > [5] http://wiki.python.org/moin/GuiProgramming > If you are looking for a good IDE and you are in the Windows World, have a look at PyScripter. It is in development and the developer gives an excellent response to any queries or potential bugs. Colin W. From kay.schluehr at gmx.net Fri Sep 7 00:19:26 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 06 Sep 2007 21:19:26 -0700 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? In-Reply-To: <1189076186.590996.190380@o80g2000hse.googlegroups.com> References: <1189076186.590996.190380@o80g2000hse.googlegroups.com> Message-ID: <1189138766.283313.113690@50g2000hsm.googlegroups.com> On Sep 6, 12:56 pm, Paul Boddie wrote: > I think there's been a widespread "kitchen sink" mentality around the > Python language for some time, which is where the multimethods > proposal, amongst others, fits in here. Maybe that's one of two fixed points in the evolution of a programming language? The other one might be an almost non-designed and small language with a vast and flat library a la PHP and Zend. Apparently even Scheme moves into the kitchen sink today with the new R6RS specification. Python is going to be the-right-thing with abandoning the print statement or making lists a bit more monotyped with a type aware sort. The worse-is-better philosophy on the other hand is indifferent towards stylistic consistency and equipped with less nominalistic pedantry ( "this is a list and therefore you only have to use it as a list and not as a multiset..." ). This explains also the lack of interest into the std library which will be reduced to CPython services and basic datatypes. But there are also organizational issues and I don't even think that a lib that provides applications and domain specific services has to be necessarily maintained and approved by python-dev. I'd go even further and contend that's one of the issues where a rather large community such as Pythons could grow up and set code review standards ( and I mean *manual* code reviews of conscientous readers. I don't mean cheesecake or up(down)moddings in Web 2.0 style, implementing the "wisdom of the crowd" ). I can even live with Eggs and a not-so-common code base but not with low quality. From nospam at non.com Fri Sep 14 14:42:56 2007 From: nospam at non.com (=?iso-8859-1?b?cultaQ==?=) Date: Fri, 14 Sep 2007 18:42:56 GMT Subject: Rename multiple files using names in a text file Message-ID: Hi, I would like to rename files (jpg's ones) using a text file containing the new names... Below is the code that doesn't work : ***** #!/usr/bin/python #-*- coding: utf-8 -*- from os import listdir, getcwd, rename import re list_names=['new_name1','new_name2'] list_files = listdir(getcwd()) filtre = re.compile("jpg$", re.IGNORECASE) list_jpg = filter(filtre.search, list_files) #strip all element of list list_jpg list_jpg_strip=[] for nom in list_jpg: #print nom.strip() list_jpg_strip.append(nom.strip()) #let's rename : i=0 while i <= len(list_jpg_strip): rename(list_jpg_strip[i],list_names[i]) i=i+1 **** The error message is : File "ecm.py", line 17, in rename(list_jpg_strip[i],list_names[i]) OSError: [Errno 2] No such file or directory and all files exists, I checked it hundred times ! :-s Do you have a clue ? Thanks a lot. R?mi. From neoedmund at gmail.com Mon Sep 10 05:30:04 2007 From: neoedmund at gmail.com (neoedmund) Date: Mon, 10 Sep 2007 09:30:04 -0000 Subject: unexpected behavior: did i create a pointer? In-Reply-To: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> Message-ID: <1189416604.902880.24370@g4g2000hsf.googlegroups.com> On Sep 7, 4:07 pm, gu wrote: > hi to all! > after two days debugging my code, i've come to the point that the > problem was caused by an unexpected behaviour of python. or by lack of > some information about the program, of course! i've stripped down the > code to reproduce the problem: > > > a = {} > > for x in range(10): > for y in range(10): > a[x,y] = "0" > > copyOfA = a > > def functionA(x,y): > print a[x,y], > copyOfA[x,y] = "*" > print a[x,y],copyOfA[x,y] > > for x in range(10): > for y in range(10): > functionA(x,y) > > > > now, in the second "for" cycle and in functionA() i only 'touch' copyOfA > (altering it). as i don't touch the variable "a", i expect it not to be > affected by any change, but copyOfA acts like a pointer to a and > altering copyOfA's values result in altering the values of "a", so the > result that i expect is: > 0 0 * > 0 0 * > 0 0 * > 0 0 * > [..] > > but i get: > 0 * * > 0 * * > 0 * * > 0 * * > [..] > > what's going on? > thanks in advance. no language act like want you tought, or the assignment operation will be too expensive. From arkanes at gmail.com Thu Sep 20 10:58:03 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 20 Sep 2007 09:58:03 -0500 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <7x1wctwg6x.fsf@ruckus.brouhaha.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> <1190241711.344058.238380@57g2000hsv.googlegroups.com> <1190242799.954176.279440@22g2000hsm.googlegroups.com> <7xps0ew0a8.fsf@ruckus.brouhaha.com> <13f3roj6gdfq6b7@corp.supernews.com> <7x1wctwg6x.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60709200758o21d76483mb7f16d744ebc3f80@mail.gmail.com> On 20 Sep 2007 07:43:18 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Steven D'Aprano writes: > > That's why your "comparatively wimpy site" preferred to throw extra web > > servers at the job of serving webpages rather than investing in smarter, > > harder-working programmers to pull the last skerricks of performance out > > of the hardware you already had. > > The compute intensive stuff (image rendering and crunching) has > already had most of those skerricks pulled out. It is written in C > and assembler (not by us). Only a small part of our stuff is written > in Python: it just happens to be the part I'm involved with. > That means that this part is also unaffected by the GIL. > > But Python speed ups don't come for free. For instance, I'd *really* > > object if Python ran twice as fast for users with a quad-core CPU, but > > twice as slow for users like me with only a dual-core CPU. > > Hmm. Well if the tradeoff were selectable at python configuration > time, then this option would certainly be worth doing. You might not > have a 4-core cpu today but you WILL have one soon. > > > What on earth makes you think that would be anything more than a > > temporary, VERY temporary, shutdown? My prediction is that the last of > > the machines wouldn't have even been unplugged > > Of course that example was a reductio ad absurdum. In reality they'd > use the speedup to compute 2x as much stuff, rather than ever powering > any servers down. Getting the extra computation is more valuable than > saving the electricity. It's just easier to put a dollar value on > electricity than on computation in an example like this. It's also > the case for our specfiic site that our server cluster is in large > part a disk farm and not just a compute farm, so even if we sped up > the software infinitely we'd still need a lot of boxes to bolt the > disks into and keep them spinning. > I think this is instructive, because it's pretty typical of GIL complaints. Someone gives an example where the GIL is limited, but upon inspection it turns out that the actual bottleneck is elsewhere, that the GIL is being sidestepped anyway, and that the supposed benefits of removing the GIL wouldn't materialize because the problem space isn't really as described. > > Now there's a thought... given that Google: > > > > (1) has lots of money; > > (2) uses Python a lot; > > (3) already employs both Guido and (I think...) Alex Martelli and > > possibly other Python gurus; > > (4) is not shy in investing in Open Source projects; > > (5) and most importantly uses technologies that need to be used across > > multiple processors and multiple machines > > > > one wonders if Google's opinion of where core Python development needs to > > go is the same as your opinion? > > I think Google's approach has been to do cpu-intensive tasks in other > languages, primarily C++. It would still be great if they put some > funding into PyPy development, since I think I saw something about the > EU funding being interrupted. > -- At the really high levels of scalability, such as across a server farm, threading is useless. The entire point of threads, rather than processes, is that you've got shared, mutable state. A shared nothing process (or Actor, if you will) model is the only one that makes sense if you really want to scale because it's the only one that allows you to distribute over machines. The fact that it also scales very well over multiple cores (better than threads, in many cases) is just gravy. The only hard example I've seen given of the GIL actually limiting scalability is on single server, high volume Django sites, and I don't think that the architecture of those sites is very scalable anyway. From arne at vajhoej.dk Sun Sep 30 17:03:15 2007 From: arne at vajhoej.dk (=?UTF-8?B?QXJuZSBWYWpow7hq?=) Date: Sun, 30 Sep 2007 17:03:15 -0400 Subject: which language allows you to change an argument's value? In-Reply-To: References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> Message-ID: <47000ed3$0$90272$14726298@news.sunsite.dk> Erik Wikstr?m wrote: >> their reference (alias) mechanism. And C, Python, and Ruby probably >> won't let you do that. What about Java and Perl? > > C will let you do it with pointers (it is just a syntactical difference > from references in this case) and Java's references allows it. Neither C or Java has call by reference. C pointers and Java references may work similarly in most cases but it is still call by value. > I do not > know about Ruby, Python and Perl, but (AFAIK) the all have OO support so > I would be surprised if they used purely value semantics. I can not see why OO should indicate anything about call by reference support. >> isn't "what i pass in, the function can modify it" not a desireable >> behavior if i am NOT passing in the address of my argument? For one > > Being able to pass the actual object instead of a copy is highly > desirable for two reasons. In most languages only one return value is > allowed for a function so the ability to change parameters allows you to > artificially return more without having to wrap them in constructs. The > second reason is that for large objects the performance hit of having to > create a copy each time you call a function can be forbidding. Usually it is not a good thing, because it makes the code much more difficult to read. But sometimes it is handy. I think C# got it right. It allows it but require an explicit marking of it in both formal argument list and actual argument list. >> Java, Python, and Ruby, and we pass in a reference to object (not C+ >> +'s meaning of alias reference) > > In what way does the C++ reference differ from those in Java, Python, > and Ruby in this situation? C++ and Java are very different in this aspect. Arne From mail at timgolden.me.uk Tue Sep 11 10:55:03 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Sep 2007 15:55:03 +0100 Subject: Minor documentation bug In-Reply-To: <1189518490.939985.101460@g4g2000hsf.googlegroups.com> References: <1189518490.939985.101460@g4g2000hsf.googlegroups.com> Message-ID: <46E6AC47.8030204@timgolden.me.uk> Frank Millman wrote: > I spotted a minor bug in the documentation to SimpleXMLRPCServer. It > does not seem worth getting a login to the bugtracker just to enter > this, so if it is confirmed as a bug perhaps someone would be so kind > as to enter it for me. Frank, please do take the trouble to enter this. With the new roundup bugtracker, it's *really easy* to get a login. http://bugs.python.org TJG From carsten at uniqsys.com Mon Sep 24 07:55:35 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Sep 2007 07:55:35 -0400 Subject: Almost There - os.kill() In-Reply-To: References: Message-ID: <1190634935.3385.36.camel@dot.uniqsys.com> On Mon, 2007-09-24 at 19:48 +0800, Delaney, Timothy (Tim) wrote: > Always be careful with int() incase any of the values have a leading > zero - check the documentation for int() carefully. Why would leading zeroes be a problem? >>> int("10") 10 >>> int("010") 10 >>> int("0010") 10 >>> int("00010") 10 Maybe you're thinking of "evil eval?" >>> eval("10") 10 >>> eval("010") 8 -- Carsten Haese http://informixdb.sourceforge.net From wink at saville.com Wed Sep 26 11:18:32 2007 From: wink at saville.com (wink) Date: Wed, 26 Sep 2007 08:18:32 -0700 Subject: Asynchronous Messaging In-Reply-To: <1190807252.731074.141450@k79g2000hse.googlegroups.com> References: <1190807252.731074.141450@k79g2000hse.googlegroups.com> Message-ID: <1190819912.344267.52680@50g2000hsm.googlegroups.com> On Sep 26, 4:47 am, wink wrote: To make it easier to comment on the code, I'm including "mproc.py" file below. Fredrik, was commenting about using Queue and in fact I do. Queue is quite nice and is also thread safe, which is a requirement for this implementation. But its performance is poor if the number of items on a Queue becomes large because it is implemented using a list. One of the things I was thinking of was doing another implementation using of Queue which was based on deque. """Message Processor Module. This modules allows programmers to create compnents which communicate asynchronously via messages. In addition the receiving component is will only handle one message at a time. This allows the programmer to create multi-threaded program with fewer shared memory thus fewer mutex's and semaphore's. The basic communication is via an instance of the Msg class which is sent to mproc's using the send method. An Mproc is an active component which has a thread and executes asynchronously from all other Mproc's by using one MprocDriver for each Mproc. It is also possible for several mproc's to share one MprocDriver by using BaseMproc. Each mproc must override the _handler method. When a message arrives for a mproc is it placed in a Queue and the driver calls the _handler method passing the Msg as a parameter. The driver uses the Queue to serialize the message processing, thus the _handler method will be invoked with one message at a time. Thus the _handler method does not generally need to use mutex's or semaphore's. But because each message's processing must be completed before the next message will be started it is important that the message be processed as quickly as possible. Add more documentation.""" import copy import threading import Queue import traceback class Msg: """A message""" def __init__(self): """Initializer""" self.dstMpId = None self.dstCnId = None self.srcMpId = None self.srcCnId = None self.mid = None self.cmd = None self.tag = None self.status = None self.data = None def dup(self): """Duplicate the message""" msgCopy = copy.deepcopy(self) return msgCopy def send(self): """Send a message. Returns True if the message was started on its way""" try: MprocDriver._mpList[self.dstMpId]._msgQueue.put(self) return True except: return False class BaseMproc: """Message Processor. A message processor requires a handler method and another driver which passes messages to it. This mproc driver has one overriding requirement, it must only pass one message at a time to the handler method. This eliminates any need for the programmer to worry about multi-threading issues while processing messages. This does put a burden on the handler routine, it must process messages quickly and in a non-blocking fashion so that the mproc may remain lively. The name of an BaseMproc must be unique, an exception is thrown if the name is already used.""" def __init__(self, name, mprocDriver): """Initializer""" self.name = name addMproc(self, mprocDriver) def close(self): """Close the mproc""" #print "BaseMproc.close: ", self.name try: rmvMproc(self) except: #print "BaseMproc.close: excption" traceback.print_exc() self._unreg() def _handler(self): """Override this routine.""" raise Exception("BaseMproc._handler needs to be overridden") def _reg(self, mprocDriver, id): """Register the mproc driver for this mproc""" self._mprocDriver = mprocDriver self._msgQueue = mprocDriver._msgQueue self.id = id def _unreg(self): """Unregister the mproc driver for this mproc""" self._mprocDriver = None self._msgQueue = None self.id = None class Mproc(BaseMproc): """Active Message Processor. An active message processor isa BaseMproc but it always creates a MprocDriver instance as its driver""" def __init__(self, name): """Initializer""" BaseMproc.__init__(self, name, MprocDriver("ActiveMprocDriver_" + name)) def close(self): """Close the active mproc""" try: this_mprocDriver = self._mprocDriver BaseMproc.close(self) this_mprocDriver.close() except: print "Mproc.close: excption" traceback.print_exc() self._unreg() class MprocDriver(threading.Thread, BaseMproc): """Message processor driver.""" _mpList = [] _mpDict = {} def __init__(self, name): """Initializer""" self._thisMpdDict = {} self._running = True self._msgQueue = Queue.Queue() threading.Thread.__init__(self) BaseMproc.__init__(self, name, self) self.start() def _regMproc(self, mproc, id): self._thisMpdDict[mproc.name] = mproc mproc._reg(self, id) def _unregMproc(self, mproc): #print "%s._unregMproc(%s):" % (self.name, mproc.name) del self._thisMpdDict[mproc.name] mproc._unreg() def _handler(self, msg): if (msg.mid == -1) and (msg.cmd == 0): self._running = False msg.completeQ.put(0) def close(self): """Close the mproc driver""" # Remove all mprocs related to this MprocDriver????? mprocs = self._thisMpdDict.values() for mproc in mprocs: if (mproc.name != self.name): rmvMproc(mproc) completeQ = Queue.Queue() msg = Msg() msg.dstMpId = self.id msg.mid = -1 msg.cmd = 0 msg.completeQ = completeQ msg.send() completeQ.get() # Remove ourself BaseMproc.close(self) del self._thisMpdDict def run(self): while (self._running): try: msg = self._msgQueue.get() mproc = MprocDriver._mpList[msg.dstMpId] mproc._handler(msg) except: if msg == None: print "run: no message" elif mproc == None: print "run: no mproc" elif not callable(mproc._handler): print "run: mproc._handler is not callable" else: print "run: mproc._handler caused an exception" traceback.print_exc() class PsMgr: """Publish Subscribe Manager. Allow mprocs to subscribe to any message having a specified mid/cmd. Maybe this should be in a separte module and instead of using class variables? """ midDict = {} @classmethod def publish(self, msg): """Send the message to all subscribers""" pass @classmethod def subscribe(self, mproc, mid, cmd): """Subscribe the mproc to messages with mid/cmd""" self.publish = PsMgr._publish self.subscribe = PsMgr._subscribe self.unsubscribe = PsMgr._unsubscribe self.subscribe(mproc, mid, cmd) @classmethod def unsubscribe(self, mproc, mid, cmd): """Unsubscirve the mproc""" pass @classmethod def _publish(self, msg): """The actual publish routine where there is one or more subscribers""" try: #print "_publish: msg.mid=%d msg.cmd=%d" % (msg.mid, msg.cmd) subscribers = self.midDict[msg.mid][msg.cmd] except KeyError: #print "_publish: error no subscribers for msg.mid=%d msg.cmd=%d" % (msg.mid, msg.cmd) pass else: for mproc in subscribers: msgNew = msg.dup() #print "_public mid=%d cmd=%d to %s" % (msgNew.mid, msgNew.cmd, mproc.name) #, mproc.id) msgNew.dstMpId = mproc.id msgNew.send() @classmethod def _subscribe(self, mproc, mid, cmd): """The actual subscribe routine""" #print "_subscribe: add mproc %s for mid=%d cmd=%d" % (mproc.name, mid, cmd) cmdDict = self.midDict.get(mid, {}) subscribers = cmdDict.get(cmd, []) subscribers.append(mproc) cmdDict[cmd] = subscribers self.midDict[mid] = cmdDict @classmethod def _unsubscribe(self, mproc, mid, cmd): """The actual unsubscribe routine when there is one or more subscribers""" #print "_unsubscribe: remove mproc %s for mid=%d cmd=%d" % (mproc.name, mid, cmd) cmdDict = self.midDict.get(mid, {}) subscribers = cmdDict.get(cmd, []) delList = [] count = 0 for mp in subscribers: if mp == mproc: delList.append(count) count += 1 l = len(delList) for x in xrange(l-1, -1, -1): del subscribers[delList[x]] if len(self.midDict) == 0: self.publish = PsMgr.publish self.subscribe = PsMgr.subscribe self.unsubscribe = PsMgr.unsubscribe def lookupMproc(name, onNotFound=None): """Lookup an message processor""" try: #print "lookupMproc: %s dict=%s" % (name, MprocDriver._mpDict) mproc = MprocDriver._mpDict[name] except: # Add not found exception? #print "lookupMproc: NOT FOUND", name mproc = onNotFound return mproc def addMproc(mproc, mprocDriver): """Add a new message processor to the database""" if (lookupMproc(mproc.name) != None): raise NameError("%s BaseMproc already exists" % mproc.name) #print "addMproc:", mproc.name MprocDriver._mpList.append(mproc) MprocDriver._mpDict[mproc.name] = mproc #print "addMproc: dict=", MprocDriver._mpDict id = MprocDriver._mpList.index(mproc) mprocDriver._regMproc(mproc, id) def rmvMproc(mproc): """Remove message processor from the database""" #print "rmvMproc:", mproc.name MprocDriver._mpList[mproc.id] = None del MprocDriver._mpDict[mproc.name]; #print "rmvMproc: dict=", MprocDriver._mpDict mproc._mprocDriver._unregMproc(mproc) From alexandre.badez at gmail.com Wed Sep 5 09:34:42 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Wed, 05 Sep 2007 13:34:42 -0000 Subject: Multi Heritage with slots In-Reply-To: <1188996990.810829.122910@w3g2000hsg.googlegroups.com> References: <1188982916.071976.160170@g4g2000hsf.googlegroups.com> <1188994956.570845.269250@w3g2000hsg.googlegroups.com> <1188996990.810829.122910@w3g2000hsg.googlegroups.com> Message-ID: <1188999282.387338.173880@o80g2000hse.googlegroups.com> On Sep 5, 2:56 pm, Michele Simionato wrote: > On Sep 5, 2:52 pm, "Simon Brunning" wrote: > > > On 9/5/07, Alexandre Badez wrote: > > > > I use __slots__ not for memory optimization nor doing java. > > > I use __slots__ because my class are used by other lib, and in the > > > past, some of them misspell some attributes and involved a very > > > annoying comportment of the global application. > > > So the objective is only to prevent unwanted dynamism (but not in all > > > the application, just some class). > > > Using slots to prevent the creation of new properties is what Eric > > *means* by "doing java". You're trying to write Java style code in > > Python, and it's not going to be pretty. Slots are not intended for > > this purpose, and they aren't very good for it. > > Right, and this the way to do what the original poster wants: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 > > Michele Simionato Thanks every body for your remarks. I still have a lot to learn in python... From steve at holdenweb.com Fri Sep 28 16:09:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 16:09:26 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191009608.985644.271160@50g2000hsm.googlegroups.com> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> <1191008702.579795.141180@r29g2000hsg.googlegroups.com> <1191009608.985644.271160@50g2000hsm.googlegroups.com> Message-ID: TheFlyingDutchman wrote: > On Sep 28, 12:45 pm, George Sakkis wrote: >> On Sep 28, 3:29 pm, TheFlyingDutchman wrote: >> >>> One issue I have with this group and that I encountered many years ago >>> in the Perl group is that there is no separate group >>> comp.lang.python.beginner where you can ask questions without getting >>> hit with RTFM! and the like. >> Which shows once again that you're trying to break the world record of >> being wrong in as many sentences as possible: >> >> http://mail.python.org/mailman/listinfo/tutor >> >> You would do yourself (and others) a favor by migrating there for a >> few weeks or months. >> >> George > > Being in a land where every nit can be picked, I am surprised that you > offered up a mailing list when I was asking for a newsgroup. > That's because the tutor list doesn't offer a newsgroup. He was probably just trying to get rid of you. Now at 98.75% ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From steve at holdenweb.com Fri Sep 14 02:54:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Sep 2007 02:54:09 -0400 Subject: "once" assigment in Python In-Reply-To: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> References: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> Message-ID: Lorenzo Di Gregorio wrote: > Hello, > > I've been using Python for some DES simulations because we don't need > full C speed and it's so much faster for writing models. During > coding I find it handy to assign a variable *unless it has been > already assigned*: I've found that this is often referred to as "once" > assigment. > > The best I could come up with in Python is: > > try: > variable > except NameError: > variable = method() > > I wonder if sombody has a solution (trick, whatever ...) which looks > more compact in coding. Something like: > > once(variable, method) > > doesn't work, but it would be perfect. Of course I can preprocess the > Python code but an all-Python solution would be more handy. > > Any suggestions? > Without being fatuous, I would suggest you rethink your approach to the problem. Do your variables have default values? If not, what happens if the user does not set them and your code tries to refer to them? You seem to be trying to apply defaults if the user hasn't set a value, when the correct things to do is to apply the defaults *before the user gets a chance to do anything at all*. Then any changes made by the user will overwrite the defaults. Even better, if its practical, is to provide your functionality as one or more functions, whose definitions can set default values for keyword arguments. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From fakeaddress at nowhere.org Thu Sep 27 05:05:02 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 27 Sep 2007 09:05:02 GMT Subject: Load balancing and passing sockets; was: Re: Google and Python In-Reply-To: References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com><1190231094.276099.136250@22g2000hsm.googlegroups.com><1190235678.019823.315850@o80g2000hse.googlegroups.com><7xejgr68pm.fsf@ruckus.brouhaha.com><7xps07w5g3.fsf@ruckus.brouhaha.com> Message-ID: <2nKKi.937$4V6.695@newssvr14.news.prodigy.net> Hendrik van Rooyen wrote: > "Nick Craig-Wood" wrote: [about passing sockets between processes] >> It is trivial to pass a socket to a new thread or a forked child - you >> don't need this mechanism for that. It doesn't work on different >> machines though - it has to be on the same machine. > > How does a very large volume site work then? - there must be some > way of sharing the load without bottlenecking it through one machine? Several ways. The Domain Name System can provide multiple IP addresses for the same name. IP addresses often often lead to HTTP "reverse proxies" that shoot back cached replies to common simple requests, and forward the harder ones to the file/application servers, with intelligent load balancing. The services are surprisingly basic, and some excellent software is free: http://en.wikipedia.org/wiki/Round_robin_DNS http://en.wikipedia.org/wiki/Reverse_proxy http://en.wikipedia.org/wiki/Squid_proxy Web apps tend to scale just great, except when they need data that is both shared and modifiable. -- --Bryan From XX.XmcX at XX.XmclaveauX.com Mon Sep 10 12:07:07 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Mon, 10 Sep 2007 18:07:07 +0200 Subject: shared memory pointer References: <1189436265.841415.234050@w3g2000hsg.googlegroups.com> <1189437684.476993.130390@g4g2000hsf.googlegroups.com> Message-ID: Hi! I agree ; on windows mmap use Memory-Mapped-file, who use virtual memory. And shared memory use physical memory. The difference is OS an not Python -- @-salutations Michel Claveau From wizzardx at gmail.com Mon Sep 10 07:30:56 2007 From: wizzardx at gmail.com (David) Date: Mon, 10 Sep 2007 13:30:56 +0200 Subject: Enum class with ToString functionality In-Reply-To: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> Message-ID: <18c1e6480709100430rf627c58we3fc525a1447c264@mail.gmail.com> On 9/10/07, bg_ie at yahoo.com wrote: > Hi, > > I have the following class - > > class TestOutcomes: > PASSED = 0 > FAILED = 1 > ABORTED = 2 > > plus the following code - > > testResult = TestOutcomes.PASSED > > testResultAsString > if testResult == TestOutcomes.PASSED: > testResultAsString = "Passed" > elif testResult == TestOutcomes.FAILED : > testResultAsString = "Failed" > else: > testResultAsString = "Aborted" > > But it would be much nicer if I had a function to covert to string as > part of the TestOutcomes class. How would I implement this? You can use reflection to do this. Perhaps a constructor that goes through your class dict (dir(self)) and builds an int->string mapping property based on the value and name of the attributes (perhaps just the ones whose type is int). To get the exact same result as your code above you can capitalize the first letter of the attribute name, and lowercase the rest. From Shawn at Milochik.com Fri Sep 7 14:19:06 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Fri, 7 Sep 2007 14:19:06 -0400 Subject: Python and Cron In-Reply-To: References: Message-ID: <2dc0c81b0709071119scb80186k8114f6592391f3f9@mail.gmail.com> Could you send the output of "crontab -l" and the script you're running? It's probably an environment issue of some kind, but it's hard to say what blindly. From laurent.pointal at limsi.fr Wed Sep 19 04:12:22 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 19 Sep 2007 10:12:22 +0200 Subject: lxml codespeak pages empty ? Message-ID: I can no longer get codespeak's lxml page at http://codespeak.net/lxml/ (get an empty HTML document )... Am-I alone in this case ? Any codespeaker reading ? A+ Laurent. From deets at nospam.web.de Sat Sep 22 06:34:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Sep 2007 12:34:12 +0200 Subject: Who can develop the following Python script into working application ? In-Reply-To: <1190419744.390216.19040@w3g2000hsg.googlegroups.com> References: <1190334828.210230.293980@50g2000hsm.googlegroups.com> <1190372423.768184.60080@19g2000hsx.googlegroups.com> <5lho31F84jgjU1@mid.uni-berlin.de> <1190419744.390216.19040@w3g2000hsg.googlegroups.com> Message-ID: <5lk9e0F8leeeU1@mid.uni-berlin.de> http://members.lycos.co.uk/dariusjack/ schrieb: > On Sep 21, 1:26 pm, "Diez B. Roggisch" wrote: >> >> >>> Please help and let me know your terms. >> There are websites dedicated to this - like e.g. >> >> http://www.guru.com/ >> >> Make an offer there. >> >> Diez > > Ok Diez, > > Do you really think only Gurus from Guru.com can help me ? > Do really need a middle-man ? What middle-man? > As you see, I am not developer of that code. > Henri responded to me, code was intended for developers. > It doesn't really look complicated or high-tech. > Script should connect to a remote web site and get xml formatted data > as a response to a query string http request, read data and inject > into SQL database. > Is Python not fit to a task of this kind ? > Is there no a library of Python free scripts to accomplish the above > like many for javascripts ? > I am asking just of curosity, as an author of this script didn't > respond to my second request to tell me how complicated is the > problem and what made him not to write that script as a fully working > version. > > Is Python so difficult, complicated, even for experienced developers ? No, it's neither complicated nor difficult. And you know what? Not only for expierenced, but also for inexperienced developers it's an easy language. And this community here is an extremely helpful and kind one. But what it isn't is a forum to ask other to do your work FOR FREE. And get kinky about it if they refuse to do so... And as you said yourself: """ Frankly speaking I would prefer to pay for your kind assistance as it may take me to much time to learn some Python and understand the following script. """ Now, again: http://www.guru.com/ There you can get devlopers for money. So what again is your problem? Diez From tutufan at gmail.com Thu Sep 27 10:56:10 2007 From: tutufan at gmail.com (asdfjehqwjerhqjwljekrh) Date: Thu, 27 Sep 2007 14:56:10 -0000 Subject: Google and Python In-Reply-To: <1i4xorh.j5nc9k3y60vqN%aleax@mac.com> References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> <1i4rfyx.8vuc2j14j596uN%aleax@mac.com> <1i4xorh.j5nc9k3y60vqN%aleax@mac.com> Message-ID: <1190904970.990749.113240@o80g2000hse.googlegroups.com> On Sep 24, 10:40 am, al... at mac.com (Alex Martelli) wrote: > > Good motto. So is most of Google's code base now in > > Python? About what is the ratio of Python code to C++ > > code? Of course lines of code is kine of a bogus measure. > > Of all those cycles Google executes, about what portion > > are executed by a Python interpreter? > > I don't have those numbers at hand, and if I did they would be > confidential I would be curious to know whether they code much "mixed model" coding. By that I mean (a) code your application in Python, and then (b) optimize it as necessary by moving some functionality into Python C/C++ modules. (Some of (b) may happen during design, of course.) I think of this as the state of the art in programming practice, and I wonder whether Google's doing this, or has a superior alternative. Mike From stefan.behnel-n05pAM at web.de Mon Sep 10 09:39:27 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 10 Sep 2007 15:39:27 +0200 Subject: XML: SAX and XInclude In-Reply-To: References: Message-ID: <46E5490F.8060107@web.de> Laurent Pointal wrote: > does anybody know about an XML parser usable with the sax API (xml.sax) > and with XInclude feature support (directly or via hacks). Try lxml.etree. http://codespeak.net/lxml/ http://codespeak.net/lxml/tutorial.html http://codespeak.net/lxml/api.html#xinclude-and-elementinclude http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk It's not half as complicated as SAX, BTW. Stefan From brenNOSPAMbarn at NObrenSPAMbarn.net Thu Sep 20 13:05:08 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Thu, 20 Sep 2007 17:05:08 GMT Subject: Sets in Python References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <13f3m15igkstq2e@corp.supernews.com> <1190260923.243865.312190@z24g2000prh.googlegroups.com> <13f4nclh902f78f@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > But of course you can't look up the dict by value, only by > identity. But that's what you wanted. Actually, if I understand the OP's examples right, he wants to look up only by value, not by identity. -- --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 facundobatista at gmail.com Wed Sep 19 16:41:49 2007 From: facundobatista at gmail.com (Facundo Batista) Date: Wed, 19 Sep 2007 17:41:49 -0300 Subject: Python tickets summary In-Reply-To: References: Message-ID: 2007/9/10, Facundo Batista : > I modified my tool, whichs makes a summary of all the Python tickets > (I moved the source where the info is taken from SF to our Roundup). Based on an idea from Dennis Benzinger, now the temporal bars show the moments where each comment was made, so it's easy to see the "rhythm" of the ticket activity: http://www.taniquetil.com.ar/facundo/py_tickets.html Regards, -- . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From bert at bertisevil.tv Thu Sep 6 15:06:23 2007 From: bert at bertisevil.tv (Evil Bert) Date: Thu, 06 Sep 2007 12:06:23 -0700 Subject: interesting puzzle......try this you will be rewarded... In-Reply-To: <46e04138$0$16377$88260bb3@free.teranews.com> References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> <46e04138$0$16377$88260bb3@free.teranews.com> Message-ID: Tobiah wrote: > My adblock extension must be doing a great job. > I don't see any ads. The puzzle is fun really, > but I'm stuck right now at 'eeiigg'. eight --> eeiigg nine --> nniinn Kinda silly, but it works From Michael.J.Fromberger at Clothing.Dartmouth.EDU Wed Sep 19 17:55:39 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Wed, 19 Sep 2007 17:55:39 -0400 Subject: Parsing problems: A journey from a text file to a directory tree References: <1189958074.670245.17910@n39g2000hsh.googlegroups.com> <1190154665.944722.137750@q3g2000prf.googlegroups.com> Message-ID: Hi, John, Your comments below are all reasonable. However, I would like to point out that the purpose of my example was to provide a demonstration of an algorithm, not an industrial-grade solution to every aspect of the original poster's problem. I am confident the original poster can deal with these aspects of his problem space on his own. In article <1190154665.944722.137750 at q3g2000prf.googlegroups.com>, John Machin wrote: > [...] > > . while new_level < len(state): > > . state.pop() > > Hmmm ... consider rewriting that as the slightly less obfuscatory > > while len(state) > new_level: > state.pop() This seems to me to be an aesthetic consideration only; I'm not sure I understand your rationale for reversing the sense of the comparison. Since it does not change the functionality, it's hardly worthy of complaint, but I don't see any improvement, either. > A warning message if there are too many "-" characters might be a good > idea: > > [foo] > |-bar > |-zot > |---plugh Perhaps so. Again, the original poster will have to decide what should be the correct response to input of this sort; at present, the implementation is tolerant of such variations, without loss of generality. > And if the input line matches neither regex? I believe it should be clear that such lines are ignored. Again, this is an opportunity for the original poster to determine an alternative response -- perhaps an exception could be raised, if that is his desire. The problem specification did not constrain this case. > > To call this, pass a file-like object to parse_folders(), e.g.: > > > > test1 = ''' > > [New client]. > > Won't work with the dot on the end. My mistake. The period was a copy-and-paste artifact, which I missed. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From robin at NOSPAMreportlab.com Wed Sep 19 17:17:19 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Wed, 19 Sep 2007 22:17:19 +0100 Subject: Odd files; just left behind? In-Reply-To: <878x725ts7.fsf@pobox.com> References: <878x725ts7.fsf@pobox.com> Message-ID: <46F191DF.7000908@jessikat.plus.net> John J. Lee wrote: > Robin Becker writes: > >> I see a folder .python-eggs in my home directory on one of our servers >> with various .so files >> >> ~/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so >> >> are these just left behind from some install process? > > Ah, it's about the resource extraction feature of setuptools. It's > possible for zipped eggs to contain resources that have to be > extracted to the filesystem. It puts them in the directory you saw > (or somewhere else -- see the docstring in my other reply). > > http://peak.telecommunity.com/DevCenter/PkgResources#resource-extraction > http://peak.telecommunity.com/DevCenter/setuptools#automatic-resource-extraction ..... Thanks John, but why not clean up? -- Robin Becker From zzbbaadd at aol.com Mon Sep 10 07:52:34 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 10 Sep 2007 04:52:34 -0700 Subject: Enum class with ToString functionality In-Reply-To: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> Message-ID: <1189425154.788466.132370@d55g2000hsg.googlegroups.com> On Sep 10, 2:28 am, bg... at yahoo.com wrote: > Hi, > > I have the following class - > > class TestOutcomes: > PASSED = 0 > FAILED = 1 > ABORTED = 2 > > plus the following code - > > testResult = TestOutcomes.PASSED > > testResultAsString > if testResult == TestOutcomes.PASSED: > testResultAsString = "Passed" > elif testResult == TestOutcomes.FAILED : > testResultAsString = "Failed" > else: > testResultAsString = "Aborted" > > But it would be much nicer if I had a function to covert to string as > part of the TestOutcomes class. How would I implement this? > > Thanks, > > Barry class TestOutcomes: PASSED = 0 FAILED = 1 ABORTED = 2 def ToString(outcome): if outcome == TestOutcomes.PASSED: return "Passed" elif outcome == TestOutcomes.FAILED : return "Failed" else: return "Aborted" ToString = staticmethod(ToString) if __name__ == "__main__": testResult = TestOutcomes.PASSED testResultAsString = TestOutcomes.ToString(testResult) print testResultAsString print TestOutcomes.ToString(testResult) Passed Passed From michele.simionato at gmail.com Thu Sep 6 05:18:07 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 06 Sep 2007 09:18:07 -0000 Subject: How to do python and RESTful In-Reply-To: <1189022079.403495.175800@g4g2000hsf.googlegroups.com> References: <1189022079.403495.175800@g4g2000hsf.googlegroups.com> Message-ID: <1189070287.239501.70270@k79g2000hse.googlegroups.com> On Sep 5, 9:54 pm, MarkyMarc wrote: > Hi all, > > I want to make a web service application in python and keywords are > RESTful, python and nice urls(urls mapped to python objects). > > I don't want a big framework but a nice small one, that can just do > the things I want. > > I have be looking at quixote, but is this uptodate? "plain" > mod_python, can this make url to http put,get,delete and post? > > Can some one here point me some where I can read about python and > RESTful or have some experiences with other? > > Any help is apricieted. > > Regards Marc For the client part, there is an easy_installable library called restclient (which I tested very little but it seems to work). For the server part, I am sure there are many available, but is also easy to write your own. For instance, using WSGI, you can do something like: def restful_wsgi_app(env, resp): meth = env.get('REQUEST_METHOD') if meth == 'GET': ... elif meth == 'POST': ... elif meth == 'PUT': .... elif meth == 'DELETE': ... else: raise ValueError('Unknown HTTPMethod %r!!' % meth) ... Michele Simionato From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 18 10:38:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 16:38:59 +0200 Subject: Saving parameters between Python applications? In-Reply-To: <1190122569.509673.41420@57g2000hsv.googlegroups.com> References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> <1190060967.696332.113190@n39g2000hsh.googlegroups.com> <1190122569.509673.41420@57g2000hsv.googlegroups.com> Message-ID: <46efe2fb$0$27792$426a74cc@news.free.fr> Stodge a ?crit : > os.path.expanduser isn't an option; I need each console/window to > maintain different values which I wouldn't get from saving to a user's > home directory. Unless I used a different file for each console/window > but that just gets me into the same situation I'm already in. I think > the only option is to set environment variables using another script. > I'm really surprised and disapponited by this. Note that it's *not* a Python issue. You'd have the same problem with any other language. From wgwhalley at gmail.com Thu Sep 13 15:16:54 2007 From: wgwhalley at gmail.com (WGWhalley) Date: Thu, 13 Sep 2007 12:16:54 -0700 Subject: Search path for python script In-Reply-To: <1189633230.265179.58780@19g2000hsx.googlegroups.com> References: <1189633230.265179.58780@19g2000hsx.googlegroups.com> Message-ID: This works for me under cygwin. Start the script with the line #! /usr/bin/python Place the script in a directory shown by the command echo $PATH Invoke the script using its name, i.e. test.py From richyjsm at gmail.com Sat Sep 22 14:09:49 2007 From: richyjsm at gmail.com (richyjsm at gmail.com) Date: Sat, 22 Sep 2007 18:09:49 -0000 Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: References: <46f49740$0$32514$4c368faf@roadrunner.com> Message-ID: <1190484589.890198.266430@y42g2000hsy.googlegroups.com> On Sep 22, 11:13 am, Bryan Olson wrote: > One surprising result was that more of the Python > programmers surveyed use bitwise operators than are aware > of the exponentiation operator, which C does not offer. On that subject, I'd suggest that the pow() builtin (not the ** operator - just the pow() function) should also be a candidate for removal... Richard From pavlovevidence at gmail.com Sat Sep 22 01:32:37 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Sep 2007 01:32:37 -0400 Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> <46f4a2e2$0$17220$9b622d9e@news.freenet.de> Message-ID: <46f4b35b$0$19648$4c368faf@roadrunner.com> On Sat, 22 Sep 2007 05:06:42 +0000, Stargaming wrote: > On Fri, 21 Sep 2007 23:44:00 -0400, Carl Banks wrote: > >> Anyone with me here? (I know the deadline for P3 PEPs has passed; this >> is just talk.) >> >> Not many people are bit-fiddling these days. > > Why did we invent the `binary literals`_ (0b101) then? Hah, good point. Ironic that base-2 literals are going into Python, but have never been a standard part of C where they would be a LOT more useful. Carl Banks From andreaswapf at gmail.com Wed Sep 12 21:13:13 2007 From: andreaswapf at gmail.com (Andreas Wapf) Date: Wed, 12 Sep 2007 18:13:13 -0700 Subject: python & osgi Message-ID: <1189645993.968565.313760@57g2000hsv.googlegroups.com> Is there something like a osgi implementation in python? I am really impressed by the bundle system and the possibility to load and unload bundles without wasting memory. Is it even possible to do something like that in python? Would be nice to have a very small python interpreter and just load the modules as needed. From robin at reportlab.com Fri Sep 21 05:32:44 2007 From: robin at reportlab.com (Robin Becker) Date: Fri, 21 Sep 2007 10:32:44 +0100 Subject: Odd files; just left behind? In-Reply-To: <46f2bd9b$0$20143$426a74cc@news.free.fr> References: <878x725ts7.fsf@pobox.com> <46F191DF.7000908@jessikat.plus.net> <46f2bd9b$0$20143$426a74cc@news.free.fr> Message-ID: <46F38FBC.7090903@chamonix.reportlab.co.uk> Bruno Desthuilliers wrote: > Robin Becker a ?crit : >> John J. Lee wrote: >> >>> Robin Becker writes: >>> >>>> I see a folder .python-eggs in my home directory on one of our servers >>>> with various .so files >>>> >>>> ~/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so >>>> >>>> >>>> are these just left behind from some install process? >>> >>> Ah, it's about the resource extraction feature of setuptools. It's >>> possible for zipped eggs to contain resources that have to be >>> extracted to the filesystem. It puts them in the directory you saw >>> (or somewhere else -- see the docstring in my other reply). >>> >>> http://peak.telecommunity.com/DevCenter/PkgResources#resource-extraction >>> http://peak.telecommunity.com/DevCenter/setuptools#automatic-resource-extraction >>> >> ..... >> Thanks John, but why not clean up? >> > Does it needs to be "cleaned up" ? .so files (shared libs) *need* to be > extracted from the egg to be usable. Where they are extracted is IIRC > configurable... You're right! These files aren't temporary? It seems strange that the python files live with their associated lib/site-packages and the .so files are somewhere entirely different. Python 2.3.6 (#1, Jun 7 2007, 10:44:52) [GCC 3.4.4 [FreeBSD] 20050518] on freebsd6 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>> print MySQLdb.__file__ /myhome/PYTHON/lib/python2.3/site-packages/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg/MySQLdb/__init__.pyc >>> import _mysql >>> print _mysql.__file__ /myhome/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so >>> it would seem simpler to have the .so files inside the site-packages and there's the question of why this folder has to be obfuscated (name starts with .). Even if these files are "resources" why should they be assumed to belong to the user? I could make the PYTHON folder world usable, but that won't help if I make all other things in myhome private. Surely code resources belong in the same area as the code that uses them. Just another nonsense from the eggworld -- Robin Becker From harry.g.george at boeing.com Thu Sep 6 03:18:31 2007 From: harry.g.george at boeing.com (Harry George) Date: Thu, 6 Sep 2007 07:18:31 GMT Subject: Sip4.7 References: <1189084181.385917.253950@d55g2000hsg.googlegroups.com> Message-ID: luca72 writes: > Hello > i have python2.5 with sip4.6 installed on a linux machine, i need to > install sip4.7 but i get a lot of error like this: > > sip.h:525: error: expected specifier-qualifier-list before > 'PyMethodDef' > sip.h:609: error: expected specifier-qualifier-list before > 'sipForceConvertToFunc' > sip.h:666: error: expected specifier-qualifier-list before 'PyObject' > sip.h:902: error: expected specifier-qualifier-list before > 'PyTypeObject > sipint.h:81: error: expected '=', ',', ';', 'asm' or '__attribute__' > before '*' token > sipint.h:86: error: expected '=', ',', ';', 'asm' or '__attribute__' > before '*' token > sipint.h:87: error: expected '=', ',', ';', 'asm' or '__attribute__' > before '*' token > siplib.c:39: error: expected ')' before '*' token > siplib.c:41: error: expected ')' before '*' token > siplib.c:43: error: expected ')' before '*' token > siplib.c:45: error: expected ')' before '*' token > siplib.c:48: error: expected ')' before '*' token > plib.c:285: error: expected specifier-qualifier-list before 'PyObject' > siplib.c:290: error: expected '=', ',', ';', 'asm' or '__attribute__' > before 'sipWrapperType_Type' > > Have you some idea why? > > Regards > > Luca > On Linux, py2.5 installed, sip 4.6 installed: I just tried it using gcc/g++ 3.4.6 and and then a fresh start with gcc/g++ 4.2.0. Both worked fine. If you have an older gcc/g++ that might give the effect. Notice that I have a wrapper to set paths for qt4, and a wrapper to run python2.5.1. These are for convenience and should not impact results, unless of course you aren't makeing qt4 visible to the sip compile process. [sip-4.7]$ qt4 py25 configure.py This is SIP 4.7 for Python 2.5.1 on linux2. The SIP code generator will be installed in /usr/local/bin. The SIP module will be installed in /usr/local/lib/python2.5/site-packages. The SIP header file will be installed in /usr/local/include/python2.5. The default directory to install .sip files in is /usr/local/share/sip. The platform/compiler configuration is linux-g++. Creating sipconfig.py... Creating top level Makefile... Creating sip code generator Makefile... Creating sip module Makefile... [build at cola3 sip-4.7]$ gmake gmake[1]: Entering directory `/usr2/src/qt/sip-4.7/sipgen' gcc -c -pipe -O2 -w -I. -o main.o main.c gcc -c -pipe -O2 -w -I. -o transform.o transform.c gcc -c -pipe -O2 -w -I. -o gencode.o gencode.c gcc -c -pipe -O2 -w -I. -o export.o export.c gcc -c -pipe -O2 -w -I. -o heap.o heap.c gcc -c -pipe -O2 -w -I. -o parser.o parser.c gcc -c -pipe -O2 -w -I. -o lexer.o lexer.c g++ -o sip main.o transform.o gencode.o export.o heap.o parser.o lexer.o gmake[1]: Leaving directory `/usr2/src/qt/sip-4.7/sipgen' gmake[1]: Entering directory `/usr2/src/qt/sip-4.7/siplib' gcc -c -pipe -fPIC -O2 -w -I. -I/usr/local/include/python2.5 -o siplib.o siplib.c gcc -c -pipe -fPIC -O2 -w -I. -I/usr/local/include/python2.5 -o qtlib.o qtlib.c gcc -c -pipe -fPIC -O2 -w -I. -I/usr/local/include/python2.5 -o threads.o threads.c gcc -c -pipe -fPIC -O2 -w -I. -I/usr/local/include/python2.5 -o objmap.o objmap.c g++ -c -pipe -fPIC -O2 -w -I. -I/usr/local/include/python2.5 -o bool.o bool.cpp g++ -shared -Wl,--version-script=sip.exp -o sip.so siplib.o qtlib.o threads.o objmap.o bool.o gmake[1]: Leaving directory `/usr2/src/qt/sip-4.7/siplib' -- Harry George PLM Engineering Architecture From gandalf at shopzeus.com Thu Sep 6 10:41:03 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 06 Sep 2007 16:41:03 +0200 Subject: 2 python questions! In-Reply-To: <20070905091437.C7C09C3821@mailserver10.hushmail.com> References: <20070905091437.C7C09C3821@mailserver10.hushmail.com> Message-ID: <46E0117F.8030700@shopzeus.com> resist_think at hushmail.com wrote: > Hi python community! > First question has to do with threading support. There is the > following simple case: > I have a dictionnary that gets it's values -which are url's-from a > function. Sort of > > dictionnary['1'] = "http://www.google.com" > dictionnary['2'] = "http://www.python.com" > .... > > I need to fill in the dictionnary with some url's. If I do it on > the simplest way, it would be like: > > for i in range(20): > dictionnary["%s" % i] = get_urls(args) > > and wait a long long time till it finishes. Can I do it easily with > threads, without having to add too much code? Ideal case would be > if all threads start simultaneously :) > Look at thread.start_new_thread here: http://docs.python.org/lib/module-thread.html You can call a function in a separate thread, and you do not need to write a new class. (I do not like start_new_thread and I would define classes for this, but you are free to use this feature.) > Now the second question has to do with images retrieval and > manipulation. Which libraries do you propose to work with to > retrieve and resize images from the web? > I would use PIL because it is popular, easy to use, available on most platforms and has few dependencies. Check out http://www.pythonware.com/products/pil/ Best, Laszlo From http Tue Sep 25 03:49:00 2007 From: http (Paul Rubin) Date: 25 Sep 2007 00:49:00 -0700 Subject: Google and Python References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> <7xejgr68pm.fsf@ruckus.brouhaha.com> Message-ID: <7xps07w5g3.fsf@ruckus.brouhaha.com> "Hendrik van Rooyen" writes: > What is the advantage of passing the open file rather than just the > fully qualified file name and having the other process open the > file itself? The idea is that the application is a web server. The socket listener accepts connections and hands them off to other processes. That is, the file descriptors are handles on network connections that were opened by the remote client, not disk files that can be opened locally. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Sep 9 07:14:21 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 09 Sep 2007 13:14:21 +0200 Subject: Python syntax wart References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> Message-ID: <5ki2sdF3nr68U1@mid.individual.net> Lawrence D'Oliveiro wrote: > But then you can no longer use indentation to display the > two-dimensional structure of the statement. How can a statement be two-dimensional? Like a two-dimensional Turing Machine? Regards, Bj?rn -- BOFH excuse #156: Zombie processes haunting the computer From bbxx789_05ss at yahoo.com Sun Sep 16 04:47:59 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 16 Sep 2007 01:47:59 -0700 Subject: (wxPython) wx.ProgressDialog - how to cancel out of? In-Reply-To: <1189898710.639012.142170@19g2000hsx.googlegroups.com> References: <1189898710.639012.142170@19g2000hsx.googlegroups.com> Message-ID: <1189932479.661450.13280@19g2000hsx.googlegroups.com> On Sep 15, 5:25 pm, 7stud wrote: > dialog.Destroy() > timer.Stop() > win.Show() #******************** You can also change that last line to win.Destroy(), and then the user will never see the frame. From bignose+hates-spam at benfinney.id.au Wed Sep 12 00:14:00 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 12 Sep 2007 14:14:00 +1000 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <7x7imwpn1u.fsf@ruckus.brouhaha.com> Message-ID: <87abrs7c6v.fsf@benfinney.id.au> Paul Rubin writes: > TheFlyingDutchman writes: > > Python user and advocate Bruce Eckel is disappointed with the > > additions (or lack of additions) in Python 3: > > > > http://www.artima.com/weblogs/viewpost.jsp?thread=214112 > > That article is pretty weak. It is responded to by Guido here: "A Response to Bruce Eckel" -- \ "The trouble with eating Italian food is that five or six days | `\ later you're hungry again." -- George Miller | _o__) | Ben Finney From marco at yafd.de Mon Sep 24 06:49:17 2007 From: marco at yafd.de (Marco) Date: Mon, 24 Sep 2007 12:49:17 +0200 Subject: vim - what's a smarttab? In-Reply-To: <1190624225.926815.149720@50g2000hsm.googlegroups.com> References: <1190624225.926815.149720@50g2000hsm.googlegroups.com> Message-ID: <46F7962D.8000007@yafd.de> Hi "7stud", > Alternatively, what is a smarttab? in VIM type :help smarttab and you'll see the following: 'smarttab' 'sta' boolean (default off) global {not in Vi} When on, a in front of a line inserts blanks according to 'shiftwidth'. 'tabstop' or 'softtabstop' is used in other places. A will delete a 'shiftwidth' worth of space at the start of the line. When off, a always inserts blanks according to 'tabstop' or 'softtabstop'. 'shiftwidth' is only used for shifting text left or right |shift-left-right|. What gets inserted (a Tab or spaces) depends on the 'expandtab' option. Also see |ins-expandtab|. When 'expandtab' is not set, the number of spaces is minimized by using s. NOTE: This option is reset when 'compatible' is set. If you'd like to use VIM for Python make sure you have the following settings for the best result: http://www.vex.net/~x/python_and_vim.html Marco From detlev at die-offenbachs.de Sun Sep 30 12:02:39 2007 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 30 Sep 2007 18:02:39 +0200 Subject: ANN: eric 4.0.2 released Message-ID: Hi, this is to inform you about the release of eric 4.0.2. This is mainly a bugfix release. As usual you may get it at http://www.die-offenbachs.de/eric/index.html ChangeLog --------- - compatibility fixes for Debian - added '-z' to the installer to inhibit compilation of the python files - changed code to not look for the Qt4 tools in a subdirectory of the Qt installation directory (it is now required, that the Qt bin directory is in the PATH) - changed code of Python debug client to better intercept output on non-win32 systems What is eric? ------------- eric is a Python and Ruby IDE with all batteries included. It is written using PyQt4 and QScintilla2. For details see the a.m. web site. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From knipknap at gmail.com Thu Sep 6 12:13:56 2007 From: knipknap at gmail.com (Samuel) Date: Thu, 06 Sep 2007 16:13:56 -0000 Subject: ImportError depending on the calling module In-Reply-To: <1189093482.137051.73770@r29g2000hsg.googlegroups.com> References: <1189079269.279716.254560@50g2000hsm.googlegroups.com> <1189093482.137051.73770@r29g2000hsg.googlegroups.com> Message-ID: <1189095236.413270.288090@50g2000hsm.googlegroups.com> On Sep 6, 5:44 pm, Gabriel Genellina wrote: > On 6 sep, 08:47, Samuel wrote: > > Given the following directory structure: > > > --------- > > |-- Obj.py > > |-- __init__.py > > |-- foo > > | |-- FooTest.py > > | `-- __init__.py > > `-- start1.py > > --------- > > The container looks like a package (you didn't tell us the name). > Should be placed somewhere accessible thru sys.path But it is. I added the path to sys.path. > They should import the package as any other > client code, without doing any import tricks nor playing with > sys.path. Why does it matter whether I install it in sys.path or whether sys.path is modified? What's the difference? What I am doing is I ship two modules in one tarball with my software. The software is only unpacked and ran. It has to work without installation. -Samuel From fakeaddress at nowhere.org Sun Sep 30 13:49:23 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 30 Sep 2007 10:49:23 -0700 Subject: s.split() on multiple separators In-Reply-To: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> Message-ID: mrkafk at gmail.com wrote: > Hello everyone, > > OK, so I want to split a string c into words using several different > separators from a list (dels). > > I can do this the following C-like way: > > c=' abcde abc cba fdsa bcd '.split() > dels='ce ' > for j in dels: > cp=[] > for i in xrange(0,len(c)-1): The "-1" looks like a bug; remember in Python 'stop' bounds are exclusive. The indexes of c are simply xrange(len(c)). Python 2.3 and up offers: for (i, word) in enumerate(c): > cp.extend(c[i].split(j)) > c=cp > > > c > ['ab', 'd', '', 'ab', '', ''] The bug lost some words, such as 'fdsa'. > But. Surely there is a more Pythonic way to do this? When string.split() doesn't quite cut it, try re.split(), or maybe re.findall(). Is one of these what you want? import re c = ' abcde abc cba fdsa bcd ' print re.split('[ce ]', c) print re.split('[ce ]+', c) print re.findall('[^ce ]+', c) -- --Bryan From jcd at sdf.lonestar.org Tue Sep 11 07:20:28 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 11 Sep 2007 07:20:28 -0400 Subject: function to do dynamic import? In-Reply-To: <13ecb84p1ghrd64@corp.supernews.com> References: <13ecb84p1ghrd64@corp.supernews.com> Message-ID: <46E679FC.1000302@sdf.lonestar.org> bambam wrote: > import works in the main section of the module, but does > not work as I hoped when run inside a function. > > That is, the modules import correctly, but are not visible to > the enclosing (global) scope. > > Questions: > (1) Where can I read an explanation of this? > (2) Is there a work around? > > BTW, sys.modules("filename") shows that the module is > loaded, I just don't know how to use it when loaded that > way. Also, if I import again at the global scope, the module > name becomes available. > > Steve. > > --- > >>>> def gim(): >>>> > ... exec "import gamel" > ... > All you have done in this function is bind the module to the name gamel within the scope of the function. As soon as the function exits, the module goes out of scope. If you want to use it externally, return the module. def: gim(): import gamel return gamel >>>> gim() >>>> This will have to change to gamel = gim() and the rest should work as expected. >>>> sys.modules["gamel"] >>>> > > >>>> gamel >>>> > NameError: name 'gamel' is not defined > >>>> exec "import gamel" >>>> gamel >>>> > > > > From gagsl-py2 at yahoo.com.ar Sun Sep 9 23:08:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 10 Sep 2007 00:08:22 -0300 Subject: Setting stdout encoding References: Message-ID: En Sun, 09 Sep 2007 17:49:14 -0300, Fabio Zadrozny escribi?: > Does someone know if there's a way to explicitly set the > stdout/stderr/stdin > encoding that python should use? The encoding can be set using the C API for file objects - from Python code, use ctypes: py> from ctypes import * py> PyFile_SetEncoding = pythonapi.PyFile_SetEncoding py> PyFile_SetEncoding.argtypes = (py_object, c_char_p) py> if not PyFile_SetEncoding(sys.stdout, "hex"): ... raise ValueError ... py> print "Hello" Hello py> print u"Hello" 48656c6c6f -- Gabriel Genellina From n00m at narod.ru Fri Sep 21 09:58:57 2007 From: n00m at narod.ru (n00m) Date: Fri, 21 Sep 2007 06:58:57 -0700 Subject: SHOCK: WHY None? Message-ID: <1190383137.015553.235870@o80g2000hse.googlegroups.com> def f(i,sm): if i+1==len(a): print sm+a[i] return sm+a[i] else: f(i+1,sm+a[i]) a=[1,2,3,4,5] print f(0,0) >>> 15 None >>> From JYOUNG79 at kc.rr.com Wed Sep 12 15:21:22 2007 From: JYOUNG79 at kc.rr.com (JYOUNG79 at kc.rr.com) Date: Wed, 12 Sep 2007 14:21:22 -0500 Subject: xml question Message-ID: Just curious if there's any python xml parsing tools built into the Mac (OS 10.4.10 Tiger)? If so, could anyone share some simple code (or maybe point me to a web-site) of how to parse xml data from a file? For example, if I had a file that contained this: Black Light Blue Green I'd want to look in the 'colors' xml element, then look at each 'color' xml element inside and pull any that have values (which would be Black, Light Blue and Green). I'd like to know how to pull 'attributes' too. Thanks very much for your help. Jay From gagsl-py2 at yahoo.com.ar Thu Sep 27 02:35:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Sep 2007 03:35:08 -0300 Subject: Asynchronous Messaging References: <1190807252.731074.141450@k79g2000hse.googlegroups.com> <1190819912.344267.52680@50g2000hsm.googlegroups.com> <1190868212.383316.20990@57g2000hsv.googlegroups.com> Message-ID: En Thu, 27 Sep 2007 01:43:32 -0300, wink escribi?: > You are most correct, but Queue is slow compared to deque but > not for the reason I guessed. Apparently it's because deque is > implemented in C while Queue is in python. Using the program below > it looks there is about a 35:1 speed difference. That't not the reason. A Queue is built around a container, and it happens to be a deque in the default implementation. But the important thing is that a Queue is a synchronized object - it performs the necesary synchronization to ensure proper operation even from multiple threads attempting to use it at the same time. So your comparison is meaningless, apart from telling that using mutexes is not cheap. -- Gabriel Genellina From duncan.booth at invalid.invalid Wed Sep 26 09:46:03 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Sep 2007 13:46:03 GMT Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <1190805297.182232.116830@50g2000hsm.googlegroups.com> Message-ID: Paul Hankin wrote: >> I suspect that for many use patterns you could improve performance >> significantly by having two levels of invalidation for the the key >> list: in __setitem__, if the key already exists you don't need to >> discard the list in __keycache (although if a key or cmp function was >> provided it may no longer be sorted). In that case it might be >> worthwhile keeping __keycache but flagging it as needing to be sorted >> again next time it is used. Given that Python's sort is very fast on >> sorted or nearly sorted lists this could provide a worthwhile speedup >> for cases where the values change but the keys don't change often. > > More flexibly, keep a set of inserted keys that haven't yet been > included in the sorted list, and a set of deleted keys that haven't > yet been removed from the sorted list. The cache is invalid if either > of these sets are empty - and to make it valid you can choose what to > do based on the sizes of the two sets (and the sorted list). For > instance, if there's just been one insertion you're probably better > doing an insertion rather than a full resort. Of course, there's a few > nasty cases here but it's always possible to just throw away the > sorted list and reconstruct it from the dict keys when things get too > hairy (eg, the user deletes a key that's in the inserted-but-not-yet- > sorted set). > Yes that sounds good. Did you mean 'The cache is invalid if either of these sets is not empty'? If you delete a key which is in the inserted set you can simply delete it from the inserted set. The inserted set can be added to sorted list simply by appending and sorting, and the deleted keys can be removed with a list comprehension. The only other thing you need is to catch when the sort key has changed: a public method to request a resort would handle this (but of course it wouldn't actually resort until it needed the sorted keys again.) Mark's sortteddict.py modified to avoid calling __invalidate_key (and __repr__ also implemented): ------------ sorteddict.py ------------- #!/usr/bin/env python # Copyright (c) 2007 Qtrac Ltd. All rights reserved. # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # The API and implementation are based on ideas from Paul Hankin writing # on comp.lang.python. """ A dictionary that is sorted by key or by the given cmp or key function. Provides a dictionary with the same methods and behavior as a standard dict and that can be used as a drop-in replacement for a dict (apart from the constructor), but which always returns iterators and lists (whether of keys or values) in sorted order. It does not matter when items are inserted or when removed, the items in the sorteddict are always returned in sorted order. The ordering is implicitly based on the key's __lt__() (or failing that __cmp__()) method if no cmp or key function is given. The main benefit of sorteddicts is that you never have to explicitly sort. One use case is where you have a set of objects that you want to make available in various sorted orders. You could, of course, sort on demand, but if the number of objects is very large (and if you're prepared to sacrifice some memory), it may be faster to use a sorteddict. For example: >>> class PrimeMinister: ... def __init__(self, forename, surname, elected): ... self.forename = forename ... self.surname = surname ... self.elected = elected >>> byForename = sorteddict(key=lambda pm: (pm.forename, pm.surname)) >>> bySurname = sorteddict(key=lambda pm: (pm.surname, pm.forename)) >>> byName = sorteddict(key=lambda pm: (pm.surname, pm.forename, ... pm.elected), reverse=True) >>> byElected = sorteddict(key=lambda pm: pm.elected) >>> for forename, surname, elected in ( ... ("Ramsay", "MacDonald", "1924-01-22"), ... ("Arthur", "Balfour", "1902-07-11"), ... ("Herbert Henry", "Asquith", "1908-04-07"), ... ("Stanley", "Baldwin", "1924-11-04"), ... ("David", "Lloyd George", "1916-12-07"), ... ("Andrew", "Bonar Law", "1922-10-23"), ... ("Henry", "Campbell-Bannerman", "1905-12-05"), ... ("Stanley", "Baldwin", "1923-05-23"), ... ("Ramsay", "MacDonald", "1929-06-05")): ... pm = PrimeMinister(forename, surname, elected) ... byForename[pm] = pm ... bySurname[pm] = pm ... byName[pm] = pm ... byElected[pm] = pm >>> [pm.forename for pm in byForename.values()] ['Andrew', 'Arthur', 'David', 'Henry', 'Herbert Henry', 'Ramsay', \ 'Ramsay', 'Stanley', 'Stanley'] >>> [pm.surname for pm in bySurname.values()] ['Asquith', 'Baldwin', 'Baldwin', 'Balfour', 'Bonar Law', \ 'Campbell-Bannerman', 'Lloyd George', 'MacDonald', 'MacDonald'] >>> ["%s %s %s" % (pm.forename, pm.surname, pm.elected) \ for pm in byName.values()] ['Ramsay MacDonald 1929-06-05', 'Ramsay MacDonald 1924-01-22', \ 'David Lloyd George 1916-12-07', 'Henry Campbell-Bannerman 1905-12-05', \ 'Andrew Bonar Law 1922-10-23', 'Arthur Balfour 1902-07-11', \ 'Stanley Baldwin 1924-11-04', 'Stanley Baldwin 1923-05-23', \ 'Herbert Henry Asquith 1908-04-07'] >>> ["%s %s %s" % (pm.forename, pm.surname, pm.elected) \ for pm in byElected.values()] ['Arthur Balfour 1902-07-11', 'Henry Campbell-Bannerman 1905-12-05', \ 'Herbert Henry Asquith 1908-04-07', 'David Lloyd George 1916-12-07', \ 'Andrew Bonar Law 1922-10-23', 'Stanley Baldwin 1923-05-23', \ 'Ramsay MacDonald 1924-01-22', 'Stanley Baldwin 1924-11-04', \ 'Ramsay MacDonald 1929-06-05'] Thanks to Python's object references, even though there are four sorteddicts referring to the same PrimeMinister objects, only one instance of each object is held in memory. >>> files = ["README.txt", "readme", "MANIFEST", "test.py"] >>> d = sorteddict([(name, name) for name in files], ... cmp=lambda a, b: cmp(a.lower(), b.lower())) >>> d.keys() ['MANIFEST', 'readme', 'README.txt', 'test.py'] Here are a few tests for some of the base class methods that are not reimplemented: >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.get("X", 21) 21 >>> d.get("i") 4 >>> d.has_key("a") True >>> d.has_key("x") False >>> "a" in d True >>> "x" in d False >>> len(d) 6 >>> del d["n"] >>> del d["y"] >>> len(d) 4 >>> d.clear() >>> len(d) 0 >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d["i"] 4 >>> d["y"] 6 >>> d["z"] Traceback (most recent call last): ... KeyError: 'z' """ __author__ = "Mark Summerfield" __version__ = "1.1.0" class sorteddict(dict): """A dictionary that is sorted by key or by the given cmp or key function. The sorteddict always returns any list or iterator in sorted order. For best performance prefer a key argument to a cmp one. If neither is given __lt__() (falling back to __cmp__()) will be used for ordering. This particular implementation has reasonable performance if the pattern of use is: lots of edits, lots of lookups, ..., but gives its worst performance if the pattern of use is: edit, lookup, edit, lookup, ..., in which case using a plain dict and sorted() will probably be better. If you want to initialize with a dict, either use sorteddict(dict(...), ...), or create the sorteddict and then call update with the arguments normally passed to a dict constructor. """ def __init__(self, iterable=None, cmp=None, key=None, reverse=False): """Initializes the sorteddict using the same arguments as sorted() >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.items() [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] >>> str(sorteddict()) '{}' >>> e = sorteddict(d) >>> e.items() [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] """ if iterable is None: iterable = [] dict.__init__(self, iterable) self.__cmp = cmp self.__key = key self.__reverse = reverse self.__keycache = None self.__addkeys = set() self.__delkeys = set() @property def __keys(self): if self.__keycache is None: self.__keycache = dict.keys(self) self.__addkeys = set() self.__delkeys = set() self.__keycache.sort(cmp=self.__cmp, key=self.__key, reverse=self.__reverse) else: if self.__delkeys: delkeys = self.__delkeys self.__keycache = [key for key in self.__keycache if key not in delkeys] self.__delkeys = set() if self.__addkeys: self.__keycache += list(self.__addkeys) self.__addkeys = set() self.__keycache.sort(cmp=self.__cmp, key=self.__key, reverse=self.__reverse) return self.__keycache def __invalidate_key_cache(self): self.__keycache = None self.__addkeys = set() self.__delkeys = set() def __addkey(self, key): if key in self.__delkeys: del self.__delkeys[key] else: self.__addkeys.add(key) def __removekey(self, key): if key in self.__addkeys: del self.__addkeys[key] else: self.__delkeys.add(key) def update(self, *args, **kwargs): """Updates the sorteddict using the same arguments as dict >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5)) >>> d.update(a=4, z=-4) >>> d.items() [('a', 4), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('z', -4)] >>> del d["a"] >>> del d["i"] >>> d.update({'g': 9}, a=1, z=3) >>> d.items() [('a', 1), ('g', 9), ('n', 3), ('s', 1), ('t', 5), ('z', 3)] >>> e = sorteddict(dict(p=4, q=5)) >>> del d["a"] >>> del d["n"] >>> e.update(d) >>> e.items() [('g', 9), ('p', 4), ('q', 5), ('s', 1), ('t', 5), ('z', 3)] """ self.__invalidate_key_cache() dict.update(self, *args, **kwargs) @classmethod def fromkeys(cls, iterable, value=None): """A class method that returns an sorteddict whose keys are from the iterable and each of whose values is value >>> d = sorteddict() >>> e = d.fromkeys("KYLIE", 21) >>> e.items() [('E', 21), ('I', 21), ('K', 21), ('L', 21), ('Y', 21)] >>> e = sorteddict.fromkeys("KYLIE", 21) >>> e.items() [('E', 21), ('I', 21), ('K', 21), ('L', 21), ('Y', 21)] """ dictionary = cls() for key in iterable: dictionary[key] = value return dictionary def copy(self): """Returns a shallow copy of this sorteddict >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> e = d.copy() >>> e.items() [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] >>> d = sorteddict() >>> e = d.copy() >>> e.items() [] """ return sorteddict(dict.copy(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) def clear(self): """Removes every item from this sorteddict >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> len(d) 6 >>> d.clear() >>> len(d) 0 >>> d["m"] = 3 >>> d["a"] = 5 >>> d["z"] = 7 >>> d["e"] = 9 >>> d.keys() ['a', 'e', 'm', 'z'] """ self.__invalidate_key_cache() dict.clear(self) def setdefault(self, key, value): """If key is in the dictionary, returns its value; otherwise adds the key with the given value which is also returned >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.setdefault("n", 99) 3 >>> d.values() [2, 4, 3, 1, 5, 6] >>> d.setdefault("r", -20) -20 >>> d.items()[2:] [('n', 3), ('r', -20), ('s', 1), ('t', 5), ('y', 6)] >>> d.setdefault("@", -11) -11 >>> d.setdefault("z", 99) 99 >>> d.setdefault("m", 50) 50 >>> d.keys() ['@', 'a', 'i', 'm', 'n', 'r', 's', 't', 'y', 'z'] """ if key not in self: self.__addkey(key) return dict.setdefault(self, key, value) def pop(self, key, value=None): """If key is in the dictionary, returns its value and removes it from the dictionary; otherwise returns the given value >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.pop("n") 3 >>> "n" in d False >>> d.pop("q", 41) 41 >>> d.keys() ['a', 'i', 's', 't', 'y'] >>> d.pop("a") 2 >>> d.pop("t") 5 >>> d.keys() ['i', 's', 'y'] """ if key not in self: return value self.__removekey(key) return dict.pop(self, key, value) def popitem(self): """Returns and removes an arbitrary item from the dictionary >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> len(d) 6 >>> item = d.popitem() >>> item = d.popitem() >>> item = d.popitem() >>> len(d) 3 """ item = dict.popitem(self) self.__removekey(item[0]) return item def keys(self): """Returns the dictionary's keys in sorted order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.keys() ['a', 'i', 'n', 's', 't', 'y'] """ return self.__keys[:] def values(self): """Returns the dictionary's values in key order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.values() [2, 4, 3, 1, 5, 6] >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6), ... reverse=True) >>> d.values() [6, 5, 1, 3, 4, 2] >>> d = sorteddict(dict(S=1, a=2, N=3, i=4, T=5, y=6), ... cmp=lambda a, b: cmp(a.lower(), b.lower())) >>> d.keys() ['a', 'i', 'N', 'S', 'T', 'y'] """ return [self[key] for key in self.__keys] def items(self): """Returns the dictionary's items in key order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.items() [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] """ return [(key, self[key]) for key in self.__keys] def __iter__(self): """Returns an iterator over the dictionary's keys >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d) ['a', 'i', 'n', 's', 't', 'y'] """ return iter(self.__keys) def iterkeys(self): """Returns an iterator over the dictionary's keys >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d) ['a', 'i', 'n', 's', 't', 'y'] """ return iter(self.__keys) def itervalues(self): """Returns an iterator over the dictionary's values in key order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d.itervalues()) [2, 4, 3, 1, 5, 6] """ for key in self.__keys: yield self[key] def iteritems(self): """Returns an iterator over the dictionary's values in key order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d.iteritems()) [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] """ for key in self.__keys: yield key, self[key] def __delitem__(self, key): """Deletes the item with the given key from the dictionary >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> del d["s"] >>> del d["y"] >>> del d["a"] >>> d.keys() ['i', 'n', 't'] """ self.__removekey(key) dict.__delitem__(self, key) def __setitem__(self, key, value): """If key is in the dictionary, sets its value to value; otherwise adds the key to the dictionary with the given value >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d["t"] = -17 >>> d["z"] = 43 >>> d["@"] = -11 >>> d["m"] = 22 >>> d["r"] = 5 >>> d.keys() ['@', 'a', 'i', 'm', 'n', 'r', 's', 't', 'y', 'z'] """ if key not in self: self.__addkey(key) dict.__setitem__(self, key, value) def __repr__(self): """ >>> sorteddict() sorteddict() >>> sorteddict({'a':1}) sorteddict({'a': 1}) >>> def comparison(a,b): return cmp(a,b) >>> def keyfn(a): return a >>> sorteddict({'a':1}, cmp=comparison) #doctest: +ELLIPSIS sorteddict({'a': 1}, cmp=) >>> sorteddict({'a':1}, key=keyfn, reverse=True) #doctest: +ELLIPSIS sorteddict({'a': 1}, key=, reverse=True) """ args = [] if self: args.append(dict.__repr__(self)) if self.__cmp is not None: args.append('cmp=%r' % self.__cmp) if self.__key is not None: args.append('key=%r' % self.__key) if self.__reverse is not False: args.append('reverse=%r' % self.__reverse) return "%s(%s)" % (self.__class__.__name__, ', '.join(args)) def __str__(self): """Returns a human readable string representation of the dictionary The returned string is proportional in size to the number of items so could be very large. >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5)) >>> str(d) "{'a': 2, 'i': 4, 'n': 3, 's': 1, 't': 5}" >>> d = sorteddict({2: 'a', 3: 'm', 1: 'x'}) >>> str(d) "{1: 'x', 2: 'a', 3: 'm'}" """ return "{%s}" % ", ".join( ["%r: %r" % (key, self[key]) for key in self.__keys]) if __name__ == "__main__": import doctest doctest.testmod() ---------------------------------------- From attn.steven.kuo at gmail.com Tue Sep 11 02:12:32 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Mon, 10 Sep 2007 23:12:32 -0700 Subject: function to do dynamic import? In-Reply-To: <13ecb84p1ghrd64@corp.supernews.com> References: <13ecb84p1ghrd64@corp.supernews.com> Message-ID: <1189491152.601490.33880@o80g2000hse.googlegroups.com> On Sep 10, 10:52 pm, "bambam" wrote: > import works in the main section of the module, but does > not work as I hoped when run inside a function. > > That is, the modules import correctly, but are not visible to > the enclosing (global) scope. > > Questions: > (1) Where can I read an explanation of this? > (2) Is there a work around? > > BTW, sys.modules("filename") shows that the module is > loaded, I just don't know how to use it when loaded that > way. Also, if I import again at the global scope, the module > name becomes available. > > Steve. (snipped) This was recently discussed: http://groups.google.com/group/comp.lang.python/msg/f6fcdf49710cb833 -- Hope this helps, Steven From perl4hire at softouch.on.ca Thu Sep 13 03:59:31 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Thu, 13 Sep 2007 03:59:31 -0400 Subject: Coming from Perl In-Reply-To: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> Message-ID: TheFlyingDutchman wrote: > On Sep 12, 5:30 pm, Amer Neely wrote: >> I'm a complete newbie with Python, but have several years experience >> with Perl in a web environment. >> >> A question I have, if someone here is familiar with Perl, does Python >> have something like Perl's 'here document'? I've just searched and read >> some postings on generating HTML but they all seem to refer to various >> template utilities. Is this the only way, or am I missing something? I'm >> used to generating X/HTML by hand, which makes the here document in Perl >> ideal for me. Also, many times a client already existing HTML code that >> I can use in a script. >> >> -- >> Amer Neely >> w:www.webmechanic.softouch.on.ca/ >> Perl | MySQL programming for all data entry forms. >> "Others make web sites. We make web sites work!" > > I am not sure if this is what you are looking for, but Python has a > special string with 3 quotes that I believe duplicates part of the > functionality of a here document: > > myHmtlHeader = """ > > My Page > > """ > > print myHtmlHeader > > > outputs: > > > > My Page > > Well, I have checked everything I can but I'm getting '500 Internal Server Error'. The log files aren't helpful: [Thu Sep 13 03:43:00 2007] [error] [client 24.235.184.39] Premature end of script headers: /home/softouch/public_html/cgi-bin/scratch/hello.py I can't even get it to run on my home PC running Apache + Win2K. Same error. My script: #!/usr/bin/python import cgitb; cgitb.enable(display=0, logdir=".") import sys sys.stderr = sys.stdout print "Content-Type: text/html" print print """

Hello from Python

Goodbye. """ -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From Shawn at Milochik.com Tue Sep 18 14:42:30 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 18 Sep 2007 14:42:30 -0400 Subject: Newbie question In-Reply-To: <1190140395.567419.16280@k79g2000hse.googlegroups.com> References: <1190139661.046103.45440@19g2000hsx.googlegroups.com> <1190140395.567419.16280@k79g2000hse.googlegroups.com> Message-ID: <2dc0c81b0709181142h4cfd4071o4a555002a6e44e76@mail.gmail.com> On 9/18/07, koutoo at hotmail.com wrote: > On Sep 18, 1:31 pm, "Shawn Milochik" wrote: > > On 9/18/07, kou... at hotmail.com wrote: > > > > > If I have a file name: AVC1030708.14. How do I strip out certain > > > characters from the file name? I am so used to using MID, LEFT, and > > > RIGHT functions, that I have no idea how to do this in python? I have > > > had trouble as well with most newbies on finding the help. But I have > > > used the command line built in help, but with no luck. Thanks. > > > > > Kou > > > > Do you want to strip out specific characters, characters in specific > > positions, or characters matching certain patterns? > > Yes, I want specific characters in specific positions. > Try this: newString = oldString[0:3] + oldString[5:10] Some other quick examples: >>> test = "this is a test" >>> test 'this is a test' >>> fred = test[:3] + test[9:] >>> fred 'thi test' >>> test[0:5] 'this ' >>> test[:5] 'this ' >>> test[4:] ' is a test' From ldo at geek-central.gen.new_zealand Sat Sep 8 01:14:00 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 08 Sep 2007 17:14:00 +1200 Subject: platform system may be Windows or Microsoft since Vista References: <1188578878.264671.296440@k79g2000hse.googlegroups.com> <1188584386.174981.168040@z24g2000prh.googlegroups.com> <1188661487.176167.32600@57g2000hsv.googlegroups.com> <1189179369.101809.298360@g4g2000hsf.googlegroups.com> Message-ID: In message <1189179369.101809.298360 at g4g2000hsf.googlegroups.com>, p.lavarre at ieee.org wrote: > I'm thinking no priority because there is no fixing this. Why are you bothering to check an informational string? Why not check directly for the functionality you need? From larry.bates at websafe.com Mon Sep 24 12:31:11 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 24 Sep 2007 11:31:11 -0500 Subject: Converting numbers to unicode charaters In-Reply-To: <1190641342.127770.115610@y42g2000hsy.googlegroups.com> References: <1190641342.127770.115610@y42g2000hsy.googlegroups.com> Message-ID: How about: ord=''.join([unichr(int(x,16)) for x in hexs]) I don't know if its faster, but I'll bet it is. -Larry byte8bits at gmail.com wrote: > Here's how I'm doing this right now, It's a bit slow. I've just got > the code working. I was wondering if there is a more efficient way of > doing this... simple example from interactive Python: > >>>> word = '' >>>> hexs = ['42', '72', '61', '64'] >>>> for h in hexs: > ... char = unichr(int(h, 16)) > ... word += char > ... print char > ... > B > r > a > d >>>> print word > Brad > > > Each hex_number is two digits. unichr converts that to a character > that I append to previous ints that have been converted to chars. In > this way, I convert a string of hex numbers to ints to letters, to > words. > > Perhaps I'm doing it wrong... any tips? > > Thanks, > Brad > From __peter__ at web.de Wed Sep 19 07:55:53 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2007 13:55:53 +0200 Subject: Help for Otsu implementation from C References: <1190201086.468348.274850@g4g2000hsf.googlegroups.com> Message-ID: azrael wrote: > Can somone look at this > def otsu(hi): > fmax=-1.0 > border=len(hi) > for i in range(border): > if hi[i]!=0:break > for j in range(border-1,0-1,-1): > if hi[j] != 0:break > s = sum([k*hi[k] for k in range(border)]) n = sum(hi) # > product(im.size) > n1=n2=csum=0.0 > for k in range(i,j): > n1 += hi[k] > n2 = n - n1 > csum+= k * hi[k] > m1 = csum/ n1 > m2 = (s - csum)/n2 As I said in my previous post, try replacing this line > sb = n1 * n2 * (m2 - m1) with the original sb = n1 * n2 * (m1 - m2) * (m1 - m2) that has been commented out. > if sb > fmax: > fmax = sb > V=k+1 > print V > I try to implement it from C from this location. Personally, I would start with a literal translation and not try to improve it until it works. Peter From stephen.lewitowski at googlemail.com Mon Sep 10 18:44:09 2007 From: stephen.lewitowski at googlemail.com (stephen.lewitowski at googlemail.com) Date: Mon, 10 Sep 2007 15:44:09 -0700 Subject: Generating a unique identifier In-Reply-To: <13e2fgbbpsatm39@corp.supernews.com> References: <13e2fgbbpsatm39@corp.supernews.com> Message-ID: <1189464249.600013.152290@r34g2000hsd.googlegroups.com> On Sep 7, 1:03 pm, Steven D'Aprano wrote: > I have an application that will be producing many instances, using them > for a while, then tossing them away, and I want each one to have a unique > identifier that won't be re-used for the lifetime of the Python session. > > I can't use the id() of the object, because that is only guaranteed to be > unique during the lifetime of the object. > > For my application, it doesn't matter if the ids are predictable, so I > could do something as simple as this: > > def unique_id(): > n = 1234567890 > while True: > yield n > n += 1 > > unique_id = unique_id() > > while Application_Is_Running: > make_an_object(id=unique_id()) > do_stuff_with_objects() > delete_some_of_them() > > which is easy enough, but I thought I'd check if there was an existing > solution in the standard library that I missed. Also, for other > applications, I might want them to be rather less predictable. > > -- > Steven. This is very simple. Use a class variable that increments every time a new object is created. If you need to use it in a number of different types of object then you could use the code below in a metaclass and tag all of your classes with the metaclass. Unless you are making billions of objects then i think that this should suffice. class MyObj: id_count = 0 def __init__(self): self.id = self.id_count MyObj.id_count += 1 print self.id, MyObj.id_count MyObj() MyObj() From guruyaya at gmail.com Mon Sep 17 15:33:56 2007 From: guruyaya at gmail.com (guruyaya) Date: Mon, 17 Sep 2007 12:33:56 -0700 Subject: python libs for MinGW In-Reply-To: <1190024517.087476.311460@n39g2000hsh.googlegroups.com> References: <1190022847.857960.17720@19g2000hsx.googlegroups.com> <1190024517.087476.311460@n39g2000hsh.googlegroups.com> Message-ID: <1190057636.011676.103870@d55g2000hsg.googlegroups.com> Great! I've found this link http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/cygwin.html it has libpython23.def and libpython23.a all set and ready to go. Thanks anyway! Hope I could help someone. From steve at holdenweb.com Thu Sep 27 11:35:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 11:35:27 -0400 Subject: making run time changes.. In-Reply-To: <000001c80107$4f9ff120$eedfd360$@iitk.ac.in> References: <000001c80107$4f9ff120$eedfd360$@iitk.ac.in> Message-ID: Piyush Jain wrote: > Hi, > > I am new(almost) to python. I wish to making a server in which I can > make changes at run time. For example , add a method to a > class/attribute to object etc. by sending it messages. > > Can anyone help me with what features to look into and how to go about > it. Are there any similar projects? > Take a look at Pyro (Python remote objects). It can almost certainly do what you want. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From attn.steven.kuo at gmail.com Thu Sep 6 13:56:33 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 06 Sep 2007 17:56:33 -0000 Subject: Help setting default class attributes In-Reply-To: <1189099594.432512.278950@22g2000hsm.googlegroups.com> References: <1189099594.432512.278950@22g2000hsm.googlegroups.com> Message-ID: <1189101393.484939.216840@g4g2000hsf.googlegroups.com> On Sep 6, 10:26 am, rh0dium wrote: > Hi all, > > I have the following piece of code and I wanted to set the default > attributes based on a dictionary. What I am looking for is a way to > take PIPODEFAULTS and assign each one as an attribute for the class > pipo. Can someone show me how to do this by iterating over the > PIPODEFAULTS and assign them. What I would expect to be able to do is > call the class and modify them. > > example: > a = pipo() > print a.caseSensitivity > "preserve" > > a.caseSensitivity = "lower" > print a.caseSensitivity > "lower" > I infer from your example that you want to set default attributes for *instances of* class pipo (not for class pipo itself). Use setattr: class pipo(object): PIPODEFAULTS = {'caseSensitivity':'preserve', 'cellMapTable':'checkPolygon', # etc } def __init__(self, *args, **kwargs): for attr, value in pipo.PIPODEFAULTS.iteritems(): setattr(self, attr, value) a = pipo() b = pipo() print a.caseSensitivity a.caseSensitivity = 'lower' print a.caseSensitivity print b.caseSensitivity -- Hope this helps, Steven From namesagame-usenet at yahoo.com Thu Sep 13 00:27:17 2007 From: namesagame-usenet at yahoo.com (gamename) Date: Wed, 12 Sep 2007 21:27:17 -0700 Subject: Python+Expect+Win32 = Not Possible? Message-ID: <1189657637.539038.317280@k79g2000hse.googlegroups.com> Hi, Is it still the case there is no practical Expect-like module for win32? I know that cygwin can support pexpect, but that isn't an option here --- I have to use a native win32 Python version. Are there alternatives, or is it simply not an option to replicate Expect on win32 with python? All I'm trying to do is start a couple processes, wait for each to say "done" on stdout and then quit (or timeout if something went wrong). TIA, -T From paddy3118 at googlemail.com Tue Sep 25 02:59:13 2007 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 25 Sep 2007 06:59:13 -0000 Subject: Making a small change to a large XML document In-Reply-To: References: Message-ID: <1190703553.516445.98080@22g2000hsm.googlegroups.com> On Sep 24, 11:38 pm, Dan Stromberg wrote: > Say I want to take an existing XML document, and change the value="9997" > and value="9998" to two different numbers, without changing any of the > rest of the document - not even changing comments or indentation, if > avoidable. > > What's the best way of doing it in python? > > > > > > > > > My .xml file is full of such beans. > > I've played around with minidom a little in the past, and I'm targetting > python 2.5.1. > > Thanks! If it was machine formatted, regular XML, on a unix box then I'd use sed: sed -e 's/value="9997"/value="zzz"/g;s/value="9998"/value="ZZZ"/g' \ infile > outfile It would work for what you said, but if other modifications are needed then it is short enough to throw away if necessary and write a larger script in Python. - Paddy. From nfrancken at gmail.com Thu Sep 6 17:32:08 2007 From: nfrancken at gmail.com (windandwaves) Date: Thu, 06 Sep 2007 14:32:08 -0700 Subject: why should I learn python Message-ID: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Can someone tell me why I should learn python? I am a webdeveloper, but I often see Python mentioned and I am curious to find out what I am missing out on. Thank you Nicolaas From junchi.tang at gmail.com Thu Sep 20 11:31:25 2007 From: junchi.tang at gmail.com (junchi.tang at gmail.com) Date: Thu, 20 Sep 2007 08:31:25 -0700 Subject: os.path.getmtime() and compare with a date type Message-ID: <1190302285.127448.288010@22g2000hsm.googlegroups.com> Hi, I am new to python and are tryint to write a simple program delete log files that are older than 30 days. So I used os.path.getmtime(filepath) and compare it with a date but it does not compile. threshold_time = datetime.date.today() - datetime.timedelta(days=30) mod_time = os.path.getmtime(file_path) if( mod_time < threshold_time): #delete file However the interpreter complains at the if line, say "can't comapre datetime.date to int How can I covert one of them to make it work? Thank you! From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Sep 20 12:51:06 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 20 Sep 2007 18:51:06 +0200 Subject: Lookup values from one table to another based on a value In-Reply-To: <1190305331.584560.218880@g4g2000hsf.googlegroups.com> References: <1190298876.689060.44540@d55g2000hsg.googlegroups.com> <46f2930a$0$9505$426a74cc@news.free.fr> <1190305331.584560.218880@g4g2000hsf.googlegroups.com> Message-ID: <46f2a4e6$0$15456$426a74cc@news.free.fr> koutoo at hotmail.com a ?crit : > On Sep 20, 10:34 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> kou... at hotmail.com a ?crit : (snip) >>> Normally in Access I would just use a Dlookup and be done with it, or >>> use a Recordset in VB. Thanks guys. >> What about using a database ? Like SQLite ? > > Ah, yes, that would appear to be a better means to retrieve data. I > visited the site, which version should I download? Thanks. The latest, unless you have reasons to choose an old one !-) From kevinar18 at hotmail.com Mon Sep 17 21:53:25 2007 From: kevinar18 at hotmail.com (Kevin Ar18) Date: Mon, 17 Sep 2007 21:53:25 -0400 Subject: Looking for web software in Python. Message-ID: Are any of the following pieces of web software available in Python (under a non-copyleft license like BSD or MIT or Python license)? Mailing list - with web accessable archive and list maintenance. Source control Wiki System Again, only non-copyleft licenses like MIT, BSD, or public domain. Or would I be better off with PHP? BTW, does anyone know where that project is that was working on a forum made with Python? _________________________________________________________________ More photos; more messages; more whatever ? Get MORE with Windows Live? Hotmail?. NOW with 5GB storage. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_5G_0907 From nutsbreaker2 at gmail.com Wed Sep 26 13:52:32 2007 From: nutsbreaker2 at gmail.com (nutsbreaker2 at gmail.com) Date: Wed, 26 Sep 2007 10:52:32 -0700 Subject: Guitars for 0$ !!!!! Message-ID: <1190829152.350303.280950@o80g2000hse.googlegroups.com> http://free-guitars.blogspot.com/ From iddw at hotmail.com Wed Sep 12 09:33:38 2007 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 12 Sep 2007 06:33:38 -0700 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> Message-ID: <1189604018.520338.162520@57g2000hsv.googlegroups.com> On Sep 12, 5:21 am, Charles Fox wrote: > I've just started playing around with Python, as a possible > replacement for a mix of C++, Matlab and Lisp. The language looks > lovely and clean with one huge exception: I do a lot of numerical > modeling, so I deal with objects (like neurons) described > mathematically in papers, by equations like > a_dot = -k(a-u) > In other languages, this translates nicely into code, but as far as I > can tell, Python needs the ugly: > self.a_dot = -self.k(self.a-self.u) > For large equations this is going to make my code seriously unreadable > to the point of needing to switch back to Matlab -- and it seems to go > against everything else about python's simplicity and elegance. Am I It goes back to the Zen of Python (import this): Explicit is better than implicit. And it's a boon to future maintainers of your code > missing something? Is there something like a 'with' command that lets > me set the scope, like > > with self: > .a_dot = -.k(.a-.u) The name "self" is just a convention. You can give it any name you wish. Using "s" is common. As others have mentioned, you can also provide local synonyms if the dot syntax is too onerous. But make sure you use the member access syntax if the result of an expression is an immutable type. For example, I assume a_dot is a mutable type, such as a list. If so, then you could simply use a_dot, k, a, u = self.a_dot, self.k, self.a, self.u a_dot = -k(a-u) However, if it's an immutable type, such as a scalar, strung, or tuple, you need self.a_dot = -k(a-u) And it gets trickier if you have members taking intermediate values... > > It's premature to make language suggestions as I am new to the That's for sure ;-) Regards, -=Dave From mail at timgolden.me.uk Wed Sep 5 09:10:03 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 05 Sep 2007 14:10:03 +0100 Subject: StringIO MySQL data blob Image problem In-Reply-To: References: Message-ID: <46DEAAAB.8040008@timgolden.me.uk> dimitri pater wrote: > I am trying to insert an image, which is stored as a blob in MySQL, > into a table using Reportlab. [... snip stuff involving StringIO and getvalue / tostring etc. ...] > This is also the string I see in the table, in stead of the actual image. [.. snip more stuff ...] > that returns: > ?????lbo?q?5???\???????Y|A???,?????"??m3Z???f??""N?,?????I??t"?b5?@xq?'?k????s??d???????1??? > ?^?J?*?C(r)?{:t??_??????jo?? > ?C(c)???[)?gN???X?i etc... etc... > and return an UnicodeDecodeError when I try to insert this into the table Well, I'm mystified. Not by your results: that exactly what I expected to get, but because you're doing everything *except* manipulating an image and putting it into a PDF via ReportLab. Just in case you're under any other impression, there's no such thing as "a graphical image" in a database or in computer memory. There's just a bunch of bytes which -- given the right libraries -- can be represented as an image. Given other libraries, such as the ones which print them to a text console, they can be represented as a stream of apparent gibberish. You need to use the former; you're using the latter. It's a while since I did anything with ReportLab but I seem to remember that you can pass it an image filename and, (possibly as long as you have the Python Imaging Library installed), it will insert it into the PDF you're building as a flowable. Assuming I'm right, get hold of the bytes in your MySQL query, save them as "temp.jpg" or whatever, and then pass that filename along to ReportLab. Feel free to come back and ask if those instructions aren't clear enough. TJG From steve at holdenweb.com Wed Sep 26 19:11:14 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 26 Sep 2007 19:11:14 -0400 Subject: regex with specific list of string In-Reply-To: <1190847411.999166.87060@w3g2000hsg.googlegroups.com> References: <1190821357.753909.178210@50g2000hsm.googlegroups.com> <1190827835.3397.76.camel@dot.uniqsys.com> <1190847411.999166.87060@w3g2000hsg.googlegroups.com> Message-ID: james_027 wrote: > Hi all, > >> This is fine IMO since the OP didn't specify the opposite. >> > > Thanks for all your replies, though I don't understand quite well the > going argument? What do you mean when you say "the OP didn't specify > the opposite"? > > There reason for using regex is because I am going to use it in > Django's URL pattern > Carsten was pointing out that the pattern I gave you would match any string that *began* with one of the month names, as I didn't include an element to force a match of the end of the string. I did this because I assumed you were most interested in finding out how to match one of a number of alternate strings, and this would likely only be a part of your final pattern. If you already have what you need you really don't need to pay much attention to the rest: it's just geeks picking nits! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From software at ginstrom.com Wed Sep 12 21:14:07 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Thu, 13 Sep 2007 10:14:07 +0900 Subject: Coming from Perl In-Reply-To: References: <87wsuv5r83.fsf@benfinney.id.au> Message-ID: <002801c7f5a3$620afc70$0203a8c0@MOUSE> > On Behalf Of Amer Neely > I saw that and I guess that is the closest thing. In Perl I can do .. > > print < > > Hello > > > EndHTML >>> data = dict(title="Python Rocks!", content="

I heart Python

") >>> template = """ %(title)s %(content)s """ >>> print template % data Python Rocks!

I heart Python

>>> You might also want to check out string.Template (http://docs.python.org/lib/node40.html), or even move on to one of the many, many templating languages (Mako, Cheetah, Kid, etc.) Regards, Ryan Ginstrom From steve at holdenweb.com Thu Sep 6 17:33:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Sep 2007 14:33:55 -0700 Subject: parsing long `To' and 'Cc' from email In-Reply-To: <46E076F4.20704@fmed.uba.ar> References: <46E06244.80308@fmed.uba.ar> <46E076F4.20704@fmed.uba.ar> Message-ID: <46E07243.5070402@holdenweb.com> Gerardo Herzig wrote: > Steve Holden wrote: [...] >>> >> Have you tried using email.utils.getaddresses()? >> >> regards >> Steve >> >> > No, i was not. And it works just perfect! One day i will make a hard > question!! I wonder why this getaddresess() function is not a method > into the HeaderParser class. > > Ok, so my content-filter can continue now. Thanks Steve! Don't thank me, thank Barry Warsaw - he wrote most of this code. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From neilscad at hotmail.com Sat Sep 29 16:30:33 2007 From: neilscad at hotmail.com (neil) Date: Sun, 30 Sep 2007 09:30:33 +1300 Subject: python 2.5 and 3gb switch References: <46FDF800.5030504@v.loewis.de> <46fe1e79$0$2816$9b622d9e@news.freenet.de> Message-ID: Since I was last here I found someone who is willing to do a 3gb python build for me who builds Blender as well. I am pretty sure python is just not recognising the extra space. Apparently there is a python module used in the 3gb Blender build I have that may be contributing too although the script I have requires a full python install. I will see how his assistance goes. Thanks for your willing help guys. regards Neil From python at cx.hu Tue Sep 4 16:09:56 2007 From: python at cx.hu (Ferenczi Viktor) Date: Tue, 4 Sep 2007 22:09:56 +0200 Subject: Py3K: Ensuring future compatibility between function annotation based tools Message-ID: <200709042209.56401.python@cx.hu> There could be future compatibility issues between libraries using the new function annotation scheme: PEP 3107 -- Function Annotations See also: http://www.python.org/dev/peps/pep-3107/ Let's assume two hypotetic libraries: mashaller: provides JSON marshalling support typechecker: provides runtime type checking Let's write a simple function that uses both libraries: from marshaller import marshall, JSON from typechecker import check, Str @marshall @check def splitter(s:Str) -> JSON: return s.split(',') The function get a singe string and returns JSON encoded list of it's comma separated parts. Both libraries can be used together without problems as long as all arguments and the return value are annotated by at most one annotator object. However, there could be frequent use cases, when multiple annotations for a single argument or return value is required: @marshall @check def splitter(s:(JSON, Str)) -> JSON: return s.split(',') The above function does the same as the first one, but accepts a JSON encoded string. This solution works only if both libraries can cooperatively handle composite annotator objects and do not complain about unknown ones. (Note, that the order of processing depends on the order of the decorators, not on the order of the annotators.) Let me suggest the following recommendation for tool developers: If you encounter a tuple as the annotator, then iterate it and process only the known ones while silently skipping all others. Keep all existing annotators if you include new ones. Create a tuple if you find an existing annotator and need to include a second one. Extend existing tuples by replacing them with new ones including new annotator(s). (Possibly lists or dictionaries in place of tuples? I don't think so. Ideas?) This way all annotation based tools will be compatible and should work seamlessly without imposing any unnecessary constraint. Anybody with a better solution? Any comments? Greetings, Viktor From stargaming at gmail.com Sun Sep 23 10:53:27 2007 From: stargaming at gmail.com (Stargaming) Date: 23 Sep 2007 14:53:27 GMT Subject: can I run pythons IDLE from a command line?? References: <1190475878.971841.253140@k79g2000hse.googlegroups.com> Message-ID: <46f67de7$0$8442$9b622d9e@news.freenet.de> On Sat, 22 Sep 2007 17:53:09 +0200, Thomas Jollans wrote: > On Saturday 22 September 2007, tedpottel at gmail.com wrote: >> Hi, >> Is their a version of pythons IDLE that will run in a dos command line? >> The reason is that I would like to be able to run python code >> interactively from my parable by connecting to my desktop using remote >> command line or a telnet program. > > The Python interpreter should do fine. If your PATH environment variable > is set up correctly, just run "python", otherwise it's somewhere in your > Python installation directory. If you don't want to miss IDLE's advantages, `IPython `_ might be interesting for you. Stargaming From wizzardx at gmail.com Sat Sep 8 16:35:50 2007 From: wizzardx at gmail.com (David) Date: Sat, 8 Sep 2007 22:35:50 +0200 Subject: Organizing Code - Packages In-Reply-To: <1189280539.449868.169910@22g2000hsm.googlegroups.com> References: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> <46e17143$0$6189$426a74cc@news.free.fr> <1189183088.922537.18290@r34g2000hsd.googlegroups.com> <87r6laa0ir.fsf@rudin.co.uk> <46e1a0bc$0$7689$9b4e6d93@newsspool2.arcor-online.net> <1189280539.449868.169910@22g2000hsm.googlegroups.com> Message-ID: <18c1e6480709081335t18a91309nc647f0caa33f7272@mail.gmail.com> > How do import statements that are declared at the top of a python > module work? http://docs.python.org/tut/node8.html From stargaming at gmail.com Thu Sep 20 09:25:41 2007 From: stargaming at gmail.com (Stargaming) Date: 20 Sep 2007 13:25:41 GMT Subject: frange() question References: Message-ID: <46f274d4$0$7146$9b622d9e@news.freenet.de> On Thu, 20 Sep 2007 09:08:17 -0400, George Trojan wrote: > A while ago I found somewhere the following implementation of frange(): > > def frange(limit1, limit2 = None, increment = 1.): > """ > Range function that accepts floats (and integers). Usage: > frange(-2, 2, 0.1) > frange(10) > frange(10, increment = 0.5) > The returned value is an iterator. Use list(frange) for a list. > """ > if limit2 is None: > limit2, limit1 = limit1, 0. > else: > limit1 = float(limit1) > count = int(math.ceil(limit2 - limit1)/increment) return (limit1 + > n*increment for n in range(count)) > > I am puzzled by the parentheses in the last line. Somehow they make > frange to be a generator: > >> print type(frange(1.0, increment=0.5)) > > But I always thought that generators need a keyword "yield". What is > going on here? > > George Consider the following: def foo(): yield 1 def bar(): return foo() Still, ``type(bar())`` would be a generator. I don't want to tell you anything wrong because I don't know how generators are implemented on the C level but it's more like changing foo's (or frange's, in your example) return value. HTH, Stargaming From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 24 12:42:27 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 24 Sep 2007 18:42:27 +0200 Subject: Can a base class know if a method has been overridden? In-Reply-To: <1190648887.051630.168520@r29g2000hsg.googlegroups.com> References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> <46f7d897$0$25150$426a74cc@news.free.fr> <1190648887.051630.168520@r29g2000hsg.googlegroups.com> Message-ID: <46f7e8df$0$21052$426a74cc@news.free.fr> Ratko a ?crit : >> If your use case is to make sure a given ('abstract') method has been >> overriden, the canonical solution is to raise NotImplementedError in the >> base class's implementation > > I am not really interested in forcing the subclass to implement a > method. I am interested in knowing *whether* it did implement it or > not. > > >> Else, this may be possible using a custom metaclass (or possibly just >> specializing the __new__ method), but there may be better solutions >> (depending on what you're really trying to do).. > > I have a base class EvtHandler that has methods defined to handle > certain events. You then subclass from EvtHandler and override the > methods for the events you want to receive. If a method has been > overridden, the base class will automatically register for those > events to make sure that they are even delivered to this handler > (which is why I would need to know whether a method has been > overridden or not). Of course, there are other ways of doing this > which would require a bit more work from the subclass... I just > thought this would be a neat "automatic" way of registering for > events. > > For example: > > class EvtHandler: > def __init__(self): > if onKey is overridden: > register_for_key_events() > > def onKey(self): > pass > > > class MyHandler(EvtHandler): > def onKey(self): > # do something here.... > Ok. The simplest solution, then, is simply to not implement the method in the base class, ie: class EvtHandler: def __init__(self): if hasattr(self, 'onKey'): register_for_key_events() #def onKey(self): # pass class MyHandler(EvtHandler): def onKey(self): # do something here.... Another solution is to compare the functions wrapped by the methods: class EvtHandler: def __init__(self): onKey = getattr(self, 'onKey') if onKey.im_func is EvtHandler.onKey.im_func: register_for_key_events() def onKey(self): pass class MyHandler(EvtHandler): def onKey(self): # do something here.... HTH From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Sep 20 20:39:54 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 21 Sep 2007 02:39:54 +0200 Subject: executing list of methods (and collecting results) References: Message-ID: <5lgi6qF81sotU1@mid.individual.net> Gerardo Herzig wrote: > I want the collect_validators() method is to execute any of the > above methods, and collect their names as items of a list (wich > will be the collect_validators() return value). (inside class definition -- untested) validators = {"is a number": is_really_a_number, "is even": is_even, "is greater than zero": is_greater_than_zero} def collect_validators(self): return [desc for desc, func in self.validators.items() if func()] > My first approach is: ... no method, but a generator. Executing it will give you a generator object instead of a result list. > [code] > def collect_validators(self): > v_dict = { 'is_really_a_number': is_really_a_number, > 'is_even': is_even, > 'is_greater_than_zero', is_greater_than_zero > } > > for name, meth in v_dict.items(): > result = meth() > if result: yield name > [/code] > > I wondering if is this a good pattern to apply, i like the way it > looks like, at least to me it looks `natural', IMHO, it doesn't look natural. It depends on what you want to achieve. This generator will need to be iterated over until it is "exhausted". > but...im calling every method twice here? No. Methods are only called if you apply the function call operator, "()". BTW, I hope you don't really want to test a number to be greater than zero, or even, by using an own method, respectively, just to test this. Regards, Bj?rn -- BOFH excuse #321: Scheduled global CPU outage From Brian.McCann at viziant.net Fri Sep 7 12:47:32 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Fri, 7 Sep 2007 12:47:32 -0400 Subject: passing command line arguments Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE32D@efmailx> Hi, when I run the script show_args2.py # ./show_args2.py 1 2 3 I get the following error Traceback (most recent call last): File "./show_args2.py", line 4, in ? print 'The arguments of %s are "%s"' %s \ NameError: name 's' is not defined ##################################### this is the script #!/usr/bin/python import sys, string print 'The arguments of %s are "%s"' %s \ (sys.argv[0], string.join(sys.argv[1:])) any help would be greatly appreciated -Brian -------------- next part -------------- An HTML attachment was scrubbed... URL: From shriphanip at gmail.com Tue Sep 25 04:15:55 2007 From: shriphanip at gmail.com (Shriphani) Date: Tue, 25 Sep 2007 08:15:55 -0000 Subject: obtaining multiple values from a function. Message-ID: <1190708155.683502.93040@r29g2000hsg.googlegroups.com> hello all, If I have a function that loops over a few elements and is expected to throw out a few tuples as the output, then what should I be using in place of return ? Shriphani Palakodety. From fperez.net at gmail.com Sun Sep 9 17:26:36 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Sun, 09 Sep 2007 15:26:36 -0600 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? References: <46DEFD2E.5050205@sbcglobal.net> <87tzq898e2.fsf@wilson.homeunix.com> <200709060119.28607.python@cx.hu> Message-ID: Ferenczi Viktor wrote: > Properties are very useful, since ordinary attribute access can be > transparently replaced with properties if the developer needs to add code > when it's set or needs to calculate it's value whenever it is read. > > As an additional benefit this could allow developers to implement change > events for properties that allows any number of observers to monitor > property changes. This could be very useful in GUI programming, for > example. You might be interested in Traits: http://code.enthought.com/traits/ Beautiful technology, precisely for the use cases you list, amongst many others. cheers, f From python at cx.hu Tue Sep 4 17:16:08 2007 From: python at cx.hu (Ferenczi Viktor) Date: Tue, 4 Sep 2007 23:16:08 +0200 Subject: doctest and decorators In-Reply-To: <2bfa72fa0709041401g63e5f6aem55bcabe9e00134b@mail.gmail.com> References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> <200709042236.37712.python@cx.hu> <2bfa72fa0709041401g63e5f6aem55bcabe9e00134b@mail.gmail.com> Message-ID: <200709042316.08263.python@cx.hu> > @functools.wraps Correctly: @functools.wraps(f) Pass the function to be wrapped by the decorator to the wraps function. Regards, Viktor From steve at holdenweb.com Tue Sep 4 01:58:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Sep 2007 22:58:37 -0700 Subject: parameter list notation In-Reply-To: <1188882641.899594.212400@22g2000hsm.googlegroups.com> References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> <1188882641.899594.212400@22g2000hsm.googlegroups.com> Message-ID: TheFlyingDutchman wrote: > Well I did a search on "Python variable length arguments" and found a > hit that seems to explain the *fields parameter: > > When you declare an argment to start with '*', it takes the argument > list into an array. > > def foo(*args): > print "Number of arguments:", len(args) > print "Arguments are: ", args > > Well done. The ** notation allows you to collect arbitrary keyword arguments into a dictionary (whose name is kw in the example you gave). With such a formal parameter any keyword argument is acceptable for a call (unless it duplicates a key value). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From erik at myemma.com Fri Sep 28 17:36:43 2007 From: erik at myemma.com (Erik Jones) Date: Fri, 28 Sep 2007 16:36:43 -0500 Subject: Python 3.0 migration plans? In-Reply-To: <1191009608.985644.271160@50g2000hsm.googlegroups.com> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> <1191008702.579795.141180@r29g2000hsg.googlegroups.com> <1191009608.985644.271160@50g2000hsm.googlegroups.com> Message-ID: <4EB17941-E293-4B86-8B01-3DC79324BF1F@myemma.com> On Sep 28, 2007, at 3:00 PM, TheFlyingDutchman wrote: > On Sep 28, 12:45 pm, George Sakkis wrote: >> On Sep 28, 3:29 pm, TheFlyingDutchman wrote: >> >>> One issue I have with this group and that I encountered many >>> years ago >>> in the Perl group is that there is no separate group >>> comp.lang.python.beginner where you can ask questions without >>> getting >>> hit with RTFM! and the like. >> >> Which shows once again that you're trying to break the world >> record of >> being wrong in as many sentences as possible: >> >> http://mail.python.org/mailman/listinfo/tutor >> >> You would do yourself (and others) a favor by migrating there for a >> few weeks or months. >> >> George > > Being in a land where every nit can be picked, I am surprised that you > offered up a mailing list when I was asking for a newsgroup. I'm usually pretty quiet on this list. That's what I find is the best way to participate. However, I'm going to have to speak up and point out that that response is exactly the type of comment and/or reasoning that everyone here is trying to explain to you. The resources are available for you to educate yourself. Semantic arguments such as this are, at best, at a junior high level. You are completely free to ask any question (about Python) you want here -- just don't argue with the people giving you the answers. And, to address the actual content of that response: nobody, online or off, in newsgroups or on mailing lists, likes a nitpick. So, please, quit. I'd prefer you didn't leave and, instead, decided to actually, actively get along with the others here. I think some of the question you've begun threads with have been both good and valid. It's just that you need some work on your e-people skills, man. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From michele.simionato at gmail.com Thu Sep 20 01:30:09 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 20 Sep 2007 05:30:09 -0000 Subject: Mixin classes and single/multiple inheritance In-Reply-To: <87myviuee5.fsf@benfinney.id.au> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> <877immvye0.fsf_-_@benfinney.id.au> <1190257864.945639.199230@k79g2000hse.googlegroups.com> <87y7f2uhpp.fsf@benfinney.id.au> <1190262607.684957.49610@57g2000hsv.googlegroups.com> <87myviuee5.fsf@benfinney.id.au> Message-ID: <1190266209.617774.145250@n39g2000hsh.googlegroups.com> On Sep 20, 6:52 am, Ben Finney wrote: > Michele Simionato writes: > > Since the language we have does have multiple inheritance, let's > > use it to implement mixins. > > ... > > So, multiple inheritance is giving us very little for the point of > > view of mixins; OTOH, multiple inheritance is giving us a lot of > > headaches for what concerns cooperative methods. > > I may be obtuse, but the above statements seem to be professing > contradictory viewpoints. > > Do you think multiple inheritance should or should not be used in > Python to do what mixins do? If you want to use mixins in Python, then you should use multiple inheritance, since multiple inheritance is already there, no point in reinventing it. OTOH, one may argue that there are better approaches than mixins, but this is another topic. > > My point was that even if Python had been implemented without > > multiple inheritance, it would have been simple to implement mixins, > > or by copying the methods, or by dispatching with __getattr__. > > Can you give a code example of how you think mixins should be > implemented in Python, assuming the absence of multiple inheritance? I have various example somewhere in my hard disk, but now it is time for me to go to job, so you will have to wait ;) But I am sure others here can provide examples. Michele Simionato From cjw at sympatico.ca Tue Sep 18 07:44:36 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 18 Sep 2007 07:44:36 -0400 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <740c3aec0709130730k2226e9abmbf5defb579b77660@mail.gmail.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <740c3aec0709130730k2226e9abmbf5defb579b77660@mail.gmail.com> Message-ID: BJ?rn Lindqvist wrote: > On 9/12/07, Dave Hansen wrote: >> The name "self" is just a convention. You can give it any name you >> wish. Using "s" is common. > > Not it's not common. And the name "self" is a convention codified in > PEP8 which you shouldn't violate. > > And I agree with the OP that the convention is really annoying. > > self.rect.width = self.foo(self.rect.x + self.rect.y) * self.boo() > > is much less concise than > > s.rect.width = s.foo(s.rect.x + s.rect.y) * s.boo() > Yes, but the OP went a step further, he suggested: .rect.width = .foo(.rect.x + .rect.y) * .boo() Among the many responses, I didn't spot anyone who dealt with this issue. Does this preceding "." create parsing problems? Colin W. From truelixin at gmail.com Thu Sep 6 01:44:20 2007 From: truelixin at gmail.com (truelixin at gmail.com) Date: Wed, 05 Sep 2007 22:44:20 -0700 Subject: Using wild character In-Reply-To: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> Message-ID: <1189057460.762343.187230@22g2000hsm.googlegroups.com> i hope this may help you. countries = ["india","africa","atlanta","artica","nigeria"] filtered = filter(lambda item: item.startswith('a'), l) From rami.mawas at gmail.com Wed Sep 12 16:55:22 2007 From: rami.mawas at gmail.com (rami.mawas at gmail.com) Date: Wed, 12 Sep 2007 20:55:22 -0000 Subject: Implementing a fixed size stack for an RPN Calculator Message-ID: <1189630522.152326.3040@d55g2000hsg.googlegroups.com> I have implemented an RPN calculator in python but now I would like to make the stack size fixed. how can I transform the user's RPN expression from a stack overflow to a computable expression. For instance, if my stack size is 2 then the some expression can't be computed but could be transformed as following: Non computable expression: 1 2 3 + + --> stack size of 3 is needed Computable expression: 1 2 + 3 + --> stack size of 2 is needed How can I define a formal way of transforming the non computable expression to computable one. My RPN only implements: + - x % From steve at holdenweb.com Tue Sep 11 18:15:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 18:15:20 -0400 Subject: Python.org mirror In-Reply-To: References: Message-ID: <46E71378.40505@holdenweb.com> Stream Service || Mark Scholten wrote: > Dear sir, madam, > > Stream Service would be happy to provide a free mirror for python.org. > We also host nl.php.net for free and we are happy to support more > opensource websites with free hosting. > > Could you inform me about the options to become an officiel python.org > mirror? > You may or may not be aware that the main Python site is hosted in the Netherlands. Many thanks for your offer, but we have in any case discontinued the addition of new mirrors. See item 14 in http://www.python.org/psf/records/board/minutes/2007-03-12/ regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From trekker182 at gmail.com Mon Sep 17 17:15:29 2007 From: trekker182 at gmail.com (Shawn Minisall) Date: Mon, 17 Sep 2007 17:15:29 -0400 Subject: qa Message-ID: <46EEEE71.80108@gmail.com> I'm trying to get a space in between these two strings but it's ignoring the space in between when it prints. >>> string.capwords (string.join([s1 + " " + s2])) * 3 'Spam Ni!Spam Ni!Spam Ni!' >>> From roy at panix.com Mon Sep 3 22:04:36 2007 From: roy at panix.com (Roy Smith) Date: Mon, 03 Sep 2007 22:04:36 -0400 Subject: So what exactly is a complex number? References: Message-ID: Boris Borcic wrote: > Complex numbers are like a subclass of real numbers I wouldn't use the term "subclass". It certainly doesn't apply in the same sense it applies in OOPLs. For example, you can't say, "All complex numbers are real numbers". In fact, just the opposite. But, it's equally wrong to say, "real numbers are a subclass of complex numbers", at least not if you believe in LSP (http://en.wikipedia.org/wiki/Liskov_substitution_principle). For example, it is true that you can take the square root of all complex numbers. It is not, however, true that you can take square root of all real numbers. Don't confuse "subset" with "subclass". The set of real numbers *is* a subset of the set of complex numbers. It is *not* true that either reals or complex numbers are a subclass of the other. From mail at timgolden.me.uk Fri Sep 7 03:47:19 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Sep 2007 08:47:19 +0100 Subject: Finding specific date ranges In-Reply-To: <1189122086.388859.146670@r34g2000hsd.googlegroups.com> References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> <1189122086.388859.146670@r34g2000hsd.googlegroups.com> Message-ID: <46E10207.3040900@timgolden.me.uk> Zentrader wrote: > On Sep 6, 7:56 am, kyoso... at gmail.com wrote: >> December 31, 2006 January 13, 2007 # doesn't earn >> January 14, 2007 January 27, 2007 # does earn >> January 28, 2007 February 10, 2007 # doesn't >> February 11, 2007 February 24, 2007 # does > > Am I over simplifying if I say that since it appears to be a two week > pay period, the date has to be greater than the 11th unless the first, > or first and second, are on a weekend, in which case it would be > 12 > or > 13? Or a reasonable facsimile thereof, depending on whether or > not the two week period is Saturday through Friday. I think it's one of those things where the neatest answer could well depend on the sort of heuristic you mention. As a rule, when I come across this kind of requirement, I tend to put the most general solution in place, unless a *real* optimisation is clearly called for. In my experience, this makes it much easier for the next person who looks at the code, typically years later, even if that's me! (This is has just happened to me this week, having to review a date-related calculation to do the repost frequency of the adverts my company deals with. I wrote the original code five years ago, and commented it intelligently, but I *still* had to work through the code twice when we had a problem with a particular cycle!) TJG From bj_666 at gmx.net Sat Sep 22 12:32:28 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2007 16:32:28 GMT Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> <1190454275.282176.90830@k79g2000hse.googlegroups.com> <5lkbr8F8gic1U6@mid.uni-berlin.de> <1190469537.393019.133070@k79g2000hse.googlegroups.com> Message-ID: <5lkucrF8gic1U8@mid.uni-berlin.de> On Sat, 22 Sep 2007 06:58:57 -0700, Kay Schluehr wrote: > On Sep 22, 1:15 pm, Marc 'BlackJack' Rintsch wrote: >> On Sat, 22 Sep 2007 02:44:35 -0700, Kay Schluehr wrote: >> > I checked out Io once and I disliked it. I expected Io's prototype OO >> > being just a more flexible variant of class based OO but Io couples a >> > prototype very closely to its offspring. When A produces B and A.f is >> > modified after production of B also B.f is modified. A controls the >> > state of B during the whole lifetime of B. I think parents shall not >> > do this, not in real life and also not in programming language >> > semantics. >> >> Well it's like Python: inherited slots (attributes) are looked up in the >> ancestors. It should be easy to override `Object clone` in Io, so all >> slots of the ancestor are shallow copied to the clone, but I guess this >> might break existing code. At least for your own code you could introduce >> a `realClone` slot. > > But in class based OO most relevant attributes are defined during > object construction and they can't be simply changed by setting a > class attribute. Later you often create new attributes as but on > object level. You do not overuse the object/class relationship to > broadcast changes to all objects. You don't do this in Io either. It's really like Python in this respect. There's an `init` slot that gets called by (the default) `clone` and you set "instance attributes" there, for example mutables so they are not shared by all clones. Ciao, Marc 'BlackJack' Rintsch From fabiofz at gmail.com Sun Sep 9 16:49:14 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sun, 9 Sep 2007 17:49:14 -0300 Subject: Setting stdout encoding Message-ID: Hi, Does someone know if there's a way to explicitly set the stdout/stderr/stdin encoding that python should use? What I'm trying to do is make python recognize that the Eclipse output accepts a different encoding (such as utf-8, cp1252, etc). More details on the problem can be found at: http://sourceforge.net/tracker/index.php?func=detail&aid=1580766&group_id=85796&atid=577329 The closest I could get to solving this was running a script that went on and ran the script that should really be executed through the code below (which I think is a lousy solution, but the only one I could see so far -- and I also have to keep different versions of that for jython, as in jython that works without any workaround): ---------------------- script giving error ---------------------- print u"unicode char: >>\xF6<<" ---------------------- script I have to run to make it work ---------------------- if __name__ == '__main__': import sys reload(sys) #without the reload setdefaultencoding is not accessible sys.setdefaultencoding('cp1252') #go on and make an execfile on the module we actually want to run (we have to be careful not to mess up that namespace) .... Thanks, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From zzbbaadd at aol.com Thu Sep 20 18:17:17 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 20 Sep 2007 15:17:17 -0700 Subject: about __str__ In-Reply-To: References: Message-ID: <1190326637.338109.139640@57g2000hsv.googlegroups.com> I read here recently that the __str__ method of a list calls the __repr__ method of each of its members. So you need to add a __repr__ method to your class: class CmterIDCmts: def __init__(self,commiterID,commits): self.commiterID_=long(commiterID) self.commits_=long(commits) def __str__(self): s="" s+="<"+str(self.commiterID_)+":"+str(self.commits_)+">" return s def __repr__(self): return self.__str__() From stef.mientki at gmail.com Thu Sep 13 16:44:27 2007 From: stef.mientki at gmail.com (stef mientki) Date: Thu, 13 Sep 2007 22:44:27 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <46e995d1$0$16120$9b4e6d93@newsspool1.arcor-online.net> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> <5ktfb5F5ctrvU1@mid.individual.net> <46e98e01$0$30383$9b4e6d93@newsspool4.arcor-online.net> <46e9921e$0$26251$426a74cc@news.free.fr> <46e995d1$0$16120$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <46E9A12B.20208@gmail.com> Wildemar Wildenburger wrote: > Bruno Desthuilliers wrote: > >> OTHO, simple math-illeterate programmers like me will have hard time >> maintaining such a code. >> > Certainly, but again: Such main people are not the intended audience. > The code is for people that know how to read these equations. I think a > general rule of (any form of) writing is to write with your audience in > mind. I always do that and happily, that audience is usually naked. > > > Wouldn't Mathematica, Maple or MathCad be a far better choice ? cheers, Stef Mientki From pramodmc4u at gmail.com Sun Sep 30 13:53:37 2007 From: pramodmc4u at gmail.com (pramodmc4u at gmail.com) Date: Sun, 30 Sep 2007 17:53:37 -0000 Subject: code for number guessing by computer Message-ID: <1191174817.788812.40360@y42g2000hsy.googlegroups.com> hi, please help me,,,,,, a newbie.......send me code for a programme in which the computer tell u the number that u guessed............ From paddy3118 at googlemail.com Sat Sep 15 02:36:32 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 15 Sep 2007 06:36:32 -0000 Subject: regexp search on infinite string? In-Reply-To: References: <1189802940.518794.129130@r29g2000hsg.googlegroups.com> Message-ID: <1189838192.090251.292620@g4g2000hsf.googlegroups.com> On Sep 15, 2:57 am, James Stroud wrote: > Paddy wrote: > > Lets say i have a generator running that generates successive > > characters of a 'string' > >>From what I know, if I want to do a regexp search for a pattern of > > characters then I would have to 'freeze' the generator and pass the > > characters so far to re.search. > > It is expensive to create successive characters, but caching could be > > used for past characters. is it possible to wrap the generator in a > > class, possibly inheriting from string, that would allow the regexp > > searching of the string but without terminating the generator? In > > other words duck typing for the usual string object needed by > > re.search? > > > - Paddy. > > re.search & re.compile checks for str or unicode types explicitly, so > you need to turn your data into one of those before using the module. > > buffer = [] > while True: > buffer.append(mygerator.next()) > m = re.search(pattern, "".join(buffer)) > if m: > process(m) > buffer = [] > > James Thanks James. From gagsl-py2 at yahoo.com.ar Sun Sep 30 07:21:41 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Sep 2007 08:21:41 -0300 Subject: which language allows you to change an argument's value? References: <1191149233.346818.246170__37520.6361794428$1191149499$gmane$org@22g2000hsm.googlegroups.com> Message-ID: En Sun, 30 Sep 2007 07:47:13 -0300, Summercool escribi?: > I wonder which language allows you to change an argument's value? > like: > > foo(&a) { > a = 3 > } > > n = 1 > print n > > foo(n) # passing in n, not &n > print n > > and now n will be 3. I think C++ and PHP can let you do that, using > their reference (alias) mechanism. And C, Python, and Ruby probably > won't let you do that. What about Java and Perl? > > is there any way to prevent a function from changing the argument's > value? > > isn't "what i pass in, the function can modify it" not a desireable > behavior if i am NOT passing in the address of my argument? For one C++ lets you use const references - and any well written code should use const& whenever the argument is not to be modified. A function/method may have two overloaded versions, with and without the const modifier. So, if the argument *is* to be modified, there is no point in avoiding it (unless the interfase is not well designed in the first place) In Python, rebinding a name inside a function does not have any effects in the caller. That is, def foo(a): a = 3 n = 1 foo(n) print n will still print 1, not 3. -- Gabriel Genellina From lasses_weil at klapptsowieso.net Mon Sep 3 07:34:36 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Mon, 03 Sep 2007 13:34:36 +0200 Subject: TypeError: 'module object is not callable' In-Reply-To: <1188816626.021956.281040@22g2000hsm.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> Message-ID: <46dbf14d$0$4530$9b4e6d93@newsspool3.arcor-online.net> christophertidy at hotmail.com wrote: > Thank you for your help that seems to have done the trick. > You are correct Diez B. Roggisch that I come from a java background! > > I have a new tiny problem I can't understand either. > Withing Step.py I have the following method > > def isCompleted(self): > "Check whether data step has been processed" > return self.isCompleted > Java, ey? ;) Why do you write a method that jut returns a variable anyway? Forget that. Python doesn't need getters and setters. > Then within main.py I simply wish to print the value of isCompleted > which I try to do by the following > print 'Magn completed status is',a.isCompleted() > > Which returns the following error: > a.isCompleted() > TypeError: 'int' object is not callable > That is (I think) because you have two things called "isCompleted" in your class: The variable of type int (which BTW had better been of type bool) and the method. As I said, just scrap the method. In Python it's perfectly OK to expose variables in the API. If you still want getters and setters, use look into properties. /W From dotancohen at gmail.com Sun Sep 16 12:06:08 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 16 Sep 2007 18:06:08 +0200 Subject: Cannot formulate regex In-Reply-To: <1189957099.952690.275320@n39g2000hsh.googlegroups.com> References: <1189957099.952690.275320@n39g2000hsh.googlegroups.com> Message-ID: <880dece00709160906y68a28321nb3512ad422027797@mail.gmail.com> On 16/09/2007, Paul McGuire wrote: > On Sep 16, 10:18 am, "Dotan Cohen" wrote: > > I'd like to filter spam from a certain company. Here are examples of > > strings found in their spam: > > Mega Dik > > Mega D1k > > MegaDik > > Mega. Dik > > M eg ad ik > > M E _G_A_D_ IK > > M_E_G. ADI. K > > > > I figured that this regex would match all but the second example, yet > > it matches none: > > |[^a-z]m[^a-z]e[^a-z]g[^a-z]a[^a-z]d[^a-z]i[^a-z]k[^a-z]|i > > > > What would be the regex that matches "megadik" regardless of whatever > > characters are sprinkled throughout? > > > > Thanks in advance. > > > > Dotan > > Or you could try using "MegaRegex"! I do and my girlfriend can't stop > talking about it! :) > Hehe, thanks Paul. I should have though of the * myself... Got the job done. Dotan Cohen http://what-is-what.com http://gibberish.co.il -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Sep 12 08:00:41 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 12 Sep 2007 14:00:41 +0200 Subject: cpython list __str__ method for floats References: <13ectngf3aeqrb0@corp.supernews.com> <5kndseF4iskqU1@mid.individual.net> <13eehfo8nr5eu1d@corp.supernews.com> Message-ID: <5kq2n9F4uhr0U1@mid.individual.net> [david] wrote: > Leaving aside the question of why str should return repr, str doesn't "return" repr. str returns a "nice string representation" of an object. This "nice string representation" of a list is the opening square bracket, the repr of its contents seperated by comma, and the closing square bracket. Here, it *only* makes sense to have a list printed with the repr of their contents. > 13.300000000000001 is not 'the float in full precision': > it is an arbitrary translation of the float. Do you know IEEE 754? > The idea that 13.3 is a 'rounded' value for the number, > and that 13.300000000000001 is not a 'rounded' value of > the number, is a common error of intuitive mathematics. I'm intrigued how /you/'d explain this, please do explain. > I hope that when you say that this is a FAQ, you don't > mean that the community has solidified on this naive > interpretation :~) No, I mean that your complaint is not at all new. Reading the archives you could have learned a lot about this topic. Regards, Bj?rn -- BOFH excuse #247: Due to Federal Budget problems we have been forced to cut back on the number of users able to access the system at one time. (namely none allowed....) From steve at holdenweb.com Fri Sep 21 15:21:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Sep 2007 15:21:58 -0400 Subject: xml-rpc timeout In-Reply-To: References: <2_WdnTQ86eZNY27bnZ2dnUVZ_jCdnZ2d@comcast.com> Message-ID: Jd wrote: > Steve Holden wrote: >> Jd wrote: >>> Hi >>> I have a multi-threaded application. For certain operations to the >>> server, I would like to explicitly set timeout so that I get correct >>> status from the call and not timed out exception. >>> Does anyone know how to go about doing it ? >>> >> The easiest way is to use socket.setdefaulttimeout() to establish a >> longer timeout period for all sockets, I guess. It's difficult to >> establish different timeouts for individual sockets when they aren't >> opened directly by your own code (though each socket does also have a >> method to set its timeout period). >> >> regards >> Steve > > Ya.. the problem here is that I donot have acces to the socket. I have > written my own transport etc.. but when the socket is getting created, > there is no context for the method and where I know what method I am > going to call, I do not have access to socket. > But you are writing Python, so you can write import socket socket.setdefaulttimeout(60) and this will apply to all sockets that on't have their own explicit timeouts applied. Give it a try. > I would have thought this to be an easy thing to achieve. In order to > make xml-rpc easy to use.. it has become difficult to control. > You might also ask why your server *is* timing out. Timeouts shouldn't be a normal feature of TCP communications. Is there a reason of rthis anomalous behavior, or are you perhaps trying to solve the wrong problem? > Anyone have any other ideas ? > That's all from me! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From michael at stroeder.com Wed Sep 5 03:05:01 2007 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 05 Sep 2007 09:05:01 +0200 Subject: FCGI app reloading on every request In-Reply-To: References: <46DCDE59.8060109@animats.com> <46DCE052.40708@v.loewis.de> Message-ID: John Nagle wrote: > This is running on a dedicated server at APlus.net, > running Red Hat Fedora Core 6, Python 2.5, and managed with Plesk 8.2. > I just turned on fcgid from the Plesk control panel ("Physical hosting > setup page for domain", checked "FastCGI"), and enabled the standard > FCGI configuration, which is actually mod_fcgid. > [..] > What's wierd is that the ".fcgi" suffix files get executed at all. > I'd expect them to be either ignored or run properly with FCGI. Then I would ask APlus.net what's really going on there. Ciao, Michael. From paddy3118 at googlemail.com Sat Sep 22 10:50:12 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 22 Sep 2007 14:50:12 -0000 Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <46f49740$0$32514$4c368faf@roadrunner.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> Message-ID: <1190472612.942736.325850@w3g2000hsg.googlegroups.com> Sorry Carl, I think *you* may not have much need for bitwise operators but others, including myself do. No matter what the usage found, I would think replacing bitwise operators by function calls a retrograde step. - Paddy. From rbonvall at gmail.com Fri Sep 7 13:55:57 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Fri, 07 Sep 2007 17:55:57 -0000 Subject: Speed of Python In-Reply-To: References: <1189185542.798286.168880@50g2000hsm.googlegroups.com> Message-ID: <1189187757.418355.58690@r34g2000hsd.googlegroups.com> On Sep 7, 1:37 pm, "wang frank" wrote: > Hi, > Here is the matlab code: > function [z]=bench1(n) > for i=1:n, > for j=1:1000, > z=log(j); > z1=log(j+1); > z2=log(j+2); > z3=log(j+3); > z4=log(j+4); > z5=log(j+5); > z6=log(j+6); > z7=log(j+7); > z8=log(j+8); > z9=log(j+9); > end > end > z = z9; > > I am not familiar with python, so I just simply try to reproduce the same > code in python. > If you think that my python script is not efficient, could you tell me how > to make it more efficient? > > > import math > > > def bench1(n): > > > for i in range(n): > > > for j in range(1000): The range(1000) call creates a list of 1000 elements each time it is called. This is expensive. You could try something like the following: def bench1a(n): r = range(1000) for i in range(n): # reuse the list for j in r: ... def bench1b(n): for i in range(n): # don't use a list at all j = 0 while j < 1000: ... I'm no expert on Python optimization either, so I cannot guarantee that both are the best way to write this algorithm. > > > [...] > > > m=j+1 This step also doesn't occur in the Matlab code. Hope this helps, although maybe I'm not the right person to talk about optimization, and I haven't measured my code. -- Roberto Bonvallet From laurent.pointal at limsi.fr Mon Sep 17 04:44:12 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 17 Sep 2007 10:44:12 +0200 Subject: Python "with" In-Reply-To: References: Message-ID: Ivan Voras a ?crit : > I know it can be almost always done by using a temporary variable: > > tmp = some.big.structure.or.nested.objects.element > tmp.member1 = something > tmp.member2 = something > > but this looks ugly to me.) The ugly part is the 'tmp' name, try to choose a name with a proper meaning about what it is really, and it become clean and readable: filerefs = some.big.structure.or.nested.object.with.file.references filerefs.encoding = "utf-8" filerefs.name = "MyFileName.txt" filerefs.use_quotes = True Isn't it ? From gagsl-py2 at yahoo.com.ar Mon Sep 24 22:08:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Sep 2007 23:08:12 -0300 Subject: Regular Expressions: Can't quite figure this problem out References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> Message-ID: En Mon, 24 Sep 2007 22:53:57 -0300, Robert Dailey escribi?: > Any easier way to do a 'replace' then using start(), end(), and slicing > operations? I'm currently doing it manually. Yes: forget about regular expressions. ElementTree does that for free: source = """ """ import xml.etree.ElementTree as ET tree = ET.XML(source) print ET.tostring(tree) output: -- Gabriel Genellina From mhellwig at xs4all.nl Tue Sep 4 22:13:15 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Wed, 05 Sep 2007 04:13:15 +0200 Subject: Parse or Pass? In-Reply-To: <46DD916E.4000201@v.loewis.de> References: <1188917032.271543.236420@d55g2000hsg.googlegroups.com> <46DD916E.4000201@v.loewis.de> Message-ID: <46de108a$0$29358$e4fe514c@dreader19.news.xs4all.nl> Martin v. L?wis wrote: > If I extrapolate my experience with German IT language, I > think people often use terminology they have not fully > understood. I often ask my students what the difference > between "eingeben", "ausgeben", "?bergeben" und > "zur?ckgeben" is when they start saying that "die > Funktion gibt das Ergebnis aus". > > Regards, > Martin Interesting, I lived my early childhood in Germany and somehow, now I see it all written in once, I have the feeling I get more confused. So would you agree with my interpretation? Eingeben = Input: (A bit of) data from outside the function Ausgeben = Output: (A bit of) data to display, network connection or file Zur?ckgeben = Return: (altered)(bits of) data (from Input) to Output Can I assume that Return in general always means that the particular function has exited with that? If not what is the difference then between Output and Return? Another thing is that with the above statement the opposite could be true too, meaning that Input in the German meaning would only been done when the function is initiated but how do you call the other input then? The appropriate German word would be "Zugeben", which translates to Enter (Giving too). And then we have "?bergeben" which translates to throughput (giving over), which in my view is just something that gets data in and puts it out, contextually unaltered. But would that do that with exiting the function or not? If it's not both what's the other one called? "?bernemen" perhaps (Taking over)? Hmm feels like textbook classics, only if I knew which book, probably programming 101 :-) -- mph From bdesth.quelquechose at free.quelquepart.fr Thu Sep 27 14:49:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 27 Sep 2007 20:49:40 +0200 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: <46fbfb6f$0$8896$426a74cc@news.free.fr> Neil Cerutti a ?crit : (snip) > > Vim has Python integration if you want to control it with Python > scripts. Cool! Of course, Vim needs such a capability more than > Emacs, which has the very cool elisp scripting language. FWIW, emacs is programmable in Python too IIRC. From laurent.pointal at limsi.fr Mon Sep 17 09:39:50 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 17 Sep 2007 15:39:50 +0200 Subject: Saving parameters between Python applications? In-Reply-To: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> Message-ID: Stodge a ?crit : > I'm trying to do the following. I have a Python application that is > run: > > python app1.py --location=c:\test1 > > What I want to do is save the location parameter, so I can then do (in > the same window): > > python app2.py > > And have app2.py automatically have access to the value of "location". > > Now, the difficult part is, that in another window I want to do: > > python app1.py --location=c:\test2 > python app2.py > > And have app2.py automatically get c:\test2 as the location. So the > two windows (consoles) are isolated from each other. > > I thought I could use os.environ, but that doesn't save the variable > for applications that are run afterwards in the same window. > > Any suggestions? May use simple file in known place: $HOME/.myprefs $HOME/.conf/myprefs Or host specific configuration API: WindowsRegistry HKEY_CURRENT_USER\Software\MySociety\MyApp\myprefs See os.getenv, and _winreg Windows specific module. See also standard ConfigParser module Hope you know how to read/write files. From db3l.net at gmail.com Sat Sep 1 18:58:47 2007 From: db3l.net at gmail.com (David Bolen) Date: Sat, 01 Sep 2007 18:58:47 -0400 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> Message-ID: Roy Smith writes: > Anybody remember Scribe? (raising hand) OT, but I still have a bunch of Scribe source documents from college. Of course, as I attended CMU where it originated I suppose that's not unusual. Definitely pre-WYSIWYG, but one of the first to separate presentation markup from structure (very much in line with later stuff like SGML from IBM although I don't recall the precise timing relation of the two), including the use of styles. I personally liked it a lot (I think the markup syntax is easier on the eyes than the *ML family). If I remember correctly, for a while there, it was reasonably common to see Scribe-like markup in newsgroups (e.g,. "@begin(flame)" and @end("flame") or "@b[emphasis]") before SGML/XML/HTML became much more common (" ... "). -- David From steve at holdenweb.com Tue Sep 11 23:16:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 23:16:30 -0400 Subject: Get the complete command line as-is In-Reply-To: <1189566000.793354.308420@19g2000hsx.googlegroups.com> References: <1189566000.793354.308420@19g2000hsx.googlegroups.com> Message-ID: wangzq wrote: > Hello, > > I'm passing command line parameters to my browser, I need to pass the > complete command line as-is, for example: > > test.py "abc def" xyz > > If I use ' '.join(sys.argv[1:]), then the double quotes around "abc > def" is gone, but I need to pass the complete command line ("abc def" > xyz) to the browser, how can I do this? > > I'm on Windows. > > Thanks. > You can't. The quotes are gobbled by the command-line processor before your program ever gets the chance to see them. You could try writing your own command shell ... or learn how to quote the quotes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at REMOVE-THIS-cybersource.com.au Sat Sep 22 22:53:34 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 23 Sep 2007 02:53:34 -0000 Subject: Factory function with keyword arguments Message-ID: <13fbl9ertj5es12@corp.supernews.com> I'm writing a factory function that needs to use keywords in the produced function, not the factory. Here's a toy example: def factory(flag): def foo(obj, arg): if flag: # use the spam keyword to method() return obj.method(spam=arg) else: # use the ham keyword return obj.method(ham=arg) return foo Problem: the test of which keyword to use is done every time the produced function is called, instead of once, in the factory. I thought of doing this: def factory(flag): if flag: kw = 'spam' else: kw = 'ham' def foo(obj, arg): kwargs = dict([(kw, arg)]) return obj.method(**kwargs) return foo Is this the best way of doing this? Are there any alternative methods that aren't risky, slow or obfuscated? Before anyone suggests changing the flag argument to the factory to the name of the keyword, this is only a toy example, and doing so in my actual code isn't practical. -- Steven. From daniel.j.larsson at gmail.com Wed Sep 5 06:20:44 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Wed, 5 Sep 2007 12:20:44 +0200 Subject: doctest and decorators In-Reply-To: <1188970537.297655.256600@r34g2000hsd.googlegroups.com> References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> <200709042316.08263.python@cx.hu> <2bfa72fa0709041452o72d9a98fp939852d061a2cda3@mail.gmail.com> <200709050009.46380.python@cx.hu> <2bfa72fa0709041529g9d5ac22hce3a55d5357b1a1c@mail.gmail.com> <1188970537.297655.256600@r34g2000hsd.googlegroups.com> Message-ID: <2bfa72fa0709050320o65dc2d62u854799833bce665e@mail.gmail.com> The __module__ attribute is set, but the problem is the test in doctest.py(DocTestFinder._from_module) ... elif inspect.isfunction(object): return module.__dict__ is object.func_globals elif inspect.isclass(object): return module.__name__ == object.__module__ elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) On 9/5/07, Michele Simionato wrote: > > > En Tue, 04 Sep 2007 19:29:11 -0300, Daniel Larsson > > escribi?: > > > > > > > > > On 9/5/07, Ferenczi Viktor wrote: > > > > >> > > @functools.wraps(f) > > >> > > Pass the function to be wrapped by the decorator to the wraps > > >> function. > > >> > Ooops, right. That doesn't change the fact that decorated functions > > >> get > > >> > hidden from doctest though. > > > > > I have no issue when the decorator is defined in the same module as > the > > > decorated function, my problem is running doctests on functions using > an > > > imported decorator. Having to implement the decorator in every source > > > module > > > isn't very practical. > > I cannot reproduce your problem. Using functools.wraps > the __module__ attribute is set correctly and everything > works, even for decorators defined in separated modules. > Care to post a complete example of what you are doing? inspect.isfunction(object) returns true, but the function's func_globals isn't the same as the module's __dict__, since the function is actually my decorator wrapper function. Here's my two files again: # decorator.py import functools def simplelog(f): @functools.wraps(f) def new_f(*args, **kwds): print "Wrapper calling func" return f(*args, **kwds) return new_f # test.py from decorator import simplelog @simplelog def test(): """ This test should fail, since the decorator prints output. Seems I don't get called though >>> test() 'works!' """ return "works!" if __name__ == '__main__': import doctest doctest.testmod() Michele Simionato > > P.S. for some reason your messages are not appearing on > Google groups, I see only the replies. > > Weird... afraid I have no clue why not :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Wed Sep 5 08:15:27 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 05 Sep 2007 14:15:27 +0200 Subject: creating really big lists References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> Message-ID: <874pi92tr4.fsf@mulj.homelinux.net> Dr Mephesto writes: > I would like to create a pretty big list of lists; a list 3,000,000 > long, each entry containing 5 empty lists. My application will > append data each of the 5 sublists, so they will be of varying > lengths (so no arrays!). > > Does anyone know the most efficient way to do this? I have tried: > > list = [[[],[],[],[],[]] for _ in xrange(3000000)] You might want to use a tuple as the container for the lower-level lists -- it's more compact and costs less allocation-wise. But the real problem is not list allocation vs tuple allocation, nor is it looping in Python; surprisingly, it's the GC. Notice this: $ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> t0=time.time(); l=[([],[],[],[],[]) for _ in xrange(3000000)]; >>> t1=time.time() >>> t1-t0 143.89971613883972 Now, with the GC disabled: $ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gc >>> gc.disable() >>> import time >>> t0=time.time(); l=[([],[],[],[],[]) for _ in xrange(3000000)]; >>> t1=time.time() >>> t1-t0 2.9048631191253662 The speed difference is staggering, almost 50-fold. I suspect GC degrades the (amortized) linear-time list building into quadratic time. Since you allocate all the small lists, the GC gets invoked every 700 or so allocations, and has to visit more and more objects in each pass. I'm not sure if this can be fixed (shouldn't the generational GC only have to visit the freshly created objects rather than all of them?), but it has been noticed on this group before. If you're building large data structures and don't need to reclaim cyclical references, I suggest turning GC off, at least during construction. From Michael.Coll-Barth at VerizonWireless.com Sat Sep 29 16:23:01 2007 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Sat, 29 Sep 2007 16:23:01 -0400 Subject: Program inefficiency? In-Reply-To: References: <1191094332.393736.231390@w3g2000hsg.googlegroups.com> Message-ID: <20070929202305.8A2301E4005@bag.python.org> > -----Original Message----- > From: thebjorn > > On Sep 29, 9:32 pm, stdazi wrote: > > On Sep 29, 6:07 pm, Michael.Coll-Ba... at VerizonWireless.com wrote: > > > > > You did not mention the OS, but because you are using > > > "pathname\editfile.txt", it sounds like you are using an > MS OS. From > > > past experience with various MS OSes, I found that as the > number of > > > files in a directory increases the slower your process > runs for each > > > file. > > > > how so? > > Not entirely sure why, but some of the ms docs allude to the fact that > there is a linked list involved (at least for fat-style disks). > Wow! Talk about defending one's self ( me ). I took stdazi's question to mean why I thought it was an MS OS issue. And, yes, you are correct about the linked-list. Although, I do not know if that was the reason for the my problem. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From kostaspaxos at yahoo.gr Sat Sep 15 12:34:45 2007 From: kostaspaxos at yahoo.gr (Konstantinos Pachopoulos) Date: Sat, 15 Sep 2007 19:34:45 +0300 Subject: find and remove "\" character from string Message-ID: <46EC09A5.7050609@yahoo.gr> Hi, i have the following string s and the following code, which doesn't successfully remove the "\", but sucessfully removes the "\\". >>> s="Sad\\asd\asd" >>> newS="" >>> for i in s: ... if i!="\\": ... newS=newS+i ... >>> newS 'Sadasd\x07sd' I have also read the following, but i do not understand the "...and the remaining characters have been mapped through the given translation table, which must be a string of length 256". Can some explain? *translate*( table[, deletechars]) Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. For Unicode objects, the translate() method does not accept the optional deletechars argument. Instead, it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or |None|. Unmapped characters are left untouched. Characters mapped to |None| are deleted. Note, a more flexible approach is to create a custom character mapping codec using the codecs module (see encodings.cp1251 for an example). From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Sep 14 05:48:30 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 14 Sep 2007 11:48:30 +0200 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com><46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net><1189618530.872819.136450@57g2000hsv.googlegroups.com><1189619033.968437.286580@g4g2000hsf.googlegroups.com><5kr8vlF53m8gU3@mid.individual.net><1189643616.826715.58150@d55g2000hsg.googlegroups.com><5ksoaoF5am8cU1@mid.individual.net><1189701793.466307.93210@g4g2000hsf.googlegroups.com><5ktfjqF5ctrvU2@mid.individual.net><46e98fd8$0$27757$426a34cc@news.free.fr> <5ktre7F5ig0vU1@mid.individual.net> Message-ID: <5kv3neF5mo3hU3@mid.individual.net> Terry Reedy wrote: > No it does not. The method wrapping is done at runtine. The > compiler is ignorant of the wrapping that will be done. Agreed, after reading the docs. >>>> dis.dis(f) > 1 0 LOAD_GLOBAL 0 (c) > 3 LOAD_ATTR 1 (meth) > 6 CALL_FUNCTION 0 > 9 RETURN_VALUE > > The function gets wrapped as a bound method as part of LOAD_ATTR. > When the compiler sees (args), it does not know and does not > care about the > particular type that will become. It just assumes that it > will be > callable and emits the code to call it. Consider That's interesting. BTW, do you know something (apart from the dis docs) that's worth reading if you're interested in Python byte code? Regards, Bj?rn -- BOFH excuse #138: BNC (brain not connected) From guettli.usenet at thomas-guettler.de Wed Sep 19 11:08:29 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 19 Sep 2007 15:08:29 GMT Subject: AttributeError: How to list existing attributes? References: <5lc8lbF79ba8U1@mid.individual.net> <5lc9mtF7hll5U1@mid.uni-berlin.de> Message-ID: <5lcsbdF7ku5hU1@mid.individual.net> Diez B. Roggisch wrote: > Thomas Guettler wrote: > >> Hi, >> >> how can you list the attributes of an object if you catch an >> AttributeError? >> >> I couldn't find a reference in the exception object, which >> points to the object. >> >> I want to call dir() on the object to list the user the known >> attributes. >> >> Is there a way to find the object by inspecting the stacktrace? > > By looking at the code at the line the stacktrace lists? And at least for > me, there is a type-information as well: Hello, I want to customize the debug tracebacks displayed in django. It is not to find one particular error. That's why changing the source is not a solution. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From steve at holdenweb.com Wed Sep 26 12:49:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 26 Sep 2007 12:49:10 -0400 Subject: regex with specific list of string In-Reply-To: <1190821357.753909.178210@50g2000hsm.googlegroups.com> References: <1190821357.753909.178210@50g2000hsm.googlegroups.com> Message-ID: james_027 wrote: > hi, > > how do I regex that could check on any of the value that match any one > of these ... 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', > 'sep', 'oct', 'nov', 'dec' > > Thanks >>> patr = re.compile('jan|feb|mar|apr|may|jun|jul|aug|sep|nov|oct|dec') >>> patr.match("jul") <_sre.SRE_Match object at 0x7ff28ad8> >>> patr.match("nosuch") >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From zentraders at gmail.com Thu Sep 27 20:58:52 2007 From: zentraders at gmail.com (Zentrader) Date: Thu, 27 Sep 2007 17:58:52 -0700 Subject: ValueError: too many values to unpack In-Reply-To: References: Message-ID: <1190941132.060599.89300@57g2000hsv.googlegroups.com> On Sep 27, 9:46 am, Shawn Minisall wrote: > I am trying to read a few lines of a file with multiple values, the rest > are single and are reading in fine. > > With the multiple value lines, python says this "ValueError: too many > values to unpack" > > I've googled it and it says that happens when you have too few or too > many strings that don't match with the variables in number your trying > to assign them too. Below are the lines in reading in: > > line 3 - 19.18 29.15 78.75 212.10 > line 4 - 100 20 410.29 > And this is the code I'm using: > > #read withdrawls from file on line3 > line = infile.readline() > #split withdrawls up > withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") > > #read deposits from file on line4 > line = infile.readline() > #split deposits up > deposit1, deposit2, deposit3 = string.split(line, "\t") > > I have 4 strings to match line 3 and 3 to match the 3 on line 4...any > thoughts? > > thx A string.split returns a list so you don't have to know how many elements there are beforehand. A simple example withdraw = line.split("\t") if len(withdraw) == 3: match_3(withdraw) elif len(withdraw) == 4:: match_4(withdraw) else: print "line.split() is not 3 or 4", withdraw From michele.simionato at gmail.com Thu Sep 20 11:36:31 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 20 Sep 2007 15:36:31 -0000 Subject: super() doesn't get superclass In-Reply-To: References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> Message-ID: <1190302591.145295.213170@k79g2000hse.googlegroups.com> On Sep 20, 4:31 pm, "Marshall T. Vandegrift" wrote: > Michele Simionato writes: > > I am not against mixins (even if I am certainly very much against the > > *abuse* of mixins, such as in Zope 2). What I would advocate (but I > > realize that it will never happen in Python) is single inheritance + > > mixins a la Ruby. > > Ruby might be a bad example here. Although the Ruby language syntax > only supports single inheritance, mixins are implemented as multiple > inheritance under the hood. That is, inheriting from a class and > including a class as a mixin modifies the sub-/mixing class in exactly > the same way. > > -Marshall The difference is that there is no cooperation, so you don't need to bang your head in order to understand the method resolution order. Michele Simionato From vinay_sajip at yahoo.co.uk Mon Sep 24 18:29:38 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 24 Sep 2007 15:29:38 -0700 Subject: strange behavious of the logging module? In-Reply-To: References: <1190643051.084144.230220@o80g2000hse.googlegroups.com> Message-ID: <1190672978.233964.232900@g4g2000hsf.googlegroups.com> On Sep 24, 4:29 pm, Peter Otten <__pete... at web.de> wrote: > Vinay Sajip wrote: > > On Sep 24, 8:03 am, Peter Otten <__pete... at web.de> wrote: > > >> It would still be a good idea to file a bug report. > > > Not sure where the bug is. The script below, when called, prints > > "Information" to the console and "INFO some_func Information" to > > mc_rigid.log, as I would expect. (Python 2.5.1) > > I get > > $ python vinaj.py > Information > $ cat mc_rigid.log > INFO info Information > > Maybe a platform issue (I'm on Ubuntu 7.04)? > > It seems Logger.findCaller() gets puzzled by the following discrepancy: > > >>>logging.info.func_code.co_filename > > 'logging/__init__.py'>>>logging._srcfile > > '/usr/lib/python2.5/logging/__init__.py' > > I don't think I have messed with paths manually on that machine, by the > way. > This is a known bug, and not specifically related to logging, though it sometimes manifests itself via logging: http://bugs.python.org/issue1180193 Regards, Vinay From steve at REMOVE-THIS-cybersource.com.au Sun Sep 16 05:50:39 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 09:50:39 -0000 Subject: Needless copying in iterations? References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> Message-ID: <13epv3fnb6bak15@corp.supernews.com> On Sun, 16 Sep 2007 15:05:55 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> In *general* the compiler can't tell, but in specific cases it could. A >> (hypothetical) optimizing compiler would tell the difference between: >> >> for item in alist[1:5]: >> print item # no possible side-effects > > The 'print' statement converts the 'item' to a str. That conversion > could, in a pathological case, have a side-effect (say, if the class of > 'item' had an overridden '__str__' method with side effects), and the > compiler can't know this isn't a pathological case. Fair enough... but I'm reminded of a rant by Joel Spolsky about GUI design: '...programmers have tended to think that if users are allowed to resize and move windows, they should have complete flexibility over where these windows go, right down to the last pixel. After all, positioning a window 2 pixels from the top of the screen is "equally likely" as positioning a window exactly at the top of the screen.' http://www.joelonsoftware.com/uibook/fog0000000249.html (three quarters of the way down, in Chapter 7.) Maybe I'm being unfair, but it seems to me that the attitude is similar: 'there's no point optimizing the common case of printing (say) ints stored in a list, Just In Case the programmer wants the incredibly rare case of setting sys.stdout to some wacky object that modifies the list he's iterating over. It could happen.' *shrug* But apart from the occasional smart-alec who does it just to demonstrate that it is possible, it probably never has. It seems to me that the "consenting adults" philosophy of Python doesn't extend to the compiler, and perhaps it should. Maybe Python could optimize common cases, and if developers wanted to do wacky things, let them turn optimization off on a module-by-module basis. Or even function-by-function. Wouldn't it be nice to have decorators that could optimize the functions they decorated? >> for item in alist[1:5]: >> alist.append(item) # side-effects DON'T matter > > The compiler doesn't know that, at the time of invocation, > 'alist.append' doesn't have side effects that matter. It might if it knows what type alist is, and how long it is (as Marc Rintsch points out). That's why I used "alist" in my example rather than "an_arbitrary_sequence". > The compiler for a dynamic language like Python has very little absolute > "no significant side-effect in these specific cases" guarantee of the > kind you're assuming even in the cases you choose for contrast with the > ones that *do* have significant side-effects. Yes, in general one might not be able to make those guarantees, but still there are common cases where you can. That's how Psycho works. The point is rather moot, since CPython (and probably other Pythons) do almost no optimizations. But just because Python is a dynamic language doesn't mean there are no optimizations possible: Haskell is a dynamic language, and there are optimizing compilers for it. Of course, it is much simpler for Haskell, because of the type system it uses. The CPython compiler already does a couple of source-code optimizations (ignores some unused strings; some constant folding) and at least one runtime optimization (string concatenation is no longer _always_ slow): http://utcc.utoronto.ca/~cks/space/blog/python/ExaminingStringConcatOpt Because of its very nature, optimizing Python is hard. Even something as simple as tail-call recursion optimization is verboten, because Guido considers good stack traces more important than preventing stack overflows in the first place: http://www.tratt.net/laurie/tech_articles/articles/tail_call_optimization Anyway, I'm not really complaining. I like Python, I'm grateful for the work the Python-dev people have already done, and I'm in no position to volunteer to write an optimizing compiler. And it may be that, regardless of how smart you make the compiler, Python simply can't be optimized because of design decisions made back in 1990-whatever when Guido first started his grand plan. -- Steven. From jergosh at wp.pl Sat Sep 1 06:54:00 2007 From: jergosh at wp.pl (=?UTF-8?B?R3J6ZWdvcnogU8WCb2Rrb3dpY3o=?=) Date: Sat, 01 Sep 2007 12:54:00 +0200 Subject: So what exactly is a complex number? In-Reply-To: <451mq4-les.ln1@ozzie.tundraware.com> References: <451mq4-les.ln1@ozzie.tundraware.com> Message-ID: <46D944C8.6090802@wp.pl> > Here is a simple explanation (and it is not complete by a long shot). > > A number by itself is called a "scalar". For example, when I say, > "I have 23 apples", the "23" is a scalar that just represents an > amount in this case. > > One of the most common uses for Complex Numbers is in what are > called "vectors". In a vector, you have both an amount and > a *direction*. For example, I can say, "I threw 23 apples in the air > at a 45 degree angle". Complex Numbers let us encode both > the magnitude (23) and the direction (45 degrees) as a "number". > > There are actually two ways to represent Complex Numbers. > One is called the "rectangular" form, the other the "polar" > form, but both do the same thing - they encode a vector. > > Complex Numbers show up all over the place in engineering and > science problems. Languages like Python that have Complex Numbers > as a first class data type allow you do to *arithmetic* on them > (add, subtract, etc.). This makes Python very useful when solving > problems for engineering, science, navigation, and so forth. > > > HTH, > You're mixing definition with application. You didn't say a word about what complex numbers are, not a word about the imaginary unit, where does it come from, why is it 'imaginary' etc. Since we're being arses here I'd hazard a guess you were educated in the USA where doing without understanding has been mastered by teachers and students alike. You're explanation of what vectors are is equally bogus but this has already been pointed out. I'd also like to see a three-dimensional vector represented by a complex number. Besides, I find Wikipedia extremely unhelpful for learning maths, partly beacuse of it's non-linear nature (while reading an article you come across a term you don't know, follow a link, then follow three others and over the next 4 hours you find out lots of interesting things which are sadly at best tangential to the initial subject) and because it's written by people who already know a lot about the subject and take many things for granted. This seems to be a decent introduction: http://www.ping.be/~ping1339/complget.htm Regards, Greg From hrishys at yahoo.co.uk Wed Sep 26 02:35:25 2007 From: hrishys at yahoo.co.uk (hrishy) Date: Wed, 26 Sep 2007 07:35:25 +0100 (BST) Subject: Hello Gabriel cant help noticing you In-Reply-To: Message-ID: <41607.51503.qm@web27811.mail.ukl.yahoo.com> Hi Gabriel I couldnt help but to write this mail. I am not a python programmer just a shell script coder and i am planning to learn some decent python and raise my level from a shell script junkie to a Python gentleman the way you explain things and show it in code is simply amazing. I particularly liked the way you explained that Regular expression stuff to parse that XML i am just awestruck. NO BOOK/ARTICLE EVER OUT THERE IN MY MIND HAS DONE IT SO CLEANLY AS YOU DID IT. regards Hrishy ___________________________________________________________ Yahoo! Answers - Got a question? Someone out there knows the answer. Try it now. http://uk.answers.yahoo.com/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 14 03:17:48 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 14 Sep 2007 09:17:48 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <5ktre7F5ig0vU1@mid.individual.net> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <5ksoaoF5am8cU1@mid.individual.net> <1189701793.466307.93210@g4g2000hsf.googlegroups.com> <5ktfjqF5ctrvU2@mid.individual.net> <46e98fd8$0$27757$426a34cc@news.free.fr> <5ktre7F5ig0vU1@mid.individual.net> Message-ID: <46ea3591$0$21741$426a34cc@news.free.fr> Bjoern Schliessmann a ?crit : > Bruno Desthuilliers wrote: >> Bjoern Schliessmann a ?crit : > >>> Why don't you make a preprocessor which accepts method >>> declarations without "self" and fixes them? >> The problem being that there's no such thing as a "method >> declaration" in Python > > Yep, there are only definitions. I'm sorry. > >> - only functions being attributes of a class... > > What, IYHO, is the difference between a method and a function? A method is a thin wrapper around a function, usually instanciated and returned by the __get__ method [1] of the function itself when the function is looked up as an attribute of a class or an instance: >>> class Foo(object): ... def meth(self): ... print "in %s meth" % self ... >>> Foo.__dict__['meth'] >>> Foo.meth >>> Foo().meth > >>> [1] you may want to read about the descriptor protocol which is the base mechanism on which methods and properties (computed attributes) are based. >> (ok, I know, you meant "functions declared within a class >> statement"). > > I think that those functions _are_ special ones They aren't, and you should perhaps read the manual - all this is documented. > since the compiler > is able to make "method(instance, a, b)" out of > "instance.method(a, b)". Once again, the compiler has *nothing* to do with this. Else, how could you do this: >>> def fun(obj): ... print obj ... >>> Foo.fun = fun >>> Foo.fun >>> Foo().fun > >>> fun >>> Foo.__dict__['fun'] >>> > So IMHO, "method definition" makes sense. It doesn't. From __peter__ at web.de Sat Sep 8 04:07:14 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 8 Sep 2007 10:07:14 +0200 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <13e2jdobu2kqkf1@corp.supernews.com> Message-ID: Am Fri, 07 Sep 2007 13:10:16 +0000 schrieb Grant Edwards: > On 2007-09-07, Peter Otten <__peter__ at web.de> wrote: >> Am Fri, 07 Sep 2007 10:40:47 +0000 schrieb Steven D'Aprano: >> >>> Python doesn't have any pointers. >> >> Thinking of python variables or "names" as pointers should >> get you a long way when trying to understand python's behaviour. > > But thinking of them as names bound to objects will get you > further (and get you there faster). ;) Understanding a new system in terms of one I already know works for me. When terminology and the system it describes make a perfect fit that is a strong indication that you have reached a dead end. Peter From steve at REMOVE-THIS-cybersource.com.au Sat Sep 15 01:50:44 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 15 Sep 2007 05:50:44 -0000 Subject: How to avoid overflow errors References: <13em8vnr527rq20@corp.supernews.com> Message-ID: <13emslk6n80mmf6@corp.supernews.com> On Fri, 14 Sep 2007 18:19:45 -0700, James Stroud wrote: >> How do I subclass int and/or long so that my class also auto-converts >> only when needed? >> >> >> >> > Use __new__. The disadvantage of that is that your example code requires me to duplicate my methods in the long version and the int version. It's easy enough to work around that (class factory function) but it just seems all rather untidy... -- Steven. From gherzig at fmed.uba.ar Thu Sep 6 17:53:56 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 06 Sep 2007 18:53:56 -0300 Subject: parsing long `To' and 'Cc' from email In-Reply-To: References: <46E06244.80308@fmed.uba.ar> Message-ID: <46E076F4.20704@fmed.uba.ar> Steve Holden wrote: >Gerardo Herzig wrote: > > >>Hi all. Im trying to develop yet another email filter. Just for fun for >>now. Im having a little trouble parsing long 'To' and 'Cc' headers. >>Sometimes p.e. the 'To' header comes like >> >>'account1 at site.com, account at site2.com' >>others comes like >>'"My self" , "My brother" ', >>other times a \r\t comes inside the `To' header. And any combination of >>the above mentioned (and shurely more) can ocur. >> >>the email.* package dont seems to parse that kind of headers >>`correctly'. What i want is to get a list with all the email address in >>the `To' header. >> >>Someone know if there is a more sofisticated parser for doing this? >> >> >> >Have you tried using email.utils.getaddresses()? > >regards > Steve > > No, i was not. And it works just perfect! One day i will make a hard question!! I wonder why this getaddresess() function is not a method into the HeaderParser class. Ok, so my content-filter can continue now. Thanks Steve! Gerardo From arnodel at googlemail.com Mon Sep 17 14:01:48 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 17 Sep 2007 18:01:48 -0000 Subject: how to join array of integers? In-Reply-To: <87hcltnv2z.fsf@rudin.co.uk> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <13eos6ihf2mjg4a@corp.supernews.com> <87lkb6o4bx.fsf@rudin.co.uk> <13erbtbos7ld123@corp.supernews.com> <87hcltnv2z.fsf@rudin.co.uk> Message-ID: <1190052108.347104.266250@y42g2000hsy.googlegroups.com> On Sep 17, 4:57 pm, Paul Rudin wrote: [...] > Although it's not clear to me why the join method needs a sequence > rather than just an iterator. Pure guess (I haven't looked at the code): the join method needs to know the length of the string it builds in order to allocate the correct amount of memory, therefore needs to traverse the iterable object it is joining *twice* (find the length, allocate, fill in)? -- Arnaud From m.n.summerfield at googlemail.com Tue Sep 25 07:51:01 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Tue, 25 Sep 2007 11:51:01 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190719164.587009.206340@19g2000hsx.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> Message-ID: <1190721061.573653.304110@r29g2000hsg.googlegroups.com> On 25 Sep, 12:19, Paul Hankin wrote: > Recall sorted... > sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted > list > > So why not construct sorteddicts using the same idea of sortedness? > > sorteddict((mapping | sequence | nothing), cmp=None, key=None, > reverse=None) > > Then we can specify the exact behaviour of sorteddicts: it's the same > as a regular dict, except when the order of keys is important they're > ordered as if they were sorted by sorted(keys, cmp=sd._cmp, > key=sd._key, reverse=sd._reverse). Here I imagine cmp, key and reverse > are stored in the new sorteddict as attributes _cmp, _key, _reverse - > obviously the actual implementation may differ. > > This has the benefit of making sorteddict's behaviour explicit and > easy to understand, and doesn't introduce a new sorting API when we > already have a perfectly decent one. > > The only problem here is the **kwargs form of the dict constructor > doesn't translate as we're using keyword args to pass in the sort > criterion. Perhaps someone has an idea of how this can be solved. If > nothing else, this constructor could be dropped for sorteddicts, and > sorteddict(dict(**kwargs), cmp=..., key=..., reverse=...) when that > behaviour is wanted. > > I don't like the integral indexing idea or the slicing: indexing and > slicing are already part of python and it's bad to have different > syntax for the same concept on sorteddicts. I'd say it's not an > important enough for sorteddicts anyway. > > -- > Paul Hankin This makes a lot of sense to me. But how do you envisage it would be implemented? From bdesth.quelquechose at free.quelquepart.fr Sat Sep 8 14:32:15 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 08 Sep 2007 20:32:15 +0200 Subject: Enum class with ToString functionality In-Reply-To: <1189458697.707725.244980@g4g2000hsf.googlegroups.com> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <1189425154.788466.132370@d55g2000hsg.googlegroups.com> <46e59bf7$0$21897$426a74cc@news.free.fr> <1189458697.707725.244980@g4g2000hsf.googlegroups.com> Message-ID: <46e5b7ad$0$27788$426a74cc@news.free.fr> TheFlyingDutchman a ?crit : > On Sep 8, 9:52 am, Bruno Desthuilliers > wrote: > >>TheFlyingDutchman a ?crit : (snip) >>>class TestOutcomes: >>> PASSED = 0 >>> FAILED = 1 >>> ABORTED = 2 >> >>> def ToString(outcome): >>> if outcome == TestOutcomes.PASSED: >>> return "Passed" >>> elif outcome == TestOutcomes.FAILED : >>> return "Failed" >>> else: >>> return "Aborted" >> >>> ToString = staticmethod(ToString) >> (snip) >>Technically correct, but totally unpythonic. > > > Speaking of unpythonic, I would call > > ToString = staticmethod(ToString) > > A Perlific syntax. Nope, just a good ole HOF. But nowadays, it's usually written this way: @staticmethod def some_static_method(): pass > >>May I suggest some reading ?http://dirtsimple.org/2004/12/python-is-not-java.html > > Well the Foo.Foo complaint is bogus: > > from Foo import Foo > Yes. And properties are bogus - just use getters and setters. Seriously, writing Java in Python is definitively on the masochist side. But if you like pain... From paddy3118 at googlemail.com Sun Sep 23 00:48:59 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 23 Sep 2007 04:48:59 -0000 Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <46f57841$1$15333$4c368faf@roadrunner.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> <1190472612.942736.325850@w3g2000hsg.googlegroups.com> <46f57841$1$15333$4c368faf@roadrunner.com> Message-ID: <1190522939.547177.294380@22g2000hsm.googlegroups.com> On Sep 22, 8:29 pm, Carl Banks wrote: > On Sat, 22 Sep 2007 14:50:12 +0000, Paddy wrote: > > Sorry Carl, > > I think *you* may not have much need for bitwise operators but others, > > including myself do. No matter what the usage found, I would think > > replacing bitwise operators by function calls a retrograde step. > > Well, if people are going to take the suggestion this personally, maybe > that's reason enough not to bother. > > Carl Banks Carl, don't snipe. You asked and received many answers from personal viewpoints. Tally and move on. - Paddy. From bj_666 at gmx.net Mon Sep 10 04:19:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2007 08:19:36 GMT Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> <13e99756io95p66@corp.supernews.com> <13e9taoa44icgb4@corp.supernews.com> Message-ID: <5kkd0oF3vfqqU4@mid.uni-berlin.de> On Mon, 10 Sep 2007 17:42:16 +1000, bambam wrote: > "Lawrence D'Oliveiro" wrote in > message news:fc2c86$i1l$4 at lust.ihug.co.nz... >> In message <13e99756io95p66 at corp.supernews.com>, bambam wrote: >> >>> Thank you, >> >> Don't top-post. > > I have a number of news readers here, but all of them work > better with top-posting, and in none of them is top posting > a problem. This is not about *you* having any problems but all the people who must read your top postings. Most of them, at least in this news group, expect that a text read from top to bottom follows time from earliest to latest. And as most here don't top post, a conversation with a top poster starts to get mixed and even harder to follow. Ciao, Marc 'BlackJack' Rintsch From wizzardx at gmail.com Sat Sep 8 14:21:29 2007 From: wizzardx at gmail.com (David) Date: Sat, 8 Sep 2007 20:21:29 +0200 Subject: How to insert in a string @ a index In-Reply-To: <1189274564.462664.131240@22g2000hsm.googlegroups.com> References: <1189274564.462664.131240@22g2000hsm.googlegroups.com> Message-ID: <18c1e6480709081121h21eac6d2s9d1e06a91ee8d6af@mail.gmail.com> > The python doesn't supports t1[keyword_index]="XYZhello" (string > object assignment is not supported). How do I get to this problem? Any > sugguestions? Build a new string var using slicing. eg: t1 = t1[:keyword_index] + "XYZhello" + [keyword_index] Or use string formatting: t1 = "your text bla bla %s bla bla bla %s bla bla" % (string1, string2) From laurent.pointal at limsi.fr Mon Sep 17 04:47:48 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 17 Sep 2007 10:47:48 +0200 Subject: SVG to raster conversion. In-Reply-To: References: Message-ID: J. Cliff Dyer a ?crit : > Does anybody know a good solution (preferably in python) for rasterizing > SVG or other vector graphics. > > I'm thinking something like > > vector_image = SVGFile(path_to_image) > raster_image = vector_image.rasterize(format, (width, height), dpi) > raster_image.write(out_file) > > Thanks for any pointers you might have. Another link to complement other replies: Maybe witgh Cairo: Library: http://cairographics.org/ SVG support: http://cairographics.org/manual/cairo-SVG-Surfaces.html Python binding: http://cairographics.org/bindings/ A+ Laurent. From kenneth.m.mcdonald at sbcglobal.net Wed Sep 5 15:02:06 2007 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 05 Sep 2007 14:02:06 -0500 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? Message-ID: <46DEFD2E.5050205@sbcglobal.net> The reading I've done so far on Python 3 (alpha announcement, meta-PEP, some other PEPs) is generally encouraging, but there doesn't seem to be much on cleaning up the syntax, which has become uglier over time as features have been added on to an original syntax that wasn't designed to support them. It seems to me (from what little I've read--I admit that it's impossible to know for sure without experimenting quite a bit, for which I don't currently have the time) that new features such as multimethods might just make things more confusing (especially for newbies) in a lot of ways, without appropriate syntactic support. Currently the most obvious example of this is Python 2.5's way of defining properties, which is ugly. leads often to writing of unnecessary code, and certainly doesn't make property code clear to a reader. Contrast this to the way properties (things that look like an instance variable but are actually bound to methods) are handled in Ruby and (IIRC, this also does a decent job) C#. On the other hand, it does seem that some new syntactic support for other features will be added, so perhaps I'm just missing whichever PEPs talk about going back and adding cleaner syntax for existing features...? Finally, another thing I've perhaps missed, but I can't see anything in what I've gone through, about correcting of of what I see to be one of Python's most long-standing really serious flaws, which is the lack of an official standard documentation markup syntax for writing documentation in code. This isn't even a matter of getting something developed, it's simply a matter of Guido and the Powers That Be bestowing their benediction on one of the several adequate or better documentation toolsets out there, so that more of us (slowly) start using it. Eventually this will result in work on the toolset itself, more people will be willing to use it, and there'll be a nice virtuous circle. Given how much more capable D'Oxygen is than any of the Python-specific solutions, I'd vote for D'Oxygen myself, but I'd prefer to have almost anything fill in this vacuum, rather than continue things the way they are. As I say, I don't get the time I'd like to put into reading up on Py3, so please feel free to correct, point out references, etc. etc. Thanks, Ken From tenax.raccoon at gmail.com Mon Sep 10 09:47:46 2007 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 10 Sep 2007 06:47:46 -0700 Subject: Python syntax wart In-Reply-To: References: Message-ID: <1189432066.374071.189370@57g2000hsv.googlegroups.com> On Sep 8, 11:16 pm, Lawrence D'Oliveiro wrote: > The one thing I don't like about Python syntax is using backslashes to > continue lines. Yes, you can avoid them if you can include parentheses > somehow, but this isn't always possible. > > Possible: > > if ( > quitting > and > len(client["to_write"]) == 0 > and > len(client["read"]) + client["to_read"] == 0 > ) : > close_client(client, "shutting down") > #end if > > Not possible: > > for \ > Link \ > in \ > GetEachRecord \ > ( > "links", > ("from_episode",), > "to_episode = %s", > [EpisodeID], > "order by when_created" > ) \ > : > out.write \ > ( > "

Back to episode %d\n" > % > ( > LinkToMe({"ep" : Link["from_episode"]}), > Link["from_episode"] > ) > ) > #end for Python doesn't prevent you from writing ugly code, using poor variable names, or doing other silly things. The rules on indention require that you are at least consistent on a given line. That said, the backslash simply continues the line, and I don't see why your (ugly, IMO) code is impossible. Here's some similarly schizophrenically formatted code that I just tried: >>> for \ ... l\ ... in \ ... (\ ... 1, ... 2, ... 3 ... )\ ... : ... print\ ... "This is "\ ... "poorly "\ ... "formatted!",\ ... l ... This is poorly formatted! 1 This is poorly formatted! 2 This is poorly formatted! 3 >>> Looks like it runs to me. In general, I'd recommend that you avoid such nonsense spacing and alignment, and use wrappers, generators, and other Python constructs to help write more sensible code. --Jason From daniel.j.larsson at gmail.com Tue Sep 4 20:15:21 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Wed, 5 Sep 2007 02:15:21 +0200 Subject: doctest and decorators In-Reply-To: References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> <200709042316.08263.python@cx.hu> <2bfa72fa0709041452o72d9a98fp939852d061a2cda3@mail.gmail.com> <200709050009.46380.python@cx.hu> <2bfa72fa0709041529g9d5ac22hce3a55d5357b1a1c@mail.gmail.com> Message-ID: <2bfa72fa0709041715g72006d99x731f4e35f1dd8fc3@mail.gmail.com> On 9/5/07, Gabriel Genellina wrote: > > En Tue, 04 Sep 2007 19:29:11 -0300, Daniel Larsson > escribi?: > > > On 9/5/07, Ferenczi Viktor wrote: > >> > >> > > @functools.wraps(f) > >> > > Pass the function to be wrapped by the decorator to the wraps > >> function. > >> > Ooops, right. That doesn't change the fact that decorated functions > >> get > >> > hidden from doctest though. > > > > > > I have no issue when the decorator is defined in the same module as the > > decorated function, my problem is running doctests on functions using an > > imported decorator. Having to implement the decorator in every source > > module > > isn't very practical. Try splitting your module in two, as I did, and > run > > with -v, and you'll see the problem. > > Looks like a bug. doctest is failing to recognize that the decorated > function belongs to the module being tested. > > A simple patch: In doctest.py, method _from_module, near line 840, you > have these lines: > > elif inspect.getmodule(object) is not None: > return module is inspect.getmodule(object) > > Move them up, just before the line: > > elif inspect.isfunction(object): Yes, that was basically what I did as well. It makes much more sense to check __module__ first (which is modifiable) rather than func_globals (which obviously isn't). I would have guessed the inspect.getmodule check would cover the isclass test as well (?) This works fine in this case, but I'm not sure whether this breaks in > other circumstances (but I can't think of a case when using > inspect.getmodule() would not be appropiate). > > PS: I can't see any tests for decorated functions (except > @classmethod/@staticmethod) in the library test suite. I'll try to add > some and submit a patch. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ricaraoz at gmail.com Sat Sep 1 08:45:32 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Sep 2007 09:45:32 -0300 Subject: list index() (OT) In-Reply-To: <1188631457.050512.103060@y42g2000hsy.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1cnfd31du01el95u70o8mjn9cb5r5aluiu@4ax.com> <1188631457.050512.103060@y42g2000hsy.googlegroups.com> Message-ID: <46D95EEC.2000603@bigfoot.com> Paddy wrote: > On Sep 1, 7:57 am, "Hendrik van Rooyen" wrote: >> "Richie Hindle" wrote: >>> But - the word for someone who posts to the internet with the intention of >>> stirring up trouble derives from the word for what fishermen do, not from >>> the word for something that lives under a bridge. It derives from "trolling >>> for suckers" or "trolling for newbies". >> So am I right in asserting that there is a difference in pronunciation >> of the noun and the verb? >> >> He is a Troll - like the excellent frolic example >> He likes to Troll - rhymes with roll? >> >> - Hendrik > > No difference. A troll is a troll is a troll. > > :-) > > - Paddy. BTW people , the word for what fishermen do is T R A W L and not troll (Ha! and I'm not a native English speaker). From bj_666 at gmx.net Tue Sep 11 11:29:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Sep 2007 15:29:26 GMT Subject: memcpy References: <1189449530.171049.323230@22g2000hsm.googlegroups.com> <5klnsbF3vfqqU10@mid.uni-berlin.de> <1189512598.410810.224340@y42g2000hsy.googlegroups.com> <5knhtpF4b65dU6@mid.uni-berlin.de> <1189516939.394375.248830@d55g2000hsg.googlegroups.com> Message-ID: <5knqimF4b65dU7@mid.uni-berlin.de> On Tue, 11 Sep 2007 06:22:19 -0700, Tim wrote: > Is this what you mean? Python did not like the word c_types in front > of POINTER. Do you know why? Yes I know. Read up how importing works. > How can I re-declare a function's return type if it is declared > somewhere else? The return type of C functions wrapped by `ctypes` is always `int` until you say otherwise. How to do that is covered in the `ctypes` tutorial/dicumentation. > test_data = numpy.ones(1000) > shared_memory_pointer = POINTER(c_float*256) This binds the resulting "pointer" object to the name `shared_memory_pointer`. > shared_memory_pointer = > windll.kernel32.MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, > 0, 0, TABLE_SHMEMSIZE) And here you bind a different object to that name, so the first binding has no effect. Ciao, Marc 'BlackJack' Rintsch From horpner at yahoo.com Tue Sep 11 07:15:19 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 11 Sep 2007 11:15:19 GMT Subject: Checking if elements are empty References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> <46e2013a$0$7687$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On 2007-09-10, Steve Holden wrote: >> I have a quibble not with the functionality of the boolean check, >> but with its expressiveness. if y[0] == "" expresses more, i.e., >> that I expect y[0] to contain a Python byte string. > > I have a quibble with a test that will raise an exception when > the anticipated condition is true. Your test is patently > absurd, as you would have discovered had you bothered to try > it: "if y[0] == "" expresses more, i.e., that I expect y[0] to contain a Python byte string." -- Neil Cerutti Bach's death is attributed to the end of the Baroque era. --Music Lit Essay From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Sep 12 07:40:32 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 12 Sep 2007 13:40:32 +0200 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> Message-ID: <5kq1hgF4r90oU1@mid.individual.net> Ivan Voras wrote: > What does "self" have to do with an object model? It's an > function/method argument that might as well be hidden in the > compiler without ever touching the role it has (if not, why?). I > agree that it's needless noise in a language. If this was needless, why do C++ and Java have the "this" pointer? Regards, Bj?rn -- BOFH excuse #390: Increased sunspot activity. From hniksic at xemacs.org Fri Sep 21 09:37:33 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 21 Sep 2007 15:37:33 +0200 Subject: __contains__() : Bug or Feature ??? References: <1190380085.770828.19400@o80g2000hse.googlegroups.com> Message-ID: <873ax8dtr6.fsf@mulj.homelinux.net> "sebastien.lannez at gmail.com" writes: > I need to overload the operator in and let him return an object > ... It seems it is not a behavior Python expect : Python expects it all right, but it intentionally converts the value to a boolean. The 'in' operator calls PySequence_Contains, which returns a boolean value at the C level. User-supplied __contains__ is implemented as an adaptor in typeobject.c (slot_sq_contains). It takes the value returned by your __contains__ implementation and converts it to 0 or 1. I don't think you can overload 'in' as you want without pervasive changes to CPython source code. From george.sakkis at gmail.com Thu Sep 27 15:54:40 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 27 Sep 2007 19:54:40 -0000 Subject: ValueError: too many values to unpack In-Reply-To: References: Message-ID: <1190922880.243988.149280@g4g2000hsf.googlegroups.com> On Sep 27, 12:46 pm, Shawn Minisall wrote: > I am trying to read a few lines of a file with multiple values, the rest > are single and are reading in fine. > > With the multiple value lines, python says this "ValueError: too many > values to unpack" > > I've googled it and it says that happens when you have too few or too > many strings that don't match with the variables in number your trying > to assign them too. Below are the lines in reading in: > > line 3 - 19.18 29.15 78.75 212.10 > line 4 - 100 20 410.29 > And this is the code I'm using: > > #read withdrawls from file on line3 > line = infile.readline() > #split withdrawls up > withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") > > #read deposits from file on line4 > line = infile.readline() > #split deposits up > deposit1, deposit2, deposit3 = string.split(line, "\t") > > I have 4 strings to match line 3 and 3 to match the 3 on line 4...any > thoughts? > > thx Just print out the split without unpacking to see how many elements there are actually present: print string.split(line, "\t") By the way, most functions of the string module are deprecated in favor of string methods; the above is better written as print line.split("\t") HTH, George From vijayeee at gmail.com Tue Sep 4 01:12:00 2007 From: vijayeee at gmail.com (vijayca) Date: Tue, 04 Sep 2007 05:12:00 -0000 Subject: Tkinter Message-ID: <1188882720.020666.67490@k79g2000hse.googlegroups.com> i tried to use python gui module Tkinter in solaris,aix,hpux..... while importing the module it shows an error... import Tkinter error says that your python may not be configured for Tk()... how to get out of this... From raychorn at hotmail.com Fri Sep 21 19:25:20 2007 From: raychorn at hotmail.com (Python Maniac) Date: Fri, 21 Sep 2007 16:25:20 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> <1190394011.148384.106280@q3g2000prf.googlegroups.com> Message-ID: <1190417120.723579.267560@22g2000hsm.googlegroups.com> On Sep 21, 3:02 pm, "Matt McCredie" wrote: > > Now I think I will code this little scrambler using nothing but the D > > Language just to see whether there is any benefit in using D over > > Python for this sort of problem. > > Isn't D compiled to machine code? I would expect it to win hands down. > That is, unless it is horribly unoptimized. > > Matt Well D code is compiled into machine code that runs via a VM. My initial D code ran in about 6 secs as compare with the 2.278 secs for the optimized Python code. If I want the D code to run faster than the optimized Python I would have to use the same Pythonic optimizations as were used in Python when crafting the D code and then I would guess the optimized D code might run only 2x faster than the optimized Python code. In real terms < 3 secs to process a 20 MB file is more than reasonable performance with no need to perform any additional optimizations. For this particular problem Python performs as well as the D powered machine code using far less effort, for me, than what it would take to make the D code run faster than the Python code. All this tells me the following: * List Comprehensions are very powerful for Python. * String translation is a must when processing string based data in an iterative manner. * Ruby has no hope of being able to beat Python for this type of problem given the proper Python optimizations are used. * There is no value in wasting time with lower-level languages to make Python run faster for this type of problem. It would be nice if Python could be made to automatically detect the LC and string translation patterns used by the unoptimized Python code and make them into optimized Python code on the fly at runtime. I am more than a little amazed nobody has chosen to build a JIT (Just In- Time compiler) or cached-compiler into Python but maybe that sort of thing is just not needed given the fact that Python code can be easily optimized to run 30x faster. From ldo at geek-central.gen.new_zealand Sat Sep 1 02:55:52 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 18:55:52 +1200 Subject: simple spider in python References: <1187876014.845912.236690@e9g2000prf.googlegroups.com> Message-ID: In message , Michael Bentley wrote: > First thing to know is that google doesn't like the User-agent header > urllib2 uses by default -- you'll have to masquerade as a browser > (google throws a 403 error if you connect as 'User-Agent: Python- > urllib/2.5': look into urllib2.build_opener()). A bit small-minded of Google, don't you think. They also block the default user-agent header for wget. From grante at visi.com Wed Sep 26 19:15:17 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 26 Sep 2007 23:15:17 -0000 Subject: ~ bit-wise unary operator References: Message-ID: <13flq05hoiq5he4@corp.supernews.com> On 2007-09-26, Ladislav Andel wrote: > Hello, > why ~ bit-wise unary operator returns -(x+1) and not bit inversion of > the given integer? > > example: > a = 7978 > a = ~a > python returns -7979 > > but I need to get back 57557 as in C language. It's not what C language returns, but if you want 57557, you can get it like this: >>> (~7978) & 0xffff 57557 -- Grant Edwards grante Yow! Do you think the at "Monkees" should get gas on visi.com odd or even days? From gagsl-py2 at yahoo.com.ar Fri Sep 28 04:04:21 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Sep 2007 05:04:21 -0300 Subject: marshal bug? References: <1190961020.258850.215130@g4g2000hsf.googlegroups.com> <1190964399.196877.299630@19g2000hsx.googlegroups.com> Message-ID: En Fri, 28 Sep 2007 04:26:39 -0300, Anurag escribi?: > Now is there a easy way to by pass it (hack around it) > I tried various options but all fail e.g. > i= 123; marshal.dumps("%d"%123) != marshal.dumps("%d"%i) You can't. Don't use marshal to compare objects. You appear to assume that two objects that compare equal, should have the same marshalled representation, and that is simply not true. py> [1, 2.0, 3+0j, "4"] == [1.0, 2+0j, 3, u"4"] True > So maybe I have to change all my code to use pickle, which also > consumes for memory per string. Neither marshal nor pickle guarantee that equal objects have equal representations, so in this regard pickle won't help either. Maybe if you explain what you really want to do someone could suggest a solution. -- Gabriel Genellina From rustompmody at gmail.com Sat Sep 15 07:02:48 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 15 Sep 2007 16:32:48 +0530 Subject: trim start and trailing space chars from string In-Reply-To: <46EBA4B1.1030302@yahoo.gr> References: <46EBA4B1.1030302@yahoo.gr> Message-ID: >>> s=" abcdef " >>> s.strip() 'abcdef' >>> s.rstrip() ' abcdef' >>> s.lstrip() 'abcdef ' >>> On 9/15/07, Konstantinos Pachopoulos wrote: > Hi, > is there something corresponding to the java String.trim() method, ie > trim start and trailing space/tab chars from string? > say convert " asdf " to "asdf"? > > Thnx > -- > http://mail.python.org/mailman/listinfo/python-list > From kyosohma at gmail.com Tue Sep 4 16:35:38 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 04 Sep 2007 20:35:38 -0000 Subject: function call In-Reply-To: <1188937059.459609.61850@57g2000hsv.googlegroups.com> References: <1188937059.459609.61850@57g2000hsv.googlegroups.com> Message-ID: <1188938138.583012.22570@22g2000hsm.googlegroups.com> On Sep 4, 3:17 pm, ianar? wrote: > Hey all, > > Is there a way of printing out how a function was called? In other > words if I do the following: > > def someFunction(self): > self.someOtherFunction(var1, var2) > > I would get something like "someOtherFunction: called by: > someFunction, args are: var1, var2" > > Thanks in advance > > - ianar? I think you can use __name__, but I'm not sure how to apply it here. Read up on Python's introspection tools: http://www.ibm.com/developerworks/library/l-pyint.html Mike From jeff at jmcneil.net Thu Sep 27 15:55:52 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 27 Sep 2007 15:55:52 -0400 Subject: How to Catch Errors in SimpleXMLRPCServer In-Reply-To: <1190921745.575519.53560@y42g2000hsy.googlegroups.com> References: <1190921745.575519.53560@y42g2000hsy.googlegroups.com> Message-ID: <82d28c40709271255s1039e861xf9abbc80e1b56b09@mail.gmail.com> Instead of register_function, use register_instance and provide a _dispatch method in that instance that handles your exception logging. Pseudo: class MyCalls(object): def _dispatch(self, method, args): try: self.getattr(self, method)(*args) except: handle_logging() server = SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(MyCalls()) server.serve_forever() There might be an easier way... but this works for me. -Jeff On 9/27/07, gregpinero at gmail.com wrote: > I have a pretty simple XMLRPCServer, something along the lines of the > example: > > server = SimpleXMLRPCServer(("localhost", 8000)) > server.register_function(pow) > server.register_function(lambda x,y: x+y, 'add') > server.serve_forever() > > Now what I want to do is catch any errors that happen on requests, and > ideally have them emailed to me. I have the email part all taken care > of, I just need to know how to get at the exceptions. > > Thanks in advance for any help, > > Greg > > -- > http://mail.python.org/mailman/listinfo/python-list > From danb_83 at yahoo.com Mon Sep 17 01:23:07 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 16 Sep 2007 22:23:07 -0700 Subject: A short question about non-ascii characters in list In-Reply-To: References: Message-ID: <1190006587.185218.168340@22g2000hsm.googlegroups.com> On Sep 17, 12:08 am, js wrote: > >>> print u"???" > ??? > >>> print [u"???"] > > [u'\xe4\xf6\xfc'] > > Python seems to treat non-ASCII chars in a list differently from the > one in the outside of a list. > I think this behavior is so inconvenient and actually makes debugging > work harder. > > Is this an intentional? Is there any doc discussing about this? It's intentional. __str__ of a list uses the __repr__ of its elements. This helps reduce confusion (e.g., between ['a', 'b, c'] and ['a, b', 'c']). From lasses_weil at klapptsowieso.net Thu Sep 13 12:51:51 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 13 Sep 2007 18:51:51 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <1189700775.661780.292150@50g2000hsm.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> Message-ID: <46e96aaa$0$7685$9b4e6d93@newsspool2.arcor-online.net> TheFlyingDutchman wrote: > What I would like to have seen added to class definitions was the > forced declaration of all object variables in the class outside of > methods. I don't like the fact that they have to be, and can be > created in any method on the fly. > Isn't one of the main ideas behind python that it doesn't force you to do (well, declare) anything? And by "ideas" I mean "design decisions". Thats exactly what makes python great for prototyping; you just do it and see if it works. As soon as you need to declare things you have to change stuff in at least 2 places for every change of heart you have. (Can you tell I'm currently forced to developing in Java? ;) (Which I'm currently avoiding to do, by wasting my time on usenet.)) /W From dotancohen at gmail.com Sun Sep 9 15:01:11 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 9 Sep 2007 22:01:11 +0300 Subject: Modul (%) in python not like in C? Message-ID: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> FIrst of all, how is the % symbol (as in 70%6=4) called in English? Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or the other in error? Is this a known gotcha? I tried to google the subject however one cannot google the symbol %. Thanks in advance. Dotan Cohen http://what-is-what.com http://gibberish.co.il -- ?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From dnhkng at googlemail.com Wed Sep 5 05:50:38 2007 From: dnhkng at googlemail.com (Dr Mephesto) Date: Wed, 05 Sep 2007 09:50:38 -0000 Subject: creating really big lists Message-ID: <1188985838.661821.41530@k79g2000hse.googlegroups.com> Hi! I would like to create a pretty big list of lists; a list 3,000,000 long, each entry containing 5 empty lists. My application will append data each of the 5 sublists, so they will be of varying lengths (so no arrays!). Does anyone know the most efficient way to do this? I have tried: list = [[[],[],[],[],[]] for _ in xrange(3000000)] but its not soooo fast. Is there a way to do this without looping? David. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 6 06:54:18 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Sep 2007 10:54:18 -0000 Subject: interesting puzzle......try this you will be rewarded... References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> Message-ID: <13dvn2q9qogq484@corp.supernews.com> On Thu, 06 Sep 2007 09:56:16 +0000, Renu wrote: > Hi, > > Just click on this link n use ur common sence to navigate. > > It has 23 pages one after the other, starting from this first > Page. The trick is to find a way to go to the next page. [snip] In case it wasn't obvious, the site is nothing but adware. Banner ads, google ads, text ads, blah blah blah. I stopped at page 1. -- Steven. From bdesth.quelquechose at free.quelquepart.fr Wed Sep 19 15:02:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 21:02:32 +0200 Subject: ONYX In-Reply-To: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> References: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> Message-ID: <46f1726f$0$15276$426a74cc@news.free.fr> korovev76 at gmail.com a ?crit : > Hi everybody! Is there anything out there that can validate and parse > some "onyx-style" xml? I don't know what's "onyx-style" xml, but if it's xml, any xml parser will parse it, and any validating parser should be able to validate it given the correct DTD. From mail2spj at yahoo.com Mon Sep 17 17:00:13 2007 From: mail2spj at yahoo.com (SPJ) Date: Mon, 17 Sep 2007 14:00:13 -0700 (PDT) Subject: Writing to multiple excel worksheets Message-ID: <969892.43175.qm@web50103.mail.re2.yahoo.com> Hi, I have a list which I need to write to excel worksheet. The list is like: data = ['IP1','21','ftp','\n','IP1','22','ssh','\n','IP2','22','ssh','\n','IP2','23','telnet','\n'] Now the task is to create a workbook with tabbed sheet for each of the service's in the list i.e. tabs for ftp, ssh, telnet etc. The data needs to be written in the corresponding sheets. What is the best way to achieve this? I couldn't find much help on the internet nor in the earlier threads. Please help. Thanks, SPJ --------------------------------- Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hall.jeff at gmail.com Sat Sep 29 11:22:27 2007 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Sat, 29 Sep 2007 15:22:27 -0000 Subject: Program inefficiency? Message-ID: <1191079347.192272.240540@22g2000hsm.googlegroups.com> I wrote the following simple program to loop through our help files and fix some errors (in case you can't see the subtle RE search that's happening, we're replacing spaces in bookmarks with _'s) the program works great except for one thing. It's significantly slower through the later files in the search then through the early ones... Before anyone criticizes, I recognize that that middle section could be simplified with a for loop... I just haven't cleaned it up... The problem is that the first 300 files take about 10-15 seconds and the last 300 take about 2 minutes... If we do more than about 1500 files in one run, it just hangs up and never finishes... Is there a solution here that I'm missing? What am I doing that is so inefficient? # File: masseditor.py import re import os import time def massreplace(): editfile = open("pathname\editfile.txt") filestring = editfile.read() filelist = filestring.splitlines() ## errorcheck = re.compile('(a name=)+(.*)(-)+(.*)(>)+') for i in range(len(filelist)): source = open(filelist[i]) starttext = source.read() interimtext = replacecycle(starttext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) interimtext = replacecycle(interimtext) finaltext = replacecycle(interimtext) source.close() source = open(filelist[i],"w") source.write(finaltext) source.close() ## if errorcheck.findall(finaltext)!=[]: ## print errorcheck.findall(finaltext) ## print filelist[i] if i == 100: print "done 100" print time.clock() elif i == 300: print "done 300" print time.clock() elif i == 600: print "done 600" print time.clock() elif i == 1000: print "done 1000" print time.clock() print "done" print i print time.clock() def replacecycle(starttext): p1= re.compile('(href=|HREF=)+(.*)(#)+(.*)( )+(.*)(">)+') p2= re.compile('(name=")+(.*)( )+(.*)(">)+') p3= re.compile('(href=|HREF=)+(.*)(#)+(.*)(\')+(.*)(">)+') p4= re.compile('(name=")+(.*)(\')+(.*)(">)+') p5= re.compile('(href=|HREF=)+(.*)(#)+(.*)(-)+(.*)(">)+') p6= re.compile('(name=")+(.*)(-)+(.*)(">)+') p7= re.compile('(href=|HREF=)+(.*)(#)+(.*)(<)+(.*)(">)+') p8= re.compile('(name=")+(.*)(<)+(.*)(">)+') p7= re.compile('(href=|HREF=")+(.*)(#)+(.*)(:)+(.*)(">)+') p8= re.compile('(name=")+(.*)(:)+(.*)(">)+') p9= re.compile('(href=|HREF=")+(.*)(#)+(.*)(\?)+(.*)(">)+') p10= re.compile('(name=")+(.*)(\?)+(.*)(">)+') p100= re.compile('(a name=)+(.*)(-)+(.*)(>)+') q1= r"\1\2\3\4_\6\7" q2= r"\1\2_\4\5" interimtext = p1.sub(q1, starttext) interimtext = p2.sub(q2, interimtext) interimtext = p3.sub(q1, interimtext) interimtext = p4.sub(q2, interimtext) interimtext = p5.sub(q1, interimtext) interimtext = p6.sub(q2, interimtext) interimtext = p7.sub(q1, interimtext) interimtext = p8.sub(q2, interimtext) interimtext = p9.sub(q1, interimtext) interimtext = p10.sub(q2, interimtext) interimtext = p100.sub(q2, interimtext) return interimtext massreplace() From bignose+hates-spam at benfinney.id.au Wed Sep 19 22:55:35 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 20 Sep 2007 12:55:35 +1000 Subject: Mixin classes and single/multiple inheritance (was: super() doesn't get superclass) References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> Message-ID: <877immvye0.fsf_-_@benfinney.id.au> Michele Simionato writes: > I am not against mixins (even if I am certainly very much against > the *abuse* of mixins, such as in Zope 2). What I would advocate > (but I realize that it will never happen in Python) is single > inheritance + mixins a la Ruby. For those unfamiliar with Ruby, could you explain how you see this being done in Python? What do you see as an appropriate use of mixin classes, and what an abuse? What would the semantics be in Python for "single inheritance + mixins a la Ruby"? Can you give example syntax? -- \ "As we enjoy great advantages from the inventions of others, we | `\ should be glad to serve others by any invention of ours." -- | _o__) Benjamin Franklin | Ben Finney From sergio.correia at gmail.com Sat Sep 8 13:53:49 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Sat, 8 Sep 2007 12:53:49 -0500 Subject: Why 'class spam(object)' instead of class spam(Object)' ? In-Reply-To: References: <46e10916$0$16518$4c368faf@roadrunner.com> Message-ID: Thanks for the replies, very instructive! On 9/7/07, Steve Holden wrote: > Carl Banks wrote: > > On Fri, 07 Sep 2007 01:30:00 -0500, Sergio Correia wrote: > >> Hi, I'm kinda new to Python (that means, I'm a total noob here), but > >> have one doubt which is more about consistency that anything else. > >> > >> Why if PEP 8 says that "Almost without exception, class names use the > >> CapWords convention", does the most basic class, object, is lowercase? > > > > It said "almost". :) > > > Indeed it did, and never forget that most of PEP 8 was derived from an > essay by Guido whose original title was "A Foolish Consistency is the > Hobgoblin of Little Minds" ... > > > >> I found a thread about this: > >> http://mail.python.org/pipermail/python-list/2007-April/437365.html > >> where its stated that -object- is actually a type, not a class; but the > >> idea still doesn't convince me. > > > You don't have to be convinced. You just have to do what the PEP says > yourself and ignore the people who *haven't* done what it says > (particularly if they are core Python developers). > > > There's a false dichotomy there: it's not an either-or situation. Almost > > everyone would agree that new-style classes, defined by the Python class > > statement, are both classes and types. Some might squabble over whether > > object is class, but it has nothing to do with why object is spelled in > > lower-case. > > > > The reason why "object" is lower case is because built-in types are > > spelled in lower-case. Why are built-in types lower case? Because many > > built-in types were originially functions. For example, "int" and "str" > > were once functions. When these symbols became the names of their > > respective types, they kept the lower-case spelling, and it became > > convention for built-in types to be spelled lower-case. > > > In other words: "Get over it" ;-) > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- > > -- > http://mail.python.org/mailman/listinfo/python-list > From laurent.pointal at limsi.fr Mon Sep 17 07:33:28 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 17 Sep 2007 13:33:28 +0200 Subject: Python "with" In-Reply-To: References: Message-ID: Ivan Voras a ?crit : > Laurent Pointal wrote: > >> The ugly part is the 'tmp' name, try to choose a name with a proper >> meaning about what it is really, and it become clean and readable: >> >> filerefs = some.big.structure.or.nested.object.with.file.references >> filerefs.encoding = "utf-8" >> filerefs.name = "MyFileName.txt" >> filerefs.use_quotes = True >> >> Isn't it ? > > Well, no, but this might be due to personal tastes. At least, I don't > think it's better then some other alternatives. For example, in C99 you > can do: > > static struct option_s foo_option = { > .name = "foo", > .type = O_STRING, > .def_value = "default" > }; > > At least to me, this looks even better than the Pascal's syntax. If its at construction time, you can do the same with Python: class option_s(object) : def __init__(self,**initializers) : self.__dict__.update(initializers) foo_option = option_s( name = "foo", type_ = O_STRING, def_value = "default" ) And if the class has no such construction idiom, you can play like this: x = X() x.__dict__.update(dict( name = "foo", type_ = O_STRING, def_value = "default" )) Note: this directly manipulate objects attributes - some times its preffered to use ad-hoc methods. Note2: I prefer the "namespace.name = value" solution, more readable. Note3: Its funny to see how Python users tries to change the language, does this occure with C, C++, Java, C# ? From tdelaney at avaya.com Wed Sep 26 05:42:10 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 26 Sep 2007 17:42:10 +0800 Subject: sorting a list numbers stored as strings In-Reply-To: <877imeoo5i.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > "Delaney, Timothy (Tim)" writes: > >> Yep - appears I must have been misremembering from another language >> (dunno which) > > Tcl Not bloody likely - only used Tcl for expect, and then only very minimally. I'm sure there's at least one language though among the 20+ I've forgotten over the years that has significant leading zeroes in its default string->int parsing. Actually, I think Java does ... Tim Delaney From jstroud at mbi.ucla.edu Sat Sep 8 01:00:26 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 07 Sep 2007 22:00:26 -0700 Subject: pdb question - spew out "steps" until crash needed Message-ID: How do I get pdb to just run my program and spew out what's happening until it crashes/freezes? (This is a malloc error in a library somewhere and I can't figure out where--no exceptions thrown, etc.) I think I might need to live a lot longer to simply hit 's' [enter] until I get to the crash. Easiest would be run->spew->read last line. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From grante at visi.com Wed Sep 12 10:28:59 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 12 Sep 2007 14:28:59 -0000 Subject: library to launch program in linux References: <1189103678.484278.321650@r34g2000hsd.googlegroups.com> <13e0itfgm0ida1c@corp.supernews.com> <1189604878.304602.104410@k79g2000hse.googlegroups.com> Message-ID: <13efttb3b3q40a@corp.supernews.com> On 2007-09-12, idzwan.nizam at gmail.com wrote: >>> I'm a new user. What library should I use so that I canlaunch >>> programin linux using python? Thank you in advance. > can you please show me the sample code using subprocess library. http://docs.python.org/lib/module-subprocess.html > I would like user to have few option, program they could run. > say, firefox and x chat. I'd like to be 15 years younger. -- Grant Edwards grante Yow! I'm definitely not at in Omaha! visi.com From hanser at club-internet.fr Sat Sep 1 11:19:49 2007 From: hanser at club-internet.fr (Pierre Hanser) Date: Sat, 01 Sep 2007 17:19:49 +0200 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <46d903db$0$19580$4c368faf@roadrunner.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <7xwsvcc9yz.fsf@ruckus.brouhaha.com> <1i3p8lm.19738kn1q0gkouN%aleax@mac.com> <1188587846.687895.69240@q5g2000prf.googlegroups.com> <38rmq4-cq.ln1@strongwill.g2ctech> <46d903db$0$19580$4c368faf@roadrunner.com> Message-ID: <46D98315.4030602@club-internet.fr> Carl Banks a ?crit : > > This is starting to sound silly, people. Critical is a relative term, > and one project's critical may be anothers mundane. Sure a flaw in your > flagship product is a critical problem *for your company*, but are you > really trying to say that the criticalness of a bad web search is even > comparable to the most important systems on airplanes, nuclear reactors, > dams, and so on? Come on. 20 years ago, there was *no* computer at all in nuclear reactors. From f.guerrieri at gmail.com Wed Sep 5 16:47:20 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Wed, 5 Sep 2007 22:47:20 +0200 Subject: concise code (beginner) In-Reply-To: References: <13dsvqrqivtf092@corp.supernews.com> <1189020188.842700.50950@d55g2000hsg.googlegroups.com> Message-ID: <79b79e730709051347t260ae465v4c455bc66372863f@mail.gmail.com> On 9/5/07, James Stroud wrote: > > > Another way is to make a copy of devs, if devs is short, which makes my > > When I process something of that genre (e.g. files) I prefer not to lose trace of what's happened by removing the "bad items". Instead I prefer to flag or otherwise to store them in some place from where they could get back. Obviously, it depends on the details of the program :) francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From ricaraoz at gmail.com Sun Sep 2 11:19:33 2007 From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=) Date: Sun, 02 Sep 2007 12:19:33 -0300 Subject: localizing a sort In-Reply-To: References: Message-ID: <46DAD485.405@bigfoot.com> Peter Otten wrote: > Am Sat, 01 Sep 2007 18:56:38 -0300 schrieb Ricardo Ar?oz: > >> Hi, I've been working on sorting out some words. >> >> My locale is : >>>>> import locale >>>>> locale.getdefaultlocale() >> ('es_AR', 'cp1252') >> >> I do : >>>>> a = '???????????????' >>>>> print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y))) >> aeiou??????????????? > > The lambda is superfluous. Just write cmp=locale.strcoll instead. No it is not : >>> print ''.join(sorted(a, cmp=locale.strcoll(x,y))) Traceback (most recent call last): File "", line 1, in TypeError: strcoll expected 2 arguments, got 0 You need the lambda to assign both arguments. > >> This is not what I am expecting. I was expecting : >> a???e???i???.....etc. >> >> The reason is that if you want to order some words (say for a dictionary >> (paper dict, where you look up words)) this is what happens : >>>>> a = 'pal?bra de p?labra de pblabra' >>>>> print ' '.join(sorted(a.split(), cmp=lambda x,y: locale.strcoll(x, y))) >> de de pal?bra pblabra p?labra >> >> While any human being would expect : >> >> de de pal?bra p?labra pblabra >> >> Does anybody know a way in which I could get the desired output? > > I suppose it would work on your machine if you set the locale first with > >>>> locale.setlocale(locale.LC_ALL, "") This works. Thanks Peter. From remm1 at member.fsf.org Sat Sep 15 23:05:09 2007 From: remm1 at member.fsf.org (Rob E) Date: Sat, 15 Sep 2007 22:05:09 -0500 Subject: List append References: <1189826727.204061.310380@d55g2000hsg.googlegroups.com> Message-ID: On Sat, 15 Sep 2007 03:25:27 +0000, mouseit wrote: > I'm trying to add an element to a list which is a property of an > object, stored in an array. When I append to one element, all of the > lists are appended! > > Example Code: > > class Test: > array = [] > > myTests = [Test() , Test() , Test()] > print len(myTests[1].array) > myTests[0].array.append( 5 ) > print len(myTests[1].array) > > prints: > 0 > 1 > > This is probably a really easy question (I'm very new to python), so > thanks in advance for your help! Yes, that's easy: class myclass: var1 = [] means that var1 is associated with the class. If you want an attribute: class myclass: def __init__ (self): self.var1 = [] is the correct way. Rob From p at ulmcnett.com Mon Sep 24 13:33:22 2007 From: p at ulmcnett.com (Paul McNett) Date: Mon, 24 Sep 2007 10:33:22 -0700 Subject: Is there some sort of portable IDE? In-Reply-To: References: Message-ID: <46F7F4E2.4070707@ulmcnett.com> Lamonte Harris wrote: > Like say you don't got python installed, but you want to test code is > there a way?(School) Like way, dude, check this out: http://www.portablepython.com/ -- pkm ~ http://paulmcnett.com From trekker182 at gmail.com Fri Sep 21 11:36:06 2007 From: trekker182 at gmail.com (Shawn Minisall) Date: Fri, 21 Sep 2007 11:36:06 -0400 Subject: acronym program In-Reply-To: <87lkb0hxgu.fsf@rudin.co.uk> References: <87lkb0hxgu.fsf@rudin.co.uk> Message-ID: <46F3E4E6.7050207@gmail.com> That was it! Thanks a lot! I was also trying to output the acronym in caps so I was entering string.upper (acronym) like whats in the book and kept getting a "'tuple' object is not callable" error message. Just for the heck of it I tried it acronym.upper() and it worked! I thought it could work both ways? Paul Rudin wrote: > Shawn Minisall writes: > > >> I'm trying to write a program that gets the first letter of every word >> of a phrase and prints it on screen. I'm having problems with it. >> I'm thinking a for loop would be good since I don't know the exact >> number of words the user is going to enter, but after that I get >> confused. How do I tell python to just goto the beg of each word in >> the phrase and include it in the acronym? Am I on the right track? >> >> for a in string.split(phrase) >> acronym = phrase [0] >> acronym = acronym + 1 >> > > > How about: > > for a in phrase.split(): > print a[0] > > > > From kar1107 at gmail.com Wed Sep 19 16:29:22 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Wed, 19 Sep 2007 20:29:22 -0000 Subject: Removing objects in a list via a wild card In-Reply-To: References: <8a6b8e350709191151n31b72bbvc3090031232d5fc8@mail.gmail.com> Message-ID: <1190233762.051021.307250@k35g2000prh.googlegroups.com> On Sep 19, 1:11 pm, David wrote: > On 9/19/07, James Matthews wrote: > > > Hi List > > > I have a list of files from my current directory: > > > import os > > > files = os.listdir(os.getcwd()) > > > Now this list also includes some files that i don't want like my python > > files... How would i remove them > > You can use regular expressions: > > import re > files=[file for file in os.listdir(os.getcwd()) if not > re.match('^.+\.((py)|(pyc))$', file)] > > You can also use fnmatch: > > from fnmatch import fnmatch > files = [file for file in os.listdir(os.getcwd()) if not fnmatch(file, > '*.py') and not fnmatch(file, '*.pyc')] Another option is to use glob. import glob p1 = glob.glob('*.py') p2 = glob.glob('*.pyc') all = glob.glob('*') # won't include '.', '..' non_py = set(all) - set(p1) - set(p2) Karthik From steve at REMOVE-THIS-cybersource.com.au Sun Sep 2 18:05:44 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 02 Sep 2007 22:05:44 -0000 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <13dmctogeh19410@corp.supernews.com> On Sun, 02 Sep 2007 21:00:45 +0200, Wildemar Wildenburger wrote: > Martin v. L?wis wrote: >>>> (2) it is a interpretation language >>> Not quite. It's compiled to byte-code - just like Java (would you call >>> Java an 'interpreted language' ?) >> >> Python is not implemented like Java. In Java (at least in HotSpot), the >> byte code is further compiled to machine code before execution; in >> Python, the byte code is interpreted. >> > OK, good. Naive question now comming to mind: Why doesn't Python do the > latter as well? > > /W There is no single version of Java, and the reference interpretation runs on a virtual machine just like Python. Today there are virtual machine implementations of Java, native compilers, and Just In Time compilers for Java, including HotSpot mentioned by Martin, but Java the language was originally defined to run on a VM. See, for example, here: http://schmidt.devlib.org/java/compilers.html There are costs to native compilation, the biggest one of course being the initial investment in time and effort in creating the native compiler. Sun and other commercial companies have invested a lot of money in Java, and I don't think the money invested in Python has come even close. Consequently, any work into JIT compilation for Java has been done by volunteers. Nevertheless, we have Psyco, which is a JIT compiler of sorts; work also continues on PyPy (Python implemented in Python) which, it is hoped, will lead to faster Python implementations. Part of the reason that native compilation for Python is hard is that Python's dynamic object model makes it very difficult to apply the same sorts of compiler optimizations that C and Java allow. Comparatively little of the work done by Python can be safely pushed from run time to compile time, so it is unlikely that the average Python application will ever run as fast as the equivalent C code -- although that ignores the question of what "the equivalent C code" could possibly mean. (If the C code includes all the dynamic high-level features of Python, it too would surely run as slowly as Python, and if it didn't, it can hardly be said to be equivalent.) Nevertheless, by using something like Psyco parts of your Python code can run at virtually the same speed as C. A big question mark in my mind is Lisp, which according to aficionados is just as dynamic as Python, but has native compilers that generate code running as fast as highly optimized C. I'm not qualified to judge whether the lessons learnt from Lisp can be applied to Python, but in any case Lisp is an old, old language -- only Fortran is older. The amount of development effort and money put into Lisp dwarfs that put into Python by possibly a hundred or more. So... if you'd like to see Python run as fast as C or Lisp, and you have a few tens of millions of dollars spare to invest in development, I think the Python Software Foundation would love to hear from you. -- Steven. From dsanchez at e2000.es Thu Sep 27 07:26:39 2007 From: dsanchez at e2000.es (=?iso-8859-1?Q?David_S=E1nchez_Mart=EDn?=) Date: Thu, 27 Sep 2007 13:26:39 +0200 Subject: mod_python preprocess/filter before proxy Message-ID: <004301c800f9$45dcbcd0$0414a8c0@e2000.local> Hi! I've seen the message below in this python list, that seems to be unanswered. I'm trying to do the pretty same thing. There's a way to preprocess the request with a mod_python handler and then proxying it with mod_proxy? Thank you very much in advance, and sorry for trying to revive such an old message. Cheers. > >whale whale at mycameo.com >Tue Mar 25 05:49:42 CET 2003 > >I use Apache2.0.44 and mod_python3.0.1. >I add ProxyPass and PythonHandler directives in httpd.conf >## httpd.conf >ProxyPass /test/ http://www.test.com >ProxyPassReverse /test/ http://www.test.com > > AddHandler python-program .htm .html > PythonHandler mptest > > > >And mptest.py: >from mod_python import apache >def handler(req): > req.write('Hello!!') > return apache.OK > >ex. My apache server is www.server.com. >When I browsed the local server request(ex. >http://www.server.com/1.html), >I received 'Hello!!' response, the python handler worked well. >But when I browse the proxy request(ex. >http://www.server.com/test/1.html), >the response I received is the original content of >http://www.test.com/1.html, not 'Hello!!'. >The proxy requests didn't seem to be processed by mod_python handler. >How could I pre-process the proxy request before mod_proxy module? >Thanks a lot!! > --- David Sanchez Martin Administrador de Sistemas dsanchez at e2000.es GPG Key ID: 0x37E7AC1F E2000 Nuevas Tecnolog?as Tel : +34 902 19 61 77 -------------- next part -------------- A non-text attachment was scrubbed... Name: David S?nchez Mart?n.vcf Type: text/x-vcard Size: 1401 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 1465 bytes Desc: not available URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Sep 29 17:40:26 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 29 Sep 2007 23:40:26 +0200 Subject: List search References: Message-ID: <5m7v2aFc35svU1@mid.individual.net> Kevin Walzer wrote: > I'm having a problem with searching a list. Here's my code: > > mylist = ['x11', 'x11-wm', 'x11-system'] > > for line in mylist: > if 'x11' in line: > print line > > This results in the following output: > > x11 > x11-wm > x11-system > > I'm looking to return the list item that just has 'x11'. Why do you want to have an item you already know? If you just wanted to check *if* the string "x11" is in the list, you'd use if "x11" in mylist: Regards, Bj?rn -- BOFH excuse #221: The mainframe needs to rest. It's getting old, you know. From bdesth.quelquechose at free.quelquepart.fr Sun Sep 9 08:26:08 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 09 Sep 2007 14:26:08 +0200 Subject: Python code-writing for the blind. Was (Re: newbie: stani's pythoneditor if-else) In-Reply-To: References: Message-ID: <46e6dc13$0$22499$426a34cc@news.free.fr> Hamilton, William a ?crit : >>From: madzientist >> >>Thanks, everybody, for the very very useful and kind responses. >> >>There is a second reason why I asked the question about automatic de- >>indenting. I am teaching myself Python partly so I can then help my >>technically astute, but blind friend learn programming. For the many >>reasons that Pythonistas like to cite often, I thought Python would be >>a good choice to learn programming, and that perhaps the indentation >>problem would be solved by the use of an intelligent editor. >> >>But now I am not so sure, though I will try Emacs. Is there anyone >>here with experience in such issues ? There has been recently a thread about the use of a preprocessor for blind Python programmers, you may want to have a look: http://groups.google.fr/group/comp.lang.python/browse_thread/thread/80654a87bfa89e3b/de268f888d9cdf0e (snip) >>More seriously, the added issue is that SPE uses spaces, not a single >>tab to indent the lines, Most code editor let you configure this. wrt/ Python, just make sure you do not, never, mix tabs and spaces. (snip) From kyosohma at gmail.com Thu Sep 6 13:29:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 06 Sep 2007 17:29:19 -0000 Subject: Finding specific date ranges In-Reply-To: References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> Message-ID: <1189099759.833051.253020@y42g2000hsy.googlegroups.com> On Sep 6, 10:57 am, Tim Golden wrote: > kyoso... at gmail.com wrote: > > Hi, > > > I am working on a timesheet application in which I need to to find the > > first pay period in a month that is entirely contained in that month > > to calculate vacation time. Below are some example date ranges: > > > December 31, 2006 January 13, 2007 # doesn't earn > > January 14, 2007 January 27, 2007 # does earn > > January 28, 2007 February 10, 2007 # doesn't > > February 11, 2007 February 24, 2007 # does > > > So far, the best approach I've come up with is to create a list of > > tuples that contain the pay period date ranges for the year and > > iterate through the tuples looking for the first occurrence of the > > month names matching. Then I'd add that date range to a separate list > > and somehow ignore any other matches in that month. This seems like a > > hack. Does anyone have a better idea? > > Well, I can come up with a solution which basically reflects the > way I'd do it in SQL (since this kind of thing is my bread-and-butter > there) but I'm not convinced it's really any better than your proposal. > However, for the purposes of illustration: > > > import calendar > import datetime > > YEAR = 2007 > > months = [ > (datetime.date (YEAR, n, 1), datetime.date (YEAR, n, calendar.monthrange (YEAR, n)[1])) > for n in range (1, 13) > ] > > periods = [ > (datetime.date(2006, 12, 31), datetime.date(2007, 1, 13)), > (datetime.date(2007, 1, 14), datetime.date(2007, 1, 27)), > (datetime.date(2007, 1, 28), datetime.date(2007, 2, 10)), > (datetime.date(2007, 2, 11), datetime.date(2007, 2, 24)) > ] > > for m in months: > candidate_periods = [p for p in periods if m[0] <= p[0] and p[1] <= m[1]] > if candidate_periods: > print m[0], "=>", min (candidate_periods) > else: > print m[0], "=>", "no period matches" > > > > TJG Thanks! I'll try it both ways and see if there's any appreciable difference in speed, although since it will be packaged into an executable, that may not be an issue anyway. Mike From orsenthil at gmail.com Sun Sep 9 20:22:57 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Mon, 10 Sep 2007 05:52:57 +0530 Subject: os.sep and os.path.sep In-Reply-To: <1189352918.534864.195850@g4g2000hsf.googlegroups.com> References: <1189352918.534864.195850@g4g2000hsf.googlegroups.com> Message-ID: <20070910002257.GA3416@gmail.com> * billiejoex [2007-09-09 08:48:38]: > >>> import os > >>> hasattr(os, 'sep') > True > >>> hasattr(os.path, 'sep') > True > > By chance I noticed it. > Are there differences (I think not...)? > IMHO, if there are no differences os.path.sep should be removed since > it may be confusing. If you lookup os module, not only os.sep but couple of other values are also imported from os.path. from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, devnull) Yes, you are right. There are no differences. They exists there for utility purposes. Removing them would be a bad idea. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From mccredie at gmail.com Sun Sep 23 13:48:04 2007 From: mccredie at gmail.com (Matt McCredie) Date: Sun, 23 Sep 2007 10:48:04 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190491227.688310.247030@w3g2000hsg.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> <1190394011.148384.106280@q3g2000prf.googlegroups.com> <1190417120.723579.267560@22g2000hsm.googlegroups.com> <5ljrklF8gic1U3@mid.uni-berlin.de> <1190491227.688310.247030@w3g2000hsg.googlegroups.com> Message-ID: <9e95df10709231048k81179fbo31bb3cdbb09b8f22@mail.gmail.com> > Yes, Digital Mars D is what I was referring to and yes I know D is not > as efficient as C++. If I knew of a good C++ compiler that is not > from Microsoft that works natively with Windows I would be happy to > consider using it. I've had good luck with MinGW (gcc compiled for windows). http://www.mingw.org Matt From bignose+hates-spam at benfinney.id.au Wed Sep 19 23:41:06 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 20 Sep 2007 13:41:06 +1000 Subject: Mixin classes and single/multiple inheritance References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> <877immvye0.fsf_-_@benfinney.id.au> <1190257864.945639.199230@k79g2000hse.googlegroups.com> Message-ID: <87y7f2uhpp.fsf@benfinney.id.au> Michele Simionato writes: > It is already possible to use a syntax like this > > class MyClass(Base): > mixin(Mixin1, Mixin2, ...) > > using P.J. Eby's trick for implementing what he calls class > decorators (see also > http://www.phyast.pitt.edu/~micheles/python/classinitializer.html) > > But I would not use it, let's use the language we have, not > to invent our own. Okay. How do we use the language we have to achieve what mixin classes achieve in Ruby? Can you give an code example that you *would* recommend for someone looking to do what mixin classes do? -- \ "In case you haven?t noticed, [the USA] are now almost as | `\ feared and hated all over the world as the Nazis were." -- | _o__) Kurt Vonnegut, 2004 | Ben Finney From bogus@does.not.exist.com Fri Sep 7 09:03:45 2007 From: bogus@does.not.exist.com (Thin Myrna) Date: Fri, 7 Sep 2007 15:03:45 +0200 Subject: wxPython unexpected exit References: <1189152617.169438.296630@d55g2000hsg.googlegroups.com> Message-ID: <46e14c12$0$11094$3b214f66@aconews.univie.ac.at> "Jimmy" wrote in message news:1189152617.169438.296630 at d55g2000hsg.googlegroups.com... > Hi, wxPython is cool and easy to use, But I ran into a problem > recently when I try to write a GUI. > The thing is I want to periodically update the content of StatixText > object, so after create them, I pack them into a list...the problem > comes when I later try to extract them from the list! I don't know > why? > my code is as following: > > import wx, socket > import thread > > class MyFrame(wx.Frame): > > firstrun = 0 > def __init__(self): > wx.Frame.__init__(self, None, -1, 'Notifier') > self.panel = wx.Panel(self, -1) > self.length = 50 > self.scale = 0.6 > self.count = 5 > self.size = wx.Frame.GetSize(self) > self.distance = self.size[1] / self.count > self.labellist = [] > self.gaugelist = [] > > def ParseAndDisplay(self, data): > print "Successful access to main Frame class" > print 'And receive data: ', data > if MyFrame.firstrun == 0: > print 'First time run' > items = 3 > for i in range(items): > self.labellist.append(wx.StaticText(self.panel, -1, data+str(i), > (150, 50+i*20), (300,30))) > MyFrame.firstrun = 1 > else: > self.labellist[0].SetLabel('AAA')//PROGRAM WILL ABORT HERE!!! > self.labellist[1].SetLabel("Guo") > self.labellist[2].SetLabel("Qiang") > > > class NetUdp: > > def __init__(self): > self.port = 8081 > self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > self.s.bind(("", self.port)) > print "Listening on port", self.port > > def recvdata(self): > data, addr = self.s.recvfrom(1024) > return data > > > def netThread(): > netudp = NetUdp() > while True: > data = netudp.recvdata() > frame.ParseAndDisplay(data) > > if __name__ == '__main__': > firstrun = 0 > app = wx.PySimpleApp() > frame = MyFrame() > frame.Show() > # start network thread first > id = thread.start_new_thread(netThread, ()) > # main wxpython loop begins > app.MainLoop() > > I know the code is ugly, but can anyone really save me here! > Communication OS thread -> wx has to be done in a certain way. You must not do this directly, i.e. you must not call wx code from w/i an OS thread. See the wxPython Demo for an example of what you want to do: Process and Events -> Threads. Cheers Thin From cjt22 at bath.ac.uk Tue Sep 4 07:52:47 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Tue, 04 Sep 2007 04:52:47 -0700 Subject: Printing lists in columns (was: TypeError: 'module object is not callable') In-Reply-To: References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> Message-ID: <1188906767.737741.267350@19g2000hsx.googlegroups.com> > But watch out if the lists aren't all the same length: zip won't pad out > any sequences, so it maynotbe exactly what is wanted here: > > >>> x = ['1', '2', '3'] > >>> y = ['4', '5'] > >>> for row in zip(x,y): > > print ', '.join(row) > > 1, 4 > 2, 5 > Unfortunately the lists will be of different sizes By the way I apologise for different questions within the same thread. When I have another question, I will make a new topic From daniel.j.larsson at gmail.com Wed Sep 5 06:27:50 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Wed, 5 Sep 2007 12:27:50 +0200 Subject: concise code (beginner) In-Reply-To: <13dsvqrqivtf092@corp.supernews.com> References: <13dsvqrqivtf092@corp.supernews.com> Message-ID: <2bfa72fa0709050327y2edf081anb579cc7c65b75183@mail.gmail.com> def process_devs(devs, fun): for dev in devs: try: fun(dev) except: print exception remove dev from devs return devs process_devs(devs, lambda d: d.read1()) process_devs(devs, lambda d: d.read2()) ... On 9/5/07, bambam wrote: > > I have about 30 pages (10 * 3 pages each) of code like this > (following). Can anyone suggest a more compact way to > code the exception handling? If there is an exception, I need > to continue the loop, and continue the list. > > Steve. > > ----------------------------------- > for dev in devs > try: > dev.read1() > except > print exception > remove dev from devs > > for dev in devs > try: > dev.read2() > except > print exception > remove dev from devs > > for dev in devs > try: > dev.read3() > except > print exception > remove dev from devs > > etc. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.nospam at rudin.co.uk Wed Sep 5 06:00:38 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 05 Sep 2007 11:00:38 +0100 Subject: creating really big lists References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> Message-ID: <87ejhd2zzt.fsf@rudin.co.uk> Dr Mephesto writes: > Hi! > > I would like to create a pretty big list of lists; a list 3,000,000 > long, each entry containing 5 empty lists. My application will append > data each of the 5 sublists, so they will be of varying lengths (so no > arrays!). > > Does anyone know the most efficient way to do this? I have tried: > > list = [[[],[],[],[],[]] for _ in xrange(3000000)] > > but its not soooo fast. Is there a way to do this without looping? You can do: [[[],[],[],[],[]]] * 3000000 although I don't know if it performs any better than what you already have. From bj_666 at gmx.net Mon Sep 17 04:27:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Sep 2007 08:27:17 GMT Subject: where are the .pyc files? References: <1189963710.714191.74440@n39g2000hsh.googlegroups.com> <5l57t1F655kfU5@mid.uni-berlin.de> <1189992200.860524.58620@w3g2000hsg.googlegroups.com> Message-ID: <5l6s35F64s8vU1@mid.uni-berlin.de> On Mon, 17 Sep 2007 01:23:20 +0000, Summercool wrote: > On Sep 16, 10:36 am, Marc 'BlackJack' Rintsch wrote: >> >> The `*.pyc` files are usually only created when you import a module, not >> when a module is run directly. > > how come a program that runs directly doesn't need to be optimized > into bytecode first? Programs need to be compiled to bytecode and they actually are. The bytecode is just not dumped into a file but compiled at every run. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Sat Sep 1 01:13:30 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 31 Aug 2007 22:13:30 -0700 Subject: HowTo Use Cython on a Windows XP Box? In-Reply-To: <1188618022.208258.15620@22g2000hsm.googlegroups.com> References: <1188618022.208258.15620@22g2000hsm.googlegroups.com> Message-ID: <1188623610.532790.114000@o80g2000hse.googlegroups.com> On Sep 1, 1:40 pm, Paul McGuire wrote: > On Aug 31, 9:06 pm, David Lees wrote: > > > August 31, 2007 > > > I just downloaded the current Cython release and have no problem running > > the cpython.py translator on the demo code. But when I try compiling, I > > get an error complaining that my version of Python (which is the current > > 2.5.1 downloaded from python.org) was compiled with Visual C++ 2003. I > > only have Visual C++ 2005 on my machine and am unable to find a download > > of 2003 on the Microsoft site (no big surprise). I have never built > > Python from source. Is it necessary or can someone suggest an alternative? > > > TIA > > > david lees > > Unless you are customizing Python (and you can accomplish a *lot* > without doing so), it is not necessary to build Python from source. > Download one of the pre-built Windows binaries and install it, or get > the Win Python distribution from ActiveState and install that. Then > start writing your own Python demo scripts. > Paul, AFAICT the OP is referring not to CPython, but to Cython, which is a Pyrex fork. See http://www.cython.org/ Building CPython from source is likely to be a red herring. The OP's question appears to be "How do I, on Windows, compile C code generated by Cython into a pyd that will play happily with the standard-issue python.exe and python25.dll?", and is probably best directed to one of the 3 forums mentioned on the above-referenced page. HTH, John From ricaraoz at gmail.com Fri Sep 21 19:15:34 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 21 Sep 2007 20:15:34 -0300 Subject: Counting method calls Message-ID: <46F45096.2000509@bigfoot.com> Hi, I know I'm being dumb but, why does it not work? >>> class MyList(list): ... def __init__(self): ... self.calls = 0 ... def __getattr__(self, name): ... self.calls += 1 ... return list.__getattribute__(self, name) >>> a = MyList() >>> a [] >>> a.append(1) >>> a [1] >>> a.calls 88 >>> a.append(3) >>> a.calls 88 >>> a.sort() >>> a [1, 3] >>> a.calls 176 TIA From mccredie at gmail.com Tue Sep 25 12:18:30 2007 From: mccredie at gmail.com (Matimus) Date: Tue, 25 Sep 2007 16:18:30 -0000 Subject: comparing elements of a list with a string In-Reply-To: <1190734785.439839.303030@50g2000hsm.googlegroups.com> References: <1190734785.439839.303030@50g2000hsm.googlegroups.com> Message-ID: <1190737110.939047.101990@22g2000hsm.googlegroups.com> Shriphani wrote: > Hello all, > I have a problem here. I have a list named list_of_files which > contains filenames with their timestamps attached to the name. If I > have a string "fstab", and I want to list out the files in whose names > the word fstab appears should I go about like this : > > def listAllbackups(file): > list_of_files = os.listdir("/home/shriphani/backupdir") > for element in list_of_files: > if element.find(file) != -1: > date = ### > time = #### > return (date, time) > > The major trouble is that the return statement causes it to exit after > attempt one. How do I use the yield statement here? I would just do this: [code] from glob import glob def listallbackupfiles(filename): return glob("/home/shriphani/backupdir/*%s*"%filename) [/code] From paul.nospam at rudin.co.uk Tue Sep 18 13:19:37 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Tue, 18 Sep 2007 18:19:37 +0100 Subject: can Python be useful as functional? References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Message-ID: <871wcvlwly.fsf@rudin.co.uk> Robin Becker writes: > Steve Holden wrote: >> Lorenzo Stella wrote: > ...... >> So, which environment do you habitually use that provides an >> *unlimited* stack? >> >> You remind me of the conversation between the philosopher and an >> attractive lady whom he was seated next to at dinner. He asked her >> if she would sleep with him for a million dollars, to which she >> readily agreed. So he followed this by asking her if she'd sleep >> with him for a dollar. She replied: "No. Do you take me for a >> prostitutte?", to which his riposte was "We have already established >> that fact, and are now merely haggling about the price". >> > > allegedly G B Shaw > (http://findarticles.com/p/articles/mi_qn4158/is_19980925/ai_n14182408) Also allegedly Winston Churchill, although wikiquote says: "This is a very old joke where the participants vary dramatically from each telling. It's very unlikely though not impossible that the joke originated from Churchill." From bignose+hates-spam at benfinney.id.au Tue Sep 18 01:52:15 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 18 Sep 2007 15:52:15 +1000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <1i4lvsx.mhw5621jlsd53N%aleax@mac.com> Message-ID: <87ir68zfjk.fsf@benfinney.id.au> Sorry, I read your message too fast and responded to the wrong point :-) aleax at mac.com (Alex Martelli) writes: > Ben Finney wrote: > > Am I mistaken in thinking that "superclass of foo" is equivalent > > to "parent class of foo"? If so, I'd lay heavy odds that I'm not > > alone in that thinking. > > In general, "a superclass of foo" means "a class X such that foo is a > sublass of X" Read "ancestor" where I wrote "parent", then. It seems that (with that substitution) my thinking is correct. Yes? Why, then, does super() traverse the MRO of class 'A', instead of the ancestors of class 'A'? And, since that's what it does, is it not misnamed, since "next in the MRO" is *not* the same thing as "superclass"? -- \ "Remember: every member of your 'target audience' also owns a | `\ broadcasting station. These 'targets' can shoot back." -- | _o__) Michael Rathbun to advertisers, news.admin.net-abuse.email | Ben Finney From martin at v.loewis.de Tue Sep 11 17:06:42 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 11 Sep 2007 23:06:42 +0200 Subject: Py2.5.1 on Ubuntu AMD X2, unicode problems In-Reply-To: References: Message-ID: <46e70362$0$7896$9b622d9e@news.freenet.de> > I'm building 2.5.1 from source, using the ubuntu(7.0.4)-provided gcc > 4.1.2. Something must be terribly wrong with your system if you have to go through such hassles. It should build out of the box, and does for me on Debian. Regards, Martin From wolf_tracks at invalid.com Thu Sep 20 23:47:41 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 20 Sep 2007 20:47:41 -0700 Subject: An Editor that Skips to the End of a Def In-Reply-To: <874phou1pa.fsf@benfinney.id.au> References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <874phou1pa.fsf@benfinney.id.au> Message-ID: How about in the case of MS Win? Ben Finney wrote: > "W. Watson" writes: > >> Is vim just an editor or is it capable of running and debugging a >> program, as well? > > (Please don't top-post. Instead, reply below each point to which > you're responding, removing quoted text irrelevant to your response.) > > Both Emacs and Vim are highly customisable text editors. They are > configurable with complete programming languages specific to the > program, and both have a huge community of programmers writing useful > extensions. > > So, neither of them is "just an editor"; they are editors at their > core, that can become complete programming environments by taking > already-written components for them. Your operating system > distribution of either Vim or Emacs will already include many of these > components when you install the package, and many more are available. > -- Wayne Watson (Nevada City, CA) Web Page: From steve at holdenweb.com Tue Sep 11 23:14:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 23:14:18 -0400 Subject: function to do dynamic import? In-Reply-To: <13eek2h7lcikm5b@corp.supernews.com> References: <13ecb84p1ghrd64@corp.supernews.com> <13eek2h7lcikm5b@corp.supernews.com> Message-ID: bambam wrote: [...] > def gim(self): > for gamel in self.gamel_list: > __import__(gamel['file']) > > Works as hoped for. I did a web search for 'dynamic import' and > the only examples I found used exec. > > Thanks > Cool. You're getting there! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From rt at nospam.com Tue Sep 18 17:58:48 2007 From: rt at nospam.com (Richard Townsend) Date: Tue, 18 Sep 2007 22:58:48 +0100 Subject: Tutorial or Example (or Tutorial) of Using Canvas to Produce a Plot References: <13evohih7rkd030@corp.supernews.com> <13f0b2qlvj5ige6@corp.supernews.com> Message-ID: <9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com> On Tue, 18 Sep 2007 13:18:36 -0700, "W. Watson" wrote: >Tk is it. I'm really not interested in the others at this point. > John Grayson's book 'Python and Tkinter Programming' has a chapter on plotting Graphs and Charts. You can even download that chapter as a PDF file: http://www.manning-source.com/books/grayson/grayson_ch11.pdf See http://www.manning.com/grayson/ for more info about the book. From zentraders at gmail.com Thu Sep 27 20:51:58 2007 From: zentraders at gmail.com (Zentrader) Date: Thu, 27 Sep 2007 17:51:58 -0700 Subject: Creating Table using Tkinter In-Reply-To: <1190918535.924299.22750@k79g2000hse.googlegroups.com> References: <1190918535.924299.22750@k79g2000hse.googlegroups.com> Message-ID: <1190940718.952849.135510@k79g2000hse.googlegroups.com> Two existing solutions are TableList + TableListWrapper (Google for it), and MultiListBox http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52266 In both cases you send the program the titles and data and the program takes care of all of the details. BTW, you can attach a scrollbar to any Tk app, so that shouldn't be a concern. See here for some scrollbar examples. http://infohost.nmt.edu/tcc/help/pubs/tkinter/ From skip at pobox.com Sat Sep 1 15:15:54 2007 From: skip at pobox.com (Skip Montanaro) Date: Sat, 1 Sep 2007 19:15:54 +0000 (UTC) Subject: datetime.timedelta division confusion References: <1188672183.410842.27070@r29g2000hsg.googlegroups.com> Message-ID: > Try d // 2 ? > It may be that v2.6 considers / as __truediv__ and not __div__. Ah, right you are. Thanks... Skip From mensanator at aol.com Sun Sep 16 20:45:24 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 16 Sep 2007 17:45:24 -0700 Subject: Try this In-Reply-To: References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> Message-ID: <1189989924.078654.9290@k79g2000hse.googlegroups.com> On Sep 16, 6:25?pm, Steve Holden wrote: > mensana... at aol.com wrote: > > On Sep 16, 5:28?pm, John Machin wrote: > >> On Sep 17, 7:54 am, "mensana... at aol.com" wrote: > > >>> On Sep 16, 2:22?pm, Steve Holden wrote: > >>>> mensana... at aol.com wrote: > >>>>> On Sep 16, 1:10?pm, Dennis Lee Bieber wrote: > >>>>>> On Sun, 16 Sep 2007 01:46:34 -0700, GeorgeRXZ > >>>>>> declaimed the following in comp.lang.python: > >>>>>>> Then Open the Notepad and type the following sentence, and save the > >>>>>>> file and close the notepad. Now reopen the file and you will find out > >>>>>>> that, Notepad is not able to save the following text line. > >>>>>>> Well you are speed > >>>>>>> This occurs not only with above sentence but any sentence that has > >>>>>>> 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) > >>>>>> I tried. I also opened the saved file in SciTE... > >>>>>> And the text WAS there... > >>>>>> It is Notepad that can not properly render what it, > >>>>>> itself, saved. > >>>>> C:\Documents and Settings\mensanator\My Documents>type huh.txt > >>>>> Well you are speed > >>>>> Yes, file was saved correctly. > >>>>> But reopening it shows 9 unprintable characters. > >>>>> If I copy those to a new file (huh1.txt): > >>>>> C:\Documents and Settings\mensanator\My Documents>type huh1.txt > >>>>> ????????? > >>>>> But wait...the new file is 20 characters, not 9. > >>>>> 09/16/2007 01:44 PM 18 huh.txt > >>>>> 09/16/2007 01:54 PM 20 huh1.txt > >>>>> C:\Documents and Settings\mensanator\My Documents>dump huh.txt > >>>>> huh.txt: > >>>>> 00000000 5765 6c6c 2079 6f75 2061 7265 2073 7065 Well you are spe > >>>>> 00000010 6564 ed > >>>>> Here's what it's actually doing: > >>>>> C:\Documents and Settings\mensanator\My Documents>dump huh1.txt > >>>>> huh1.txt: > >>>>> 00000000 fffe 5765 6c6c 2079 6f75 2061 7265 2073 .~Well you are s > >>>>> 00000010 7065 6564 peed > >>>> One word: Unicode. > >>>> The "open" and "save" dialogs allow you to specify an encoding. > >>> And the encoding specified was ANSI. > >>>> If you > >>>> specify Unicode the you will get what you see above. > >>> And if you specify ANSI _before_ you click the file name, > >>> the specification switches to Unicode and has to then > >>> be manually switched back to ANSI. > >>>> If you specify ANSI > >>>> you will get the text you entered. > >>> It's still a bug in the "open" dialog. > >> It's more like a bug/feature in its encoding detector. > > > It is NOT a feature. If I save something as ANSI, > > there is no excuse for it not to re-open in ANSI. > > >> I can get it to > >> switch to Unicode only if there's an even number of characters AND the > >> line is NOT terminated by CRLF -- add/remove one alpha character, or > >> hit the enter key at the end of the line, and it won't detect it as > >> Unicode when you open it again. > > >> You only get the BOM (0xfffe) if you are silly enough to save it while > >> it's open in Unicode mode. > > > That was a test. I wasn't so stupid as to save > > to the original file, but to make a copy. > > >>>> By the way, this has precisely what to do with Python? > >>> I've been known to use Notepad to create Python > >>> source code. > >> Your source code would have to be trivially short to trigger the > >> strange behaviour. > > > Makes you wonder what other edge cases aren't > > handled properly. > > > Makes you wonder why Microsoft doesn't employ > > professional programmers. > > Makes *me* wonder why you haven't got better things to do with your time. It's Sunday. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline- Hide quoted text - > > - Show quoted text - From gagsl-py2 at yahoo.com.ar Fri Sep 7 22:49:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Sep 2007 23:49:12 -0300 Subject: subprocess.communicate messes things up References: <1189216294.958415.289400@r29g2000hsg.googlegroups.com> Message-ID: En Fri, 07 Sep 2007 22:51:34 -0300, escribi?: > problem is that the first time I press a key, it works, but after it > just print the keys I press, the annoying line being the one with > communicate, any idea of what is happening ? > > child1 = subprocess.Popen("/usr/bin/mplayer -slave -quiet - > idle",stdin=subprocess.PIPE,stdout=FNULL,stderr=FNULL,shell=True) > while 1: > ch=getkey() > name=os.listdir("/home/shivan/"+ch) > file_to_load = "/home/shivan/"+ch+"/"+name[0] > print "loadfile "+file_to_load > output, errors = child1.communicate("loadfile "+file_to_load+" \n") communicate sends its input and waits until the process finishes, collecting all output. So it's not adequate for your needs. You should write directly to child1.stdin: child1.stdin.write("loadfile "+file_to_load+" \n") -- Gabriel Genellina From na at na.com Wed Sep 12 09:08:12 2007 From: na at na.com (Josh) Date: Wed, 12 Sep 2007 09:08:12 -0400 Subject: pythonesque constructs for c++ Message-ID: One of the best features of python is its ease of use, and the ease of use of its modules. Modules like os, os.path, and datetime are invaluable! Does anyone know of analagous c++ libraries? It seems to me that most of the functionality of these modules could easily be replicated in c++. Before I go about doing that, I was just wondering if anyone knows if they already exist? thanks, Josh From ricaraoz at gmail.com Sun Sep 9 19:16:52 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 09 Sep 2007 20:16:52 -0300 Subject: Modul (%) in python not like in C? In-Reply-To: <1189377800.482587.143060@22g2000hsm.googlegroups.com> References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> <46E4466C.2030303@sdf.lonestar.org> <1189377800.482587.143060@22g2000hsm.googlegroups.com> Message-ID: <46E47EE4.5080801@bigfoot.com> John Machin wrote: > On Sep 10, 8:05 am, Lee Harr wrote: >>>> Python will always yield a number x = m%n such that 0 <= x < n, but >>>> Turbo C will always yield a number such that if x = m%n -x = -m%n. That >>>> is, since 111 % 10 = 1, -111 % 10 = -1. The two values will always >>>> differ by n (as used above). >> Maybe it is an order-of-operations thing.... >> >> -111 % 10 = -1 >> (-111) % 10 = 9 >> ? > > and on the other hand, maybe it's not. Try to think of any language > where unary minus binds so loosely. Why the theoretical argument when you can TEST your assumptions? >>> -111 % 10 9 >>> (-111) % 10 9 From rcdailey at gmail.com Mon Sep 24 22:51:57 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 24 Sep 2007 21:51:57 -0500 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> Message-ID: <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> What I meant was that it's not an option because I'm trying to learn regular expressions. RE is just as built in as anything else. On 9/24/07, Steve Holden wrote: > > Robert Dailey wrote: > > > > > > On 9/24/07, *Gabriel Genellina* > > wrote: > > > > Yes: forget about regular expressions. ElementTree does that for > free: > > > > > > That's not an option. > > > Even though it's built into Python 2.5? That's a strange requirement. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From welcomestocontact at gmail.com Wed Sep 19 06:10:12 2007 From: welcomestocontact at gmail.com (welcomestocontact at gmail.com) Date: Wed, 19 Sep 2007 03:10:12 -0700 Subject: HTTP Protocol Client Message-ID: <1190196612.082912.149690@v23g2000prn.googlegroups.com> Hi, I am writing http protocol to get some data from servers. If i was using my localhost, getting replay from local and if want access other remote sites, i am getting error. Please reply it My localhost client script::: Code: ( python ) import httplib h = httplib.HTTP('localhost',80) h.putrequest('GET','') h.putheader('User-Agent','Lame Tutorial Code') h.putheader('Accept','text/html') h.endheaders() errcode,errmsg, headers = h.getreply() print errcode,errmsg, headers f = h.getfile() # Get file object for reading data data = f.read() print data f.close() the Reply getting from this:::: 403 Forbidden Date: Tue, 18 Sep 2007 05:20:36 GMT Server: Apache/2.0.52 (Red Hat) Accept-Ranges: bytes Content-Length: 3985 Connection: close Content-Type: text/html; charset=UTF-8 And some Html script If I want to access other sites::: import httplib h = httplib.HTTP('http://Google.com',80) h.putrequest('GET','') h.putheader('User-Agent','Lame Tutorial Code') h.putheader('Accept','text/html') h.endheaders() errcode,errmsg, headers = h.getreply() print errcode,errmsg, headers f = h.getfile() # Get file object for reading data data = f.read() print data f.close() I got the error like::: Traceback (most recent call last): File "c.py", line 6, in ? h.endheaders() File "/usr/lib/python2.3/httplib.py", line 712, in endheaders self._send_output() File "/usr/lib/python2.3/httplib.py", line 597, in _send_output self.send(msg) File "/usr/lib/python2.3/httplib.py", line 564, in send self.connect() File "/usr/lib/python2.3/httplib.py", line 532, in connect socket.SOCK_STREAM): socket.gaierror: (-2, 'Name or service not known') How can I access Remote sites using http protocol . I did'nt write server script. Thanks And Regards Allavarapu From hniksic at xemacs.org Thu Sep 20 04:31:46 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 20 Sep 2007 10:31:46 +0200 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <87k5qn5cwi.fsf@mulj.homelinux.net> <87y7f2w0xj.fsf@benfinney.id.au> Message-ID: <87tzppivpp.fsf@mulj.homelinux.net> Ben Finney writes: >> The definition of superclass is not the issue, the issue is >> "superclass *of which class*"? You expect super(A, self) to iterate >> only over superclasses of A, even when self is an instance of a >> subtype of A. > > Yes. Those are the specific parameters to the function call, so that > *is* what I expect. The specific parameters are a type and an instance. Those same parameters can and do allow for an implementation that accesses supertypes of type(self). That is in fact more logical; otherwise one could simply iterate over A.__bases__ and we wouldn't need an elaborate 'super' construct. Not iterating only over A's superclasses is the entire *point* of super. The only deficiency of super I see in this thread is incomplete documentation. From george.sakkis at gmail.com Mon Sep 17 09:48:41 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 17 Sep 2007 13:48:41 -0000 Subject: simple regular expression problem In-Reply-To: <1190034041.796626.66790@n39g2000hsh.googlegroups.com> References: <1190034041.796626.66790@n39g2000hsh.googlegroups.com> Message-ID: <1190036921.873800.28470@k79g2000hse.googlegroups.com> On Sep 17, 9:00 am, duikboot wrote: > Hello, > > I am trying to extract a list of strings from a text. I am looking it > for hours now, googling didn't help either. > Could you please help me? > > >>>s = """ \n\n28996\n\n\n28997\n""" > >>> regex = re.compile(r'', re.S) > >>> L = regex.findall(s) > >>> print L > > ['organisatie>\n28996\n > \n\n28997\n > I expected: > [('organisatie>\n28996\n > \n), (\n28997\n organisatie')] > > I must be missing something very obvious. The less obvious thing that you're missing is that regular expressions is not the best solution to every text-related problem. Thinking at a higher level helps sometimes; for example here you don't want to extract "a list of strings from a text", you want to extract specific elements from an XML data source. There are several standard and non standard python packages for XML processing, look for them online. Here's how to do it using the (3rd party) BeautyfulSoup module: >>> from BeautifulSoup import BeautifulStoneSoup >>> BeautifulStoneSoup(s).findAll('organisatie') [ 28996 , 28997 ] HTH, George From rcdailey at gmail.com Tue Sep 25 10:43:03 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 25 Sep 2007 09:43:03 -0500 Subject: Python script to optimize XML text In-Reply-To: <46F8B985.7000803@web.de> References: <496954360709241336i43173947sda5245c2d7477ecb@mail.gmail.com> <46F8B985.7000803@web.de> Message-ID: <496954360709250743t6eec0d51x6d713a97317e6260@mail.gmail.com> Hey guys, Thanks for everyone's input. I wanted to learn regular expressions, however I'm finding them to be quite evil. I think I've learned that it's always a good idea to make regex a very LAST resort. This is my opinion I'm developing on. In any case, I like the ideas mentioned here concerning using the XML parser to do the job for me. Thanks again everyone, I think I'll be going with the XML parser to do what I need. Have a good day everyone. On 9/25/07, Stefan Behnel wrote: > > Gabriel Genellina wrote: > > En Mon, 24 Sep 2007 17:36:05 -0300, Robert Dailey > > escribi?: > > > >> I'm currently seeking a python script that provides a way of > >> optimizing out > >> useless characters in an XML document to provide the optimal size for > the > >> file. For example, assume the following XML script: > >> > >> > >> > >> > >> > >> > >> > >> > >> By running this through an XML optimizer, the file would appear as: > >> > >> > > > > ElementTree does that almost for free. > > As the OP is currently using lxml.etree (and as this was a cross-post to > c.l.py and lxml-dev), I already answered on the lxml list. > > This is just to mention that the XMLParser of lxml.etree accepts keyword > options to ignore plain whitespace content, comments and processing > instructions, and that you can provide a DTD to tell it what > whitespace-only > content really is "useless" in the sense of your specific application. > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed Sep 19 05:50:21 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Sep 2007 11:50:21 +0200 Subject: AttributeError: How to list existing attributes? References: <5lc8lbF79ba8U1@mid.individual.net> Message-ID: <5lc9mtF7hll5U1@mid.uni-berlin.de> Thomas Guettler wrote: > Hi, > > how can you list the attributes of an object if you catch an > AttributeError? > > I couldn't find a reference in the exception object, which > points to the object. > > I want to call dir() on the object to list the user the known > attributes. > > Is there a way to find the object by inspecting the stacktrace? By looking at the code at the line the stacktrace lists? And at least for me, there is a type-information as well: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. clWelcome to rlcompleter2 0.96 for nice experiences hit multiple times >>> class Foo(object): pass ... >>> f = Foo() >>> f.foo Traceback (most recent call last): File "", line 1, in AttributeError: 'Foo' object has no attribute 'foo' >>> You can't possibly know which attributes the object has, though. Because it might be an attribute dynamically added. So the best thing is to put a print-statement before the exception-throwing line or put a import pdb; pdb.set_trace() there, and fiddle around with the object. Diez From aleax at mac.com Wed Sep 5 01:15:52 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 4 Sep 2007 22:15:52 -0700 Subject: Sort of an odd way to debug... References: <1188933503.704007.285590@22g2000hsm.googlegroups.com> Message-ID: <1i3xrwm.ah5pxyzzlxnaN%aleax@mac.com> xkenneth wrote: ... > What I'd like to do, is define a base class. This base class would > have a function, that gets called every time another function is > called (regardless of whether in the base class or a derived class), > and prints the doc string of each function whenever it's called. I'd > like to be able to do this without explicitly specifying the function > inside all of the other functions of a base class or derived class. So you need to write a metaclass that wraps every function attribute of the class into a wrapper performing such prints as you desire. The metaclass will be inherited by subclasses (unless metaclass conflicts intervene in multiple-inheritance situation). You don't appear to need the printing-wrapper to be a method, and it's simpler to have it be a freestanding function, such as: import functools def make_printing_wrapper(f): @functools.wraps(f) def wrapper(*a, **k): print f.__doc__ return f(*a, **k) return wrapper Now, the metaclass could be, say: import inspect class MetaWrapFunctions(type): def __init__(cls, name, bases, attrs): for k, f in attrs.iteritems(): if inspect.isfunction(f): attrs[k] = make_printing_wrapper(f) type.__init__(cls, name, bases, attrs) and the base class: class Base: __metaclass__ = MetaWrapFunctions Now, the code: > class Derived(Base): > """This function prints something""" > def printSometing(something) > #ghost function get's called here > print something > > Output would be: > This function prints something > something Should behave as you described. I have not tested the code I'm suggesting (so there might be some errors of detail) but the general idea should work. Alex From nospam.please at alum.com Tue Sep 4 09:42:42 2007 From: nospam.please at alum.com (n o s p a m p l e a s e) Date: Tue, 04 Sep 2007 06:42:42 -0700 Subject: Calling a dos batch file from python Message-ID: <1188913362.279426.290370@r34g2000hsd.googlegroups.com> Suppose I have a batch file called mybatch.bat and I want to run it from a python script. How can I call this batch file in python script? Thanx/NSP From ptmcg at austin.rr.com Sat Sep 8 20:10:38 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 08 Sep 2007 17:10:38 -0700 Subject: Parsing nested constructs In-Reply-To: <46e308d3$0$9153$426a74cc@news.free.fr> References: <46e308d3$0$9153$426a74cc@news.free.fr> Message-ID: <1189296638.625012.286250@k79g2000hse.googlegroups.com> On Sep 8, 3:42 pm, tool69 wrote: > Hi, > > I need to parse some source with nested parenthesis, like this : > > >cut------------- > > { > {item1} > { > {item2} > {item3} > } > > } > > >cut------------- > > In fact I'd like to get all start indexes of items and their end (or > lenght). > > I know regexps are rather limited for this type of problems. > I don't need an external module. > > What would you suggest me ? > > Thanks. Well, it is an external module, but pyparsing makes this pretty straightforward: from pyparsing import * data = """ { {item1} { {item2} {item3} } } """ # define delimiters, but suppress them from the output LBRACE,RBRACE = map(Suppress,"{}") # forward define recursive items list items = Forward() # items is zero or more words of alphas and numbers, or an embedded # group enclosed in braces items << ZeroOrMore( Word(alphanums) | Group( LBRACE + items + RBRACE ) ) # parse the input string, and print out the results print items.parseString(data) """ prints: [[['item1'], [['item2'], ['item3']]]] or: [ [ ['item1'], [ ['item2'], ['item3'] ] ] ] """ -- Paul From gigs at hi.t-com.hr Fri Sep 14 09:58:39 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 14 Sep 2007 15:58:39 +0200 Subject: recursion In-Reply-To: References: Message-ID: Steve Holden wrote: > Gigs_ wrote: >> sorry i think that i express wrong. having problem with english >> >> >> what i mean is how python knows to add all thing at the end of recursion >> >> >>> def f(l): >> if l == []: >> return [] >> else: >> return f(l[1:]) + l[:1] >> >> >> f([1,2,3]) >> >> recursion1 f([2,3]) + [1] >> >> recursion2 f([3]) + [2] or [2, 1]? >> >> recursion3 f([]) + [3] or [3, 2, 1] >> >> >> i dont get all this >> >> >>> def f(l): >> if l == []: >> print l >> return [] >> else: >> return f(l[1:]) + l[:1] >> >> >>> f([1,2,3]) >> [] >> [3, 2, 1] # how this come here? how python save variables from each >> recursion? >> >> >> sorry again for first post >> > I think the thing you are missing is that the recursive call f(l[1:]) in > the return statement causes the current call to be suspended until the > recursive call is complete. The new call has its own value for l, which > is the caller's l[1:]. Each new call creates a completely new namespace. > > A less complicated function might make it a little more obvious. > > def factorial(n): > print "n =", n > if n=0: > return 1 > else: > return n * factorial(n-1) > > Try running that with a few different arguments to show you how the > recursion works. > > regards > Steve >>> def factorial(n): print "n =", n if n==0: return 1 else: return n * factorial(n-1) >>> factorial(3) n = 3 n = 2 n = 1 n = 0 6 now i understand. but one question at the end this function return 1. how python knows that it needs to multiply 1 with all recursive returns. (why python didnt sum recursive return with 1?) that will be all, thanks in advance From knipknap at gmail.com Tue Sep 25 09:17:01 2007 From: knipknap at gmail.com (Samuel) Date: Tue, 25 Sep 2007 06:17:01 -0700 Subject: ANNOUNCE: Exscript 0.9.9 Message-ID: <1190726221.366322.87240@k79g2000hse.googlegroups.com> Introduction ------------- Exscript is a scripting language for automating Telnet or SSH sessions. It supports a wide range of features, such as parallelization, AAA authentication methods, TACACS, and a very simple template language. This release comes with many new features, and the documentation was also greatly improved. Please refer to the project page for documentation. A lot of changes were made since release 0.9.8, so 0.9.9 was added before the final 1.0. Hopefully this will be the last release before 1.0 stable. New since 0.9.8 ------------------ * The SSH adapter was completely reworked and should now be on par with the Telnet adapter. * The telnet adapter now supports negotiation. This means that a connection should now automatically choose a script-friendly terminal type. (e.g. one that uses no color control characters). * Exscript is now fully supported on Python >= 2.2. * SSH support is now optional. The protocol adapters are now loaded dynamically, such that SSH does not have to be installed if only Telnet is used. * The error handling of the parser was greatly improved, and more errors should now be detected at compile time. * Prompt recognition was further improved. * It is now possible to use \r and \n in strings. * Strings may now be concatenated using the "." operator. * Added "in" and "not in" operators for searching through a list. * Fixed: Escaping of some characters outside of code context did not work. * Fixed: Escaping quotes in a string would not work. * Added support for using $-prefixed variable names in strings. * Added the builtin variable "response", that now includes the response of the last command. * #-prefixed lines are now comments. * Fixed a bug that some operations would not work when accessing the iterator variable in the body of a loop tag. * Fix: In several cases accessing a variable would fail. * Added support for "while" and "until" loops. * Added support for "into" keyword. * Use friendlier thread names. Dependencies ------------- * Python 2.2 or greater * Python-crypto * Python-pexpect (optional, for SSH support) * ssh (optional, for SSH support) Download Exscript ------------------ Release: http://exscript.googlecode.com/files/exscript-0.9.9.tgz SVN instructions: http://code.google.com/p/exscript/source Links ------ Exscript project page: http://code.google.com/p/exscript/ Mailing list: http://groups.google.com/group/exscript Bug tracker: http://code.google.com/p/exscript/issues/list Browse the source: http://exscript.googlecode.com/svn/trunk/ From sreisscruz at gmail.com Tue Sep 11 20:08:47 2007 From: sreisscruz at gmail.com (Steve) Date: Tue, 11 Sep 2007 17:08:47 -0700 Subject: Help With PyParsing of output from win32pdhutil.ShowAllProcesses() In-Reply-To: <1189534321.833098.114700@g4g2000hsf.googlegroups.com> References: <1189534321.833098.114700@g4g2000hsf.googlegroups.com> Message-ID: <1189555727.675690.143240@v23g2000prn.googlegroups.com> Hi All, I did a lot of digging into the code in the module, win32pdhutil, and decided to create some custom methods. added to : import win32pdhutil def ShowAllProcessesAsList(): object = find_pdh_counter_localized_name("Process") items, instances = win32pdh.EnumObjectItems(None,None,object,win32pdh.PERF_DETAIL_WIZARD) # Need to track multiple instances of the same name. instance_dict = {} all_process_dict = {} for instance in instances: try: instance_dict[instance] = instance_dict[instance] + 1 except KeyError: instance_dict[instance] = 0 # Bit of a hack to get useful info. items = [find_pdh_counter_localized_name("ID Process")] + items[: 5] # print items # print "Process Name", string.join(items,",") all_process_dict['Headings'] = items # add headings to dict for instance, max_instances in instance_dict.items(): for inum in xrange(max_instances+1): hq = win32pdh.OpenQuery() hcs = [] row = [] for item in items: path = win32pdh.MakeCounterPath( (None,object,instance,None, inum, item) ) hcs.append(win32pdh.AddCounter(hq, path)) win32pdh.CollectQueryData(hq) # as per http://support.microsoft.com/default.aspx?scid=kb;EN-US;q262938, some "%" based # counters need two collections time.sleep(0.01) win32pdh.CollectQueryData(hq) # print "%-15s\t" % (instance[:15]), row.append(instance[:15]) for hc in hcs: type, val = win32pdh.GetFormattedCounterValue(hc, win32pdh.PDH_FMT_LONG) # print "item : %5d" % (val), row.append(val) win32pdh.RemoveCounter(hc) # print # print ' row = ', instance ,row all_process_dict[instance] = row # add current row to dict win32pdh.CloseQuery(hq) return all_process_dict def ShowSingleProcessAsList(sProcessName): object = find_pdh_counter_localized_name("Process") items, instances = win32pdh.EnumObjectItems(None,None,object,win32pdh.PERF_DETAIL_WIZARD) # Need to track multiple instances of the same name. instance_dict = {} all_process_dict = {} for instance in instances: try: instance_dict[instance] = instance_dict[instance] + 1 except KeyError: instance_dict[instance] = 0 # Bit of a hack to get useful info. items = [find_pdh_counter_localized_name("ID Process")] + items[: 5] # print items # print "Process Name", string.join(items,",") # all_process_dict['Headings'] = items # add headings to dict # print 'instance dict = ', instance_dict # print if sProcessName in instance_dict: instance = sProcessName max_instances = instance_dict[sProcessName] # print sProcessName, ' max_instances = ', max_instances for inum in xrange(max_instances+1): hq = win32pdh.OpenQuery() hcs = [] row = [] for item in items: path = win32pdh.MakeCounterPath( (None,object,instance,None, inum, item) ) hcs.append(win32pdh.AddCounter(hq, path)) try: win32pdh.CollectQueryData(hq) except: all_process_dict[sProcessName] = [0,0,0,0,0,0,0] # process not found - set to all zeros break # as per http://support.microsoft.com/default.aspx?scid=kb;EN-US;q262938, some "%" based # counters need two collections time.sleep(0.01) win32pdh.CollectQueryData(hq) # print "%-15s\t" % (instance[:15]), row.append(instance[:15]) for hc in hcs: type, val = win32pdh.GetFormattedCounterValue(hc, win32pdh.PDH_FMT_LONG) # print "item : %5d" % (val), row.append(val) win32pdh.RemoveCounter(hc) # print # print ' row = ', instance ,row all_process_dict[instance] = row # add current row to dict win32pdh.CloseQuery(hq) else: all_process_dict[sProcessName] = [0,0,0,0,0,0,0] # process not found - set to all zeros return all_process_dict ============================= Demo : import win32pdhutil # with customized methods in win32pdhutil (above) ################################################################### # GetMemoryStats # ################################################################### def GetMemoryStats(sProcessName, iPauseTime): Memory_Dict = {} ## Headings ['ProcessName', '% Processor Time', '% User Time', '% Privileged Time', 'Virtual Bytes Peak', 'Virtual Bytes'] ##machine process = {'firefox': ['firefox', 2364, 0, 0, 0, 242847744, 211558400]} loop_counter = 0 print('\n\n** Starting Free Memory Sampler **\n\n') print('Process : %s\n Delay : %d seconds\n\n') % (sProcessName, iPauseTime) print('\n\nPress : Ctrl-C to stop and output stats...\n\n') try: while 1: print('Sample : %d') % loop_counter row = [] machine_process = win32pdhutil2.ShowSingleProcessAsList(sProcessName) # print 'machine process = ', machine_process row.append(machine_process[sProcessName] [5]) # Virtual Bytes Peak row.append(machine_process[sProcessName] [6]) # Virtual Bytes Memory_Dict[loop_counter] = row # add values to the dictionary loop_counter += 1 time.sleep(iPauseTime) except KeyboardInterrupt: # Ctrl-C encountered print "End of Sample...\n\n" return Memory_Dict ################################################################### ############# M A I N ########################### ################################################################### def Main(): iPause_time = 5 # pause time - seconds sProcessName = 'firefox' # Process to watch sReportFileName = 'MemoryStats.csv' # output filename Memory_Dict = GetMemoryStats(sProcessName, iPause_time) outfile = open(sReportFileName,"w") # send output to a file outfile.write('SampleTime, VirtualBytesMax, VirtualBytes\n') for current_stat in Memory_Dict: line = ('%s,%d,%d\n') % (current_stat, Memory_Dict[current_stat] [0],Memory_Dict[current_stat][1] ) outfile.write(line) outfile.close() # close output file if __name__ == "__main__": Main() ------------------------- I have found that the process that you want to want to monitor needs to be started before this script is started. The script will handle when the process disappears and set the stats to zeros. Enjoy! Steve From dariusjack2006 at yahoo.ie Mon Sep 24 11:45:46 2007 From: dariusjack2006 at yahoo.ie (http://members.lycos.co.uk/dariusjack/) Date: Mon, 24 Sep 2007 08:45:46 -0700 Subject: To Andrey Khavryuchenko was: Who can develop the following Python script into working application ? Message-ID: <1190648746.213074.79210@y42g2000hsy.googlegroups.com> to Andrey Khavryuchenko he said: " Actually, I am a python (and django) developer, looking for a contract, owning Nokia 770 and contacted original poster with no response. -- Andrey V Khavryuchenko http://a.khavr.com/ Chytach - unflood your feeds http://www.chytach.com/ Software Development Company http://www.kds.com.ua/ " I didn't get any email from you. Please have a look at your mailbox to verify the above. Darius From python.list at tim.thechases.com Sun Sep 30 08:37:10 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 30 Sep 2007 07:37:10 -0500 Subject: Optparse and help formatting? In-Reply-To: <87abr423hu.fsf@benfinney.id.au> References: <87abr423hu.fsf@benfinney.id.au> Message-ID: <46FF9876.8000307@tim.thechases.com> >> I've been learning the ropes of the optparse module and have been >> having some trouble getting the help to format the way I want. > > A quick perusal of the 'optparse.py' code shows me this: > > ======== > [...] > class OptionParser([...]): > def __init__([...], > formatter=None, > [...]): > [...] > if formatter is None: > formatter = IndentedHelpFormatter() > [...] > ======== > > So, the OptionParser init method accepts the help formatter as the > 'formatter' argument, defaulting to a new instance of > IndentedHelpFormatter. > > Presumably, it's a matter of subclassing 'optparse.HelpFormatter' and > overriding the behaviour you want to change, then passing an instance > of your new class as the 'formatter' argument to the 'OptionParser()' > invocation. Ben, thanks for pointing me in the right direction. Digging in this code, it looks like textwrap.[fill|wrap] method calls were what was eating my NL and munging my tabs. While not a terribly elegant solution, as there's no easy way to intercept the two bits I want without copying and pasting a large bit of the format_description and format_option methods just to change the behavior of one call to textwrap.*, I did manage to get it working as desired. In the event that anybody else needs the solution I hacked together, I've pasted it below which, as Ben suggests, can be used with parser = OptionParser(... formatter=IndentedHelpFormatterWithNL() ) Hope this helps somebody else too. -tim class IndentedHelpFormatterWithNL(IndentedHelpFormatter): def format_description(self, description): if not description: return "" desc_width = self.width - self.current_indent indent = " "*self.current_indent # the above is still the same bits = description.split('\n') formatted_bits = [ textwrap.fill(bit, desc_width, initial_indent=indent, subsequent_indent=indent) for bit in bits] result = "\n".join(formatted_bits) + "\n" return result def format_option(self, option): # The help for each option consists of two parts: # * the opt strings and metavars # eg. ("-x", or "-fFILENAME, --file=FILENAME") # * the user-supplied help string # eg. ("turn on expert mode", "read data from FILENAME") # # If possible, we write both of these on the same line: # -x turn on expert mode # # But if the opt string list is too long, we put the help # string on a second line, indented to the same column it would # start in if it fit on the first line. # -fFILENAME, --file=FILENAME # read data from FILENAME result = [] opts = self.option_strings[option] opt_width = self.help_position - self.current_indent - 2 if len(opts) > opt_width: opts = "%*s%s\n" % (self.current_indent, "", opts) indent_first = self.help_position else: # start help on same line as opts opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) indent_first = 0 result.append(opts) if option.help: help_text = self.expand_default(option) # Everything is the same up through here help_lines = [] for para in help_text.split("\n"): help_lines.extend(textwrap.wrap(para, self.help_width)) # Everything is the same after here result.append("%*s%s\n" % ( indent_first, "", help_lines[0])) result.extend(["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]]) elif opts[-1] != "\n": result.append("\n") return "".join(result) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 12 07:30:14 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 12 Sep 2007 13:30:14 +0200 Subject: unexpected behavior: did i create a pointer? In-Reply-To: <1189416604.902880.24370@g4g2000hsf.googlegroups.com> References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <1189416604.902880.24370@g4g2000hsf.googlegroups.com> Message-ID: <46e7cdc6$0$12298$426a74cc@news.free.fr> neoedmund a ?crit : > On Sep 7, 4:07 pm, gu wrote: (snip pb and code) >> now, in the second "for" cycle and in functionA() i only 'touch' copyOfA >> (altering it). as i don't touch the variable "a", i expect it not to be >> affected by any change, but copyOfA acts like a pointer to a and >> altering copyOfA's values result in altering the values of "a", so the >> result that i expect is: (snip) > no language act like want you tought, or the assignment operation will > be too expensive. IIRC, php4 was doing copies for arrays... From kyosohma at gmail.com Thu Sep 13 09:26:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 13 Sep 2007 06:26:33 -0700 Subject: wxstyledtextctrl and xml markup In-Reply-To: References: Message-ID: <1189689993.338662.267340@k79g2000hse.googlegroups.com> On Sep 13, 6:23 am, OpenPavilion Team wrote: > Hello community, > > I want to create an editor for a self defined xml markup language. I want to > use wxpython with wxstyledtextctrl and I have looked around at yellowbrain > site, but there are no examples. I also watched the styledtextctrl examples > with wxpython 2.8.4. > > What I am looking for is an example of how to do the autocompletion part for > the styledtextctrl based on my self defined XML language. > > example: > > > > > > [...] > > > Since I don't know styledtextctrl, I fear that I am about to write a complex > handler for the autocompletion part, whereas there could be some easy to use > features built into styledtextctrl. My problem is that I don't want to > externalize the grammar of the XML instead of coding it inside the > autocompletion handler. > > Are there any examples for wxstyledtextctrl, xml and autocompletion ? > > Regards > Pavilion > -- > View this message in context:http://www.nabble.com/wxstyledtextctrl-and-xml-markup-tf4435096.html#... > Sent from the Python - python-list mailing list archive at Nabble.com. The demo for the StyledTextCtrl_2 mentions something about autocomplete in the code. Not sure what it's talking about though. The docs for it seem to link to Scintilla, so reading up on Scintilla's usage would probably be valuable. The wiki has one recipe on it for this control: http://wiki.wxpython.org/Using_Python_Regular_Expressions_with_StyledTextCtrl I highly recommend the wxPython mailing list. Right now it is down (see their website), but when it's back up (check their website for news), that's where I'd post this question if no one else here answers. Mike From m.n.summerfield at googlemail.com Tue Sep 25 07:25:39 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Tue, 25 Sep 2007 11:25:39 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> Message-ID: <1190719539.721683.282550@50g2000hsm.googlegroups.com> On 25 Sep, 12:11, Jeremy Sanders wrote: > Mark Summerfield wrote: > > If there is positive feedback I will submit the PEP to the reviewers, > > so if you think it is a good idea please say so. (I'm sure that if you > > _don't_ like it you'll tell me anyway:-) > > It would be nice to have the ability to use numerical indexes and the key, > but I don't think they should share the same methods. They don't; you use [] for key index and key(), value(), or item() for index access. > A useful use case would be to make a LRU (least recently used) dictionary, > where the keys are time-based (e.g. an incrementing counter). You should be > able to identify the least recently used object for discarding by just > accessing the last item in the dictionary. You could do that with a sorteddict simply by using datetime.date objects or timestamp strings for keys. You could get the first or last item (no matter what its key). For example: d = sorteddict({1200:"lunch", 1100:"elevensies", 1600:"tea", 1900:"dinner"}) d.items() [(1100, 'elevensies'), (1200, 'lunch'), (1600, 'tea'), (1900, 'dinner')] d.item(0), d.item(-1) ((1100, 'elevensies'), (1900, 'dinner')) So you could remove the last item using d.delete(-1). > By the way, I think a LRU cache dictionary would be a great addition to the > standard library. > > Is there any speed advantage from implementing the sorteddict as a red-black > tree or something similar in C? I'm sure that a C-based implementation using red-black or AVL trees or skiplists would be faster, but right now I'm just trying to get an acceptable API. Corrections to my original PEP: value(index : int) -> value # I incorrectly had the return value as key Also, now in the second example I use a tuple of string, int ID rather than strings. > Jeremy > > -- > Jeremy Sandershttp://www.jeremysanders.net/ From luojiang2 at tom.com Tue Sep 4 03:44:16 2007 From: luojiang2 at tom.com (Ginger) Date: Tue, 4 Sep 2007 15:44:16 +0800 Subject: how to get a formatted string? References: <46DCD51B.7040508@v.loewis.de> Message-ID: <006301c7eec7$654a9e00$4de1a8c0@amd.com> like format function in Visual Basic, format("##.##%",0.3456) ==>> 34.56% From Shawn at Milochik.com Wed Sep 12 06:42:09 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 12 Sep 2007 06:42:09 -0400 Subject: Difference between two times (working ugly code, needs polish) In-Reply-To: <1189587589.085002.34000@19g2000hsx.googlegroups.com> References: <13ee01cfc7f4be2@corp.supernews.com> <2dc0c81b0709111420r453ac15av6c7aa19473785080@mail.gmail.com> <1189587589.085002.34000@19g2000hsx.googlegroups.com> Message-ID: <2dc0c81b0709120342n49195770uf4536e7903f33af3@mail.gmail.com> > Just to be picky - your function returns the number of days between > two dates, but it's called isOld, which looks like it should return a > boolean. i.e. it looks like it would be used as: > > if not isOld(auctionDate, currentTime): > checkForBid() > > rather than how I assume it is used: > > if isOld(auctionDate, currentTime) <= 10: > checkForBid() > > I'd call it daysDiff or something similar, or make it more specific so > that it works like the first block of code above: You're absolutely right; I started writing it with one purpose in mind and changed it midstream. I actually renamed it yesterday to dayDiff. ;o) Shawn From fakeaddress at nowhere.org Thu Sep 27 02:15:49 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 27 Sep 2007 06:15:49 GMT Subject: database persistence with mysql, sqlite In-Reply-To: References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> <1190650748.590245.221490@n39g2000hsh.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > Bryan Olson wrote: > >> Lawrence D'Oliveiro wrote: >>> In Bryan Olson wrote: >>> >>>> coldpizza wrote: >>>>> It turned out that the method above ('SELECT * FROM TABLE LIMIT L1, >>>>> L2') works ok both with mysql and sqlite3, therefore I have decided to >>>>> stick with it until I find something better. With Sqlite3 you are >>>>> supposed to use LIMIT 10 OFFSET NN, but it also apparently supports >>>>> the mysql syntax (LIMIT NN, 10) for compatibility reasons. >>>> A more reliable form is along the lines: >>>> >>>> SELECT keyfield, stuff >>>> FROM table >>>> WHERE keyfield > ? >>>> ORDER BY keyfield >>>> LIMIT 10 >>>> >>>> With the right index, it's efficient. >>> But that involves keeping track of the right starting keyfield value for >>> the next batch of records, which is complicated and nontrivial. >> We write the link so that the browser will send back the parameter we >> need. If the largest keyfield value on the page is >> "Two-Sheds" the link might read: >> >> Next > > That's assuming keyfield is a) unique, Exactly; that was was the idea behind the name choice. The method extends to multi-column keys, so it is generally applicable. > and b) a relevant ordering for > displaying to the user. That's a nice-to-have, but not required. >> Keeping a cursor with pending data across HTTP requests is >> a world of hurt. > > "limit offset, count" avoids all that. It can be stateless, but then it is unreliable. Here's an example with Python 2.5: import sqlite3 db = sqlite3.connect(":memory:") # Simple table, an integer and the hex for that integer db.execute( "CREATE TABLE numbers (num INTEGER PRIMARY KEY, hex TEXT)") # Start with 10-29 in the table for i in range(10, 30): db.execute("INSERT INTO numbers VALUES (?, ?)", (i, hex(i))) # Print 4 records starting at offset def next4(offset): cur = db.execute( "SELECT * FROM numbers LIMIT 4 OFFSET ?", (offset,)) for x in cur: print x # Walk the table with LIMIT and OFFSET next4(0) # Good, prints 10-13 next4(4) # Good, prints 14-17 # Another transaction inserts new records for i in range(0, 4): db.execute("INSERT INTO numbers VALUES (?, ?)", (i, hex(i))) next4(8) # Bad, prints 14-17 again # Another transaction deletes records for i in range(0, 4): db.execute("DELETE FROM numbers WHERE num = ?", (i,)) next4(12) # Bad, we're missing 18-21 The method I advocated is still not the same as doing the whole thing in a serializable transaction, but it will return any record that stays in the table the whole time, and will not return any record multiple times. -- --Bryan From richyjsm at gmail.com Mon Sep 24 18:01:00 2007 From: richyjsm at gmail.com (richyjsm at gmail.com) Date: Mon, 24 Sep 2007 22:01:00 -0000 Subject: Nested For and While Statements In-Reply-To: <1190667172.491315.209110@y42g2000hsy.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190666647.199890.174670@o80g2000hse.googlegroups.com> <1190667172.491315.209110@y42g2000hsy.googlegroups.com> Message-ID: <1190671260.703917.279830@57g2000hsv.googlegroups.com> On Sep 24, 4:52 pm, kou... at hotmail.com wrote: > Here is my code, in the hopes that there is a reason why it isn't > running. Thanks guys. [code snipped] You're missing the closing parenthesis on the last line of the inner for loop. Richard From bdesth.quelquechose at free.quelquepart.fr Sun Sep 2 14:19:21 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 02 Sep 2007 20:19:21 +0200 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188585630.539835.242460@i38g2000prf.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <1188585630.539835.242460@i38g2000prf.googlegroups.com> Message-ID: <46dc74ad$0$8877$426a74cc@news.free.fr> Russ a ?crit : (snip) > Frankly, Mr. Holden, I'm getting a bit tired of the clannish behavior > here, where > "outsiders" like me are held to a higher standard than your "insider" > friends. I don't know who you are, nor do I care what you and your > little group think about me. If you took time to follow discussions on this group, you'd notice that newcomers are usually welcome. It's not a problem of being an "outsider" of an "insider", and there's nothing clannish (or very few, specially when compared to some other places on usenet), it's mostly a problem with your attitude. And please notice, once again, that I'm not talking about *you* - as a person - but about how you behave(d). (snip) From paul.hankin at gmail.com Mon Sep 24 18:02:48 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 24 Sep 2007 22:02:48 -0000 Subject: Nested For and While Statements In-Reply-To: <1190667172.491315.209110@y42g2000hsy.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190666647.199890.174670@o80g2000hse.googlegroups.com> <1190667172.491315.209110@y42g2000hsy.googlegroups.com> Message-ID: <1190671368.813611.260370@w3g2000hsg.googlegroups.com> First the bugs... On Sep 24, 9:52 pm, kou... at hotmail.com wrote: > ... > avcsasdoc = workspace + "\avcsas.txt" > ... There's quite a few cases like this where you don't escape backslashes, so your filenames are mostly mangled. Here \a produces character code 7, which is definitely wrong. Either escape them like this: '\\avcsas.txt' or use raw strings where backslashes aren't treated specially: r'\avcsas.txt'. You might want to look at the 'os.path' module for help in constructing filenames. You have a 'break' and the end of the last for loop. This has the effect of stopping the for loop at the first iteration. Either it's a bug, or you really didn't want a for loop! There's also quite a few places where your code could be improved: > classsum = avcclass[0] + avcclass[1] + avcclass[2] + > avcclass[3] + avcclass[4] + avcclass[5] \ > + avcclass[6] + avcclass[7] + avcclass[8] + avcclass[9] + > avcclass[10] \ > + avcclass[11] + avcclass[12] + avcclass[13] Is better written classsum = ''.join(avcclass[:14]) > addzeros = {1:"0", 2:"00", 3:"000", 4:"0000"} > ... > ... addzeros[numzeros] + lanex[i-1] Good idea, but in this case python provides an easier alternative: ... '0' * numzeros + lanex[i - 1] Or use the 'rjust' method which right-justifies a string: ... lanex[i - 1].rjust(5, '0') > for i in range(1,Nscheme+1): > numzeros = 5 - int(len(lanex[i-1])) > avcclass.append(addzeros[numzeros] + lanex[i-1]) > Nlanex.append(int(lanex[i-1]) Is better as for i in range(Nscheme): ... use i rather than i - 1 (I assume Visual Basic for loops are off by one). In fact, this loop is even better if you just iterate over lanex itself. Using a loop index rather than iterating directly is a common mistake. for lane in lanex: avcclass.append(lane.rjust(5, '0')) Nlanex.append(int(lane)) Or even better, use list comprehensions to construct your two lists explicitly: avcclass = [lane.rjust(5, '0') for lane in lanex] Nlanex = [int(lane) for lane in lanex] Note, each rewrite makes the intention of the code clearer, as well as being shorter. This makes your code easier to read and understand, and less buggy. Since all you do with avcclass is sum it, combine this with the classsum optimisation above to get classsum = ''.join(lane.rjust(5, '0') for lane in lanex[:14]) Nlanex = [int(lane) for lane in lanex] > lanex = [] > if numlanes == 2: > lane1 = newlist1[2:2+Nscheme] > lanex.append(lane1) > lane2 = newlist1[2+Nscheme:2+Nscheme*2] > lanex.append(lane2) > else: > lane1 = newlist1[2:2+Nscheme] > lanex.append(lane1) > lane2 = newlist1[2+Nscheme:2+Nscheme*2] > lanex.append(lane2) > lane3 = newlist1[2+Nscheme*2:2+Nscheme*3] > lanex.append(lane3) > lane4 = newlist1[2+Nscheme*3:2+Nscheme*4] > lanex.append(lane4) List comprehensions beat copy/paste: total_schemes = 2 if numlanes == 2 else 4 lanex = [newlist1[2 + i * Nscheme:2 + (i + 1) * Nscheme] for i in range(total_schemes)] HTH, and welcome to python! -- Paul Hankin From mccredie at gmail.com Tue Sep 4 13:08:57 2007 From: mccredie at gmail.com (Matimus) Date: Tue, 04 Sep 2007 17:08:57 -0000 Subject: Python is overtaking Perl In-Reply-To: <1188873133.137684.147260@r29g2000hsg.googlegroups.com> References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> <20070904024908.b8aca60c.sulsa@gazeta.pl> <1188869347.102325.119830@w3g2000hsg.googlegroups.com> <1188873133.137684.147260@r29g2000hsg.googlegroups.com> Message-ID: <1188925737.869396.316750@19g2000hsx.googlegroups.com> > So I think we can at least say from the chart that searches combining > the terms 'python' and 'programming' have been falling, by some > unquantifiable amount (it don't _look_ like much!?), relative to the > number of total searches. I think it is the search volume relative to the total number of searches. So, all the decline means is that the number of searches for "Python programming" releative to all searches done is declining. For example, there is a larger number of people searching for things like "Britney Spears", "Paris Hilton" and "pr0n" than there are for Python. It is simply a sign that Google is becoming more popular with the mainstream user, not python, ruby or even perl becoming less popular. Matt From shriphanip at gmail.com Thu Sep 27 12:48:53 2007 From: shriphanip at gmail.com (Shriphani) Date: Thu, 27 Sep 2007 16:48:53 -0000 Subject: True of False In-Reply-To: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> Message-ID: <1190911733.926189.228110@d55g2000hsg.googlegroups.com> kou... at hotmail.com wrote: > I tried writing a true and false If statement and didn't get > anything? I read some previous posts, but I must be missing > something. I just tried something easy: > > a = ["a", "b", "c", "d", "e", "f"] > > if "c" in a == True: > Print "Yes" > > When I run this, it runs, but nothing prints. What am I doing wrong? > Thanks. > > Kou Hello, Just try : a = ["a","b","c","d","e","f"] if "c" in a: print "yes" That is going to work as the statement '"c" in a' itself is true. You could try that by typing "c" in a at the interpreter. regards, Shriphani Palakodety From phil at riverbankcomputing.co.uk Sun Sep 23 17:34:54 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 23 Sep 2007 22:34:54 +0100 Subject: building a GUI In-Reply-To: <46F6CB6C.3050609@gmail.com> References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> <5lnp2rF90pqqU1@mid.uni-berlin.de> <46F6CB6C.3050609@gmail.com> Message-ID: <200709232234.54500.phil@riverbankcomputing.co.uk> On Sunday 23 September 2007, stef mientki wrote: > Diez B. Roggisch wrote: > > stef mientki schrieb: > >> Thomas Dybdahl Ahle wrote: > >>> Den Sun, 23 Sep 2007 17:28:38 +0200 skrev stef mientki: > >>>> yadin wrote: > >>>>> if i were up to make a GUI chich are the advantages of choosing > >>>>> python over matlab or java? > >>>> > >>>> The best is Delphi, > >>>> second is VB, > >>> > >>> That sounds mostly like a personal preference :) > >> > >> Well I prefer Python ( because of it's OS-independancy and it's open > >> source), > >> but Python is really (still) much worse for GUI designs. > >> Just compare some parameters like: > >> - ease of use > >> - speed of development > >> - support of features > >> - availability of libraries > >> - documentation > > > > Sounds like PyQt for me. Best GUI-designer I know, tremendous speed in > > development, giant sized lib that does all kinds of stuff & is > > brilliantly designed + professional grade docus. > > Could well be, > but I never looked at PyQt seriously, > because of their weird license. It's not weird. It's either GPL or proprietary. Your choice. That's as complicated as it gets. Phil From stefan.arentz at gmail.com Sun Sep 9 05:19:42 2007 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 09 Sep 2007 11:19:42 +0200 Subject: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute References: <1189173455.525144.326300@y42g2000hsy.googlegroups.com> <87k5r2zhd6.fsf@kip.sateh.com> <1189319685.273092.31830@r34g2000hsd.googlegroups.com> Message-ID: <87ejh86vrl.fsf@kip.sateh.com> Miki writes: > > steps.sort(key = lambda s: s.time) > This is why attrgetter in the operator module was invented. > from operator import attrgetter > ... > steps.sort(key=attrgettr("time")) Personally I prefer the anonymous function over attrgettr :) S. From sjmachin at lexicon.net Sat Sep 29 09:01:26 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 29 Sep 2007 06:01:26 -0700 Subject: question about for cycle In-Reply-To: References: Message-ID: <1191070886.287115.239520@19g2000hsx.googlegroups.com> On Sep 29, 8:04 pm, "fdu.xia... at gmail.com" wrote: [snip] > And I have another question. Which is the most efficient way to check if there > are duplicate items in a list ? The items in the list may cannot be hashed, so > set() may not work on the list. The following classic by Tim Peters answers the question "How do I remove duplicate items from a list". http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 It should help -- provided of course that you mean "duplicates" in the sense that two Python objects a and b are duplicates iff a == b. If you mean duplicates in a fuzzier sense e.g. "Mao Zedong" and "Mao Tse-Tung", the problem gets harder ... HTH, John From dteslenko at gmail.com Thu Sep 20 02:31:43 2007 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Thu, 20 Sep 2007 10:31:43 +0400 Subject: os.popen and lengthy operations Message-ID: <91325fec0709192331i700cd172seb9534288f200424@mail.gmail.com> Hello! I'm using os.popen to perform lengthy operation such as building some project from source. It looks like this: def execute_and_save_output( command, out_file, err_file): import os def execute_and_save_output( command, out_file, err_file): (i,o,e) = os.popen3( command ) try: for line in o: out_file.write( line ) for line in e: err_file.write( line ) finally: i.close() o.close() e.close() ... execute_and_save_output( '', out_file, err_file) Problem is that script hangs on operations that take long to execute and have lots of output such as building scripts. From xah at xahlee.org Mon Sep 10 22:26:20 2007 From: xah at xahlee.org (Xah Lee) Date: Mon, 10 Sep 2007 19:26:20 -0700 Subject: printing list containing unicode string In-Reply-To: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> References: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> Message-ID: <1189477580.214510.212420@22g2000hsm.googlegroups.com> This post is about some notes and corrections to a online article regarding unicod and python. -------------- by happenstance i was reading: Unicode HOWTO http://www.amk.ca/python/howto/unicode Here's some problems i see: ? No conspicuous authorship. (however, oddly, it has a conspicuous acknowledgement of names listing.) (This problem is a indirect consequence of communism fanatism ushered by OpenSource movement) (Originally i was just going to write to the author on some corrections.) ? It's very wasteful of space. In most texts, the majority of the code points are less than 127, or less than 255, so a lot of space is occupied by zero bytes. Not true. In Asia, most chars has unicode number above 255. Considered globally, *possibly* today there are more computer files in Chinese than in all latin-alphabet based lang. ? Many Internet standards are defined in terms of textual data, and can't handle content with embedded zero bytes. Not sure what he mean by "can't handle content with embedded zero bytes". Overall i think this sentence is silly, and he's probably thinking in unix/linux. ? Encodings don't have to handle every possible Unicode character, .... This is inane. A encoding, by definition, turns numbers into binary numbers (in our context, it means a encoding handles all unicode chars by definition). What he really meant to say is something like this: "Practically speaking, most computer languages in western society don't need to support unicode with respect to the language's source file" ? UTF-8 has several convenient properties: 1. It can handle any Unicode code point. ... As mentioned before, by definition, any Unicode encoding encodes all unicode char set. The mentioning of above as a "convenient property" is inane. ? 4.UTF-8 is fairly compact; the majority of code points are turned into two bytes, and values less than 128 occupy only a single byte. Note here, that utf-8 is relative compact only if most of your text are latin alphabets. If you are not a occidental men and you write Chinese, utf-8 is comparatively inefficient. (utf-8 as one of the Unicode encoding is probably comparatively inefficient for japanese, korean, Arabic, or any non-latin-alphabet based langs) Also note, the article overly focus on utf-8. Microsoft's Windows NT, is probably the first major operating system that support unicode throughly, and they use utf-16. For Much of America and Europe, which are currently roughly the leader in computing, utf-8 is more efficient in some sense (e.g. at least in disk space requirements). But consider global computing, in particular Chinese & Japanese, utf-16 is overall superior than utf-8. Part of the reason, that utf-8 is favored in this article, has to do with Linux (and unix). The reason unixes in general have choosen utf-8 instead of utf-16, is largely because unix is one motherfucking bag of shit that it is impossible to support utf-16 without scraping a large chuck of unix things. PS I did not read the article in detail, but only roughly to see how Python handle unicode because i was often confused by python's encode/ decode/unicode methods and functions. ... am gonna continue reading that article about Python specific issues... also note, this post is posted thru groups.google.com, and it contains the double angled quotation mark chars. As of 2 weeks ago, it quotation marks seems to be deleted in the process of posting, i.e. unicode name: "LEFT-POINTING DOUBLE ANGLE QUOTATION MARK" and "RIGHT- POINTING DOUBLE ANGLE QUOTATION MARK". Here, i enclose the double- angled quation mark inside a double curly quote: " ". If inside the double curly quote you see spaces, than that means google groups fucked up. References and Further readings: ? Unicode in Perl & Python http://xahlee.org/perl-python/unicode.html ? the Journey of a Foreign Character thru Internet http://xahlee.org/Periodic_dosage_dir/t2/non-ascii_journey.html ? Unicode Characters Example http://xahlee.org/Periodic_dosage_dir/t1/20040505_unicode.html ? Python's unicodedata module http://xahlee.org/perl-python/unicodedata_module.html ? Emacs and Unicode Tips http://xahlee.org/emacs/emacs_n_unicode.html ? Java Tutorial: Unicode in Java http://xahlee.org/java-a-day/unicode_in_java.html ? Character Sets and Encoding in HTML http://xahlee.org/js/html_chars.html Xah xah at xahlee.org ? http://xahlee.org/ From f.guerrieri at gmail.com Mon Sep 10 08:05:37 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 10 Sep 2007 14:05:37 +0200 Subject: less obvious "super" In-Reply-To: <1189424762.591411.99760@d55g2000hsg.googlegroups.com> References: <1189417830.645749.226120@d55g2000hsg.googlegroups.com> <1189424762.591411.99760@d55g2000hsg.googlegroups.com> Message-ID: <79b79e730709100505n246d9539t6c6ee0b3cca2dbfc@mail.gmail.com> On 9/10/07, Nagarajan wrote: > > > > What's the difference b/w: > class A: > and > class A ( object ): > > Thanks. > The first one declares an old-style class. The second one declares a new style class. It's better to use the new-style (always derive from object). See http://www.python.org/doc/newstyle.html for further reading francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Wed Sep 19 11:47:38 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Sep 2007 11:47:38 -0400 Subject: psycopg2 or pygresql? In-Reply-To: <1190214385.994370.167750@r29g2000hsg.googlegroups.com> References: <1190214385.994370.167750@r29g2000hsg.googlegroups.com> Message-ID: exhuma.twn wrote: > Plain and simple. What would you use? > > So far I have written everything with psycopg2. One thing that annoys > me is that I cannot easily access the column names from a query. I > know that this is not part of the DBAPI2 so I cannot expect the model > to suport it. > Yes it is. Execute a SELECT * FROM TABLE WHERE 1=0 and then examine cursor.description. This allows you to introspect on database structure. > I quite like the "mogrify" method of psycopg2 very much. It's very > useful for debugging. > > And before someone says: "Use the DictCursor-factory to access column > names". Yes I can do that. But a dict does not guarantee the same > order of keys as the columns were specified in the query. > See below. > The reason: I wrote a very simple Qt-Widget (inherited from > QTableWidget) that takes a SQL query and displays the results. And I > would like to have the columns ordered the same way as I specified in > the query *with* a header-label. For now I hava a method on the widget > which takes a query, *and* a list of labels. > > I can live with that though. Although it itches me. > > Would pygresql solve my dilemma? Or would you rather say: "Don't use > pygresql!" ;) > Here's a psycopg2-based session: >>> curs >>> curs.execute("SELECT * FROM Person WHERE 1=0") >>> curs.description (('psnid', 23, None, 4, None, None, None), ('psnfirstname', 1043, None, 50, None, None, None), ('psnlastname', 1043, None, 50, None, None, None), ('psndear', 1043, None, 50, None, None, None), ('psntitle', 1043, None, 50, None, None, None), ('psnworkphone', 1043, None, 30, None, None, None), ('psnworkextension', 1043, None, 20, None, None, None), ('psnhomephone', 1043, None, 30, None, None, None), ('psnmobilephone', 1043, None, 30, None, None, None), ('psnfaxnumber', 1043, None, 30, None, None, None), ('psnemailname', 1043, None, 50, None, None, None), ('psnreferredby', 1043, None, 50, None, None, None), ('psnlocid', 23, None, 4, None, None, None), ('psnnotes', 1043, None, -1, None, None, None)) I believe if you use specific column names in your query they will appear in the order given in the query also. I use this technique in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 to print arbitrary query outputs. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From bozonm at vscht.cz Wed Sep 26 16:31:32 2007 From: bozonm at vscht.cz (Michal Bozon) Date: Wed, 26 Sep 2007 22:31:32 +0200 Subject: Tkinter / Tk 8.5 Message-ID: Today has been released a first beta of Tk 8.5, including a Ttk (tile) style engine, which makes possible the native look of widgets on MS platform, without having to install any extension. http://wiki.tcl.tk/11075 http://sourceforge.net/mailarchive/message.php?msg_name=1190813039.46fa5d6f6a06b%40webmail.nist.gov Is there a chance it will be included in 2.5.x, 2.6 or 3.0 ? -m. From vedrandekovic at v-programs.com Tue Sep 18 07:44:32 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Tue, 18 Sep 2007 04:44:32 -0700 Subject: string replace shortcut Message-ID: <1190115872.824161.115420@w3g2000hsg.googlegroups.com> Hello, I am trying to replace some string with list objects: >>> my_text1="function1 function2" >>> from my_module_with_functions_1 import * >>> from my_module_with_functions_2 import * # functions in module " my_module_with_functions_1 ": my_func1 it's value "function1" my_func2 it's value "function2" # functions in module " my_module_with_functions_2 ": my_func100 it's value "bla bla 1" my_func200 it's value "bla bla 2" ........now, we need find and replace functions from module " my_module_with_functions_1 " and replace them with functions from module " my_module_with_functions_2 " with: my_text1.replace(items1,items2) Result must be: >>> print my_text1.replace(items1,items2) bla bla 1 bla bla 2 Regards, Vedran From anomyo2 at gmail.com Tue Sep 11 16:40:40 2007 From: anomyo2 at gmail.com (anton a) Date: Tue, 11 Sep 2007 22:40:40 +0200 Subject: Compiler Python In-Reply-To: <000001c7f4a2$307fa720$917ef560$@com> References: <000001c7f4a2$307fa720$917ef560$@com> Message-ID: <7e72bde20709111340x61d1812ag1070722dee59721f@mail.gmail.com> Hello Someone knows since as I can obtain the information detailed about the compiler of Python? (Table of tokens, lists of productions of the syntactic one , semantic restrictions...) Thanks. From lasses_weil at klapptsowieso.net Thu Sep 13 12:29:41 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 13 Sep 2007 18:29:41 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189666095.727426.135170@o80g2000hse.googlegroups.com> <1189685403.306218.13270@22g2000hsm.googlegroups.com> <13eigagsuk74l55@corp.supernews.com> <46e94623$0$30375$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <46e96575$0$7702$9b4e6d93@newsspool2.arcor-online.net> Eduardo O. Padoan wrote: > On 9/13/07, Wildemar Wildenburger wrote: >> because I'm trained to interpret the underscore as a synonym for one >> space. It's not particularly beautiful, but that is probably a matter of >> habituation. And that exact word is probably the reason why I'd still >> use self or s (explained by a comment, because I can get very dumb if I >> have to). > > Have you worked with code using gettext functions imported as "_"? > When I see a single underscore as a name, i18n comes to mind. > > See? Habituation. Just what I'm saying. :) /W From stef.mientki at gmail.com Sun Sep 23 14:22:12 2007 From: stef.mientki at gmail.com (stef mientki) Date: Sun, 23 Sep 2007 20:22:12 +0200 Subject: building a GUI In-Reply-To: References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> Message-ID: <46F6AED4.2000004@gmail.com> Thomas Dybdahl Ahle wrote: > Den Sun, 23 Sep 2007 17:28:38 +0200 skrev stef mientki: > >> yadin wrote: >> >> >>> if i were up to make a GUI chich are the advantages of choosing python >>> over matlab or java? >>> >>> >> The best is Delphi, >> second is VB, >> > > That sounds mostly like a personal preference :) > > Well I prefer Python ( because of it's OS-independancy and it's open source), but Python is really (still) much worse for GUI designs. Just compare some parameters like: - ease of use - speed of development - support of features - availability of libraries - documentation > I would certainly suggest Python very much for any kind of gui. > I agree to that ;-) cheers, Stef > From david at boddie.org.uk Sun Sep 30 14:15:33 2007 From: david at boddie.org.uk (David Boddie) Date: Sun, 30 Sep 2007 20:15:33 +0200 Subject: How to display a videostream in the PyQt GUI by a efficient way Message-ID: <200709302015.33842.david@boddie.org.uk> On Sun Sep 30 09:10:40 CEST 2007, Kivilaya wrote: > I read the method in the given link and learn a lot from it. I'll > try to display the data inside a QWidget directly instead of the > current way. But I still have a question, is there any way to make the > displaying of RGB data in a QWidget more quickly. You can set certain flags to ensure that the widget isn't being updated or painted on too often. See the WA_OpaquePaintEvent and WA_NoSystemBackground flags: http://www.riverbankcomputing.com/Docs/PyQt4/html/qt.html#WidgetAttribute-enum The problem may be related to the conversion process rather than the time it takes to display the image. You mentioned that you were obtaining the images as PIL Image objects, but these need to be converted to QImage or QPixmap objects, so the raw data from the camera is being converted at least twice before it reaches the screen! > In fact, my work is to make a gui for displaying my > partners'experimental results to our teacher, the source video is no > need to be encoded to mpeg or h264 format, so I get the video from > camera in the raw format and display them without encodeing or > decoding process. Which operating system is this on? (I'm guessing that it's Windows because you mentioned the videocapture module.) > As my partners will do some experiments on the raw data, maybe add > a mark to label some area in the current frame, or change some part of > it, I get every frame as a picture before they process the picture > data, and then display the picture after their process. So, do you intend to process the video and store it in a file, or do you want to make these changes on a live video stream? > But displaying the pictures one by one in my current way is so slow, > I'm afraid that time spend on it is too long and the displaying of > results will be discontinuous. So I think maybe there is another way > to show these pictures. Is there another way of getting the data from the camera? Perhaps the author of videocapture has some ideas that can help you speed up the conversion and rendering process. Maybe the Device.getBuffer() function will provide data that can be passed directly to QPixmap.loadFromData(). David From rowen at cesmail.net Wed Sep 12 15:08:33 2007 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 12 Sep 2007 12:08:33 -0700 Subject: An ordered dictionary for the Python library? References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <13efnmi4n959a59@corp.supernews.com> Message-ID: In article <13efnmi4n959a59 at corp.supernews.com>, Steven D'Aprano wrote: > On Wed, 12 Sep 2007 07:33:45 +0000, Mark Summerfield wrote: > > > I feel that Python lacks one useful data structure: an ordered > > dictionary. > > > > I find such data structures v. useful in C++. > [snip] > > > Personally, I've never missed an ordered dict. What do people use them > for? > > In fact, I'm not sure what people mean by ordered dicts. I assume they > mean the keys are ordered, not the values. But ordered by what? Insertion > order? Modification order? Alphabetical order? Opinions vary, but I think of it this way: - A sorted dict keeps its keys sorted. This has an obvious alternative just sort the keys later (though I can imagine cases where it would be nicer not to). - An ordered dict remembers the order of insertion. This is useful when you want to retain the order of insertion yet you also want fast lookup of individual items. Unlike a sorted dict, there is no trivial alternative (though you can argue about "trivial") and I really wish there was. There are several free versions available. -- Russell From steve at REMOVE-THIS-cybersource.com.au Fri Sep 7 21:31:46 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Sep 2007 01:31:46 -0000 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> <7x3axq7a8a.fsf@ruckus.brouhaha.com> Message-ID: <13e3us269f59s7a@corp.supernews.com> On Fri, 07 Sep 2007 08:42:45 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> def unique_id(): >> n = 1234567890 >> while True: >> yield n >> n += 1 > > unique_id = itertools.count(1234567890) Sweet! I really must make itertools second-nature. I always forget it. >> which is easy enough, but I thought I'd check if there was an existing >> solution in the standard library that I missed. Also, for other >> applications, I might want them to be rather less predictable. > > def unique_id(): > return os.urandom(10).encode('hex') Any time I see something using a random number to generate IDs, I worry about collisions. Am I being paranoid? (But even paranoids write code with bugs...) Here's something which is a little less predictable than a straight counter: def unpredictable_counter(n=12345678): while True: n += random.randint(1, 68) yield n def more_unpredictable_counter(n=1234567): uc = unpredictable_counter(n) pool = [] while True: if not pool: pool = [None]*99 for i in range(99): pool[i] = uc.next() random.shuffle(pool) yield pool.pop() -- Steven. From bdesth.quelquechose at free.quelquepart.fr Thu Sep 20 04:00:41 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 20 Sep 2007 10:00:41 +0200 Subject: Odd files; just left behind? In-Reply-To: <46F191DF.7000908@jessikat.plus.net> References: <878x725ts7.fsf@pobox.com> <46F191DF.7000908@jessikat.plus.net> Message-ID: <46f2bd9b$0$20143$426a74cc@news.free.fr> Robin Becker a ?crit : > John J. Lee wrote: > >> Robin Becker writes: >> >>> I see a folder .python-eggs in my home directory on one of our servers >>> with various .so files >>> >>> ~/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so >>> >>> >>> are these just left behind from some install process? >> >> >> Ah, it's about the resource extraction feature of setuptools. It's >> possible for zipped eggs to contain resources that have to be >> extracted to the filesystem. It puts them in the directory you saw >> (or somewhere else -- see the docstring in my other reply). >> >> http://peak.telecommunity.com/DevCenter/PkgResources#resource-extraction >> http://peak.telecommunity.com/DevCenter/setuptools#automatic-resource-extraction >> > > ..... > Thanks John, but why not clean up? > Does it needs to be "cleaned up" ? .so files (shared libs) *need* to be extracted from the egg to be usable. Where they are extracted is IIRC configurable... From ldo at geek-central.gen.new_zealand Mon Sep 24 03:50:02 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 24 Sep 2007 19:50:02 +1200 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> Message-ID: In message , Bryan Olson wrote: > The keyword "lambda" sucks. ... > > Alonzo Church's calculus used the *symbol*. The keyword was popularized by LISP, and hence adopted by most other languages to copy the concept. In my view, it's no worse than using "=" for assignment instead of equality. > "function" would be a much better keyword. As used that way in JavaScript. From danielk at featherbrain.net Tue Sep 11 10:07:27 2007 From: danielk at featherbrain.net (Daniel Klein) Date: Tue, 11 Sep 2007 14:07:27 GMT Subject: pipes References: <1189480540.812171.285820@r34g2000hsd.googlegroups.com> Message-ID: On Mon, 10 Sep 2007 20:15:40 -0700, yagyala wrote: >Hi. I'm rtying to use pipes to communicate between a python GUI and a >spawned C++ program. I prefer not to use forking because the app may >be run on windows, where forking isn't supported. Roughly what I'm >doing is: > >(r,w) = os.pipe() >spawnl(P_WAIT, 'tool.exe', ' ', message, str(w)) >close(w) >print os.read(r, 1000) > >In c++ , >... >int main(int argc, char** argv) >{ > >} The 'subprocess' module provides an easier interface imo, eg: process = subprocess.Popen('tool.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=true) (self.outstream, self.instream) = (process.stdout, process.stdin) Daniel Klein From imageguy1206 at gmail.com Fri Sep 7 07:35:34 2007 From: imageguy1206 at gmail.com (imageguy) Date: Fri, 07 Sep 2007 04:35:34 -0700 Subject: py2exe - change name of exe created Message-ID: <1189164934.705547.156670@r34g2000hsd.googlegroups.com> I have a setup script like this; setup(windows = [{"script":"myprogram.py", "icon_resources":[(0,"nabbitt.ico")], "other_resources": [(24,1,manifest)]} ], name = "Nabbitt ver 0.1", data_files = [("",rootdata)], zipfile = None, options = {"py2exe": { "compressed" : 1, "dll_excludes": ["w9xpopen.exe"], #should also exclude MSVCR71.dll "bundle_files": 3 # 1=Single .exe, 2=.exe with pythonXX.dll } }, ) From daniel.j.larsson at gmail.com Wed Sep 5 13:31:48 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Wed, 5 Sep 2007 19:31:48 +0200 Subject: Soemthing wrong w/ urllib module or something. In-Reply-To: References: <46DBC5CB.3040007@timgolden.me.uk> <46DC0BA6.50606@timgolden.me.uk> Message-ID: <2bfa72fa0709051031o3cb4230eke7b285dca1a77c26@mail.gmail.com> Are you using http proxying when you browse to the server? Have you tried to do $ curl http://DOMAINHERE/ If that works, connecting with a plain socket should work too. Otherwise, I believe urllib has support for a proxying server, check the docs. On 9/5/07, Lamonte Harris wrote: > > Anyone got an answer for this? > > On 9/3/07, Lamonte Harris wrote: > > > > Yeah I can browse it like normal. For some reason though my News System > > that worked like a charm just stopped working also. Is there any > > alternatives that I could try to use to POST to a PHP script? > > > > On 9/3/07, Tim Golden wrote: > > > > > > [Tim Golden] > > > >> To do the obvious, can you open a socket connection > > > >> to the domain you're using? > > > >> > > > >> > > > >> from socket import socket > > > >> socket ().connect (("DOMAINHERE", 80)) > > > >> > > > >> > > > >> > > > >> or does it give you the same error? > > > > > > [Lamonte Harris] > > > > Yeah I basically got the same error. > > > > > > > > Traceback (most recent call last): > > > > File "", line 1, in > > > > File "", line 1, in connect > > > > socket.error: (10053, 'Software caused connection abort') > > > > > > OK, then *something's* blocking access to that host (at least) > > > on port 80. Can you browse the web normally from this machine? > > > In particular, can you browse to that site ("DOMAINHERE")? > > > > > > TJG > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mauro.tiz at gmail.com Thu Sep 27 09:48:15 2007 From: mauro.tiz at gmail.com (mauro) Date: Thu, 27 Sep 2007 06:48:15 -0700 Subject: PyObject_CallObject: difference between functions and class methods Message-ID: <1190900895.635795.262350@y42g2000hsy.googlegroups.com> Hi all! I am trying to call within a C extension a Python function provided as an argument by the user with: PyObject_Call(). The C extension should work also if the user supplies a class method, but in this case I am getting an error. Do I need to explicitly pass 'self' as an argument to PyObject_Call()? If so, how can I do that? Now, I am using: if ((tmp_args = PyTuple_New(1)) == NULL) PyErr_SetString( PyExc_ReferenceError, "attempt to access a null- pointer" ); PyTuple_SetItem(tmp_args, 0, paramlist); to create the tuple required by PyObject_Call(), but I have no idea on how to add a reference to 'self'. Here is what I would like to obtain: ## import mymodule def myfunc(x): # Do something return [z] class MyClass: def mymethod(self, x): # Do something return z def runme(self): mymodule.main(myfunc) # This will work mymodule.main(self.mymethod) # This will not work (Segmentation fault) x = MyClass() x.runme() ## Thanks in advance. Mauro From byte8bits at gmail.com Wed Sep 26 11:13:15 2007 From: byte8bits at gmail.com (brad) Date: Wed, 26 Sep 2007 11:13:15 -0400 Subject: Script to extract text from PDF files In-Reply-To: References: Message-ID: David Boddie wrote: > There's a little information on that online: > http://www.glyphandcog.com/textext.html Thanks, I'll read that. > Just because inserting and encoding is well documented doesn't mean that the > reverse processes are easy. :-/ Boy, that's an understatement... most of the PDF tools (in fact almost all) I come across write PDF docs... they output things to PDF. It's like anyone can generate PDF files... it's dead simple, but extracting text out of them in an accurate, reliable manner is much more difficult. > Maybe you should look at the source code for pdftotext, if that's an option. I'm not sure it's opensource/free software with source available, but I'll look into that. > Can I suggest that you approach one or more authors of the existing Python > PDF solutions and work with them on this? There are at least four PDF parsers > written in Python out there. I appreciate that suggestion, but again, none of the current solutions I've seen and tried, extract text from pdf documents. I'd love to be proven wrong on this point. So if one of those four current PDF solutions you mention do that, please let me know. Thanks, Brad From joel.hedlund at gmail.com Tue Sep 25 18:11:13 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 26 Sep 2007 00:11:13 +0200 Subject: What is a good way of having several versions of a python module installed in parallell? In-Reply-To: References: <5ls95aF9pq3gU1@mid.uni-berlin.de> Message-ID: First of all, thanks for all the input - it's appreciated. > Otherwise, three words: > > test driven development Do you also do this for all the little stuff, the small hacks you just whip together to get a particular task done? My impression is that doing proper unittests adds a lot of time to development, and I'm thinking that this may be a low return investment for the small programs. I try to aim for reusability and generalizability also in my smaller hacks mainly as a safeguard. My reasoning here is that if I mess up somehow, sooner or later I'll notice, and then I have a chance of making realistic damage assessments. But even so, I must admit that I tend to do quite little testing for these small projects... Maybe I should be rethinking this? Cheers! /Joel From Caseyweb at gmail.com Thu Sep 27 13:14:10 2007 From: Caseyweb at gmail.com (Casey) Date: Thu, 27 Sep 2007 17:14:10 -0000 Subject: getopt with negative numbers? Message-ID: <1190913250.198794.269530@k79g2000hse.googlegroups.com> Is there an easy way to use getopt and still allow negative numbers as args? I can easily write a workaround (pre-process the tail end of the arguments, stripping off any non-options including negative numbers into a separate sequence and ignore the (now empty) args list returned by getopt, but it would seem this is such a common requirement that there would be an option to treat a negative value as an argument. Note that this is only a problem if the first non-option is a negative value, since getopt stops processing options as soon as it identifies the first argument value. Alternatively, does optparse handle this? I haven't used optparse (I know it is more powerful and OO, but you tend to stick with what you know, especially when it is part of my normal python programming template), but if it handles negative numbers I'm willing to learn it. From gagsl-py2 at yahoo.com.ar Mon Sep 17 04:17:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Sep 2007 01:17:31 -0700 Subject: Try this In-Reply-To: <1190008502.986300.286280@22g2000hsm.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> <1190008502.986300.286280@22g2000hsm.googlegroups.com> Message-ID: <1190017051.877316.72330@r29g2000hsg.googlegroups.com> On 17 sep, 02:55, "mensana... at aol.com" wrote: > On Sep 16, 9:27?pm, "Gabriel Genellina" > wrote: > > > En Sun, 16 Sep 2007 21:58:09 -0300, mensana... at aol.com > > escribi : > > > >> I'm eagerly awaiting publication of your professional specification > > >> for correctly detecting the encoding of an arbitrary stream of > > >> bytes > > > > The very presence of an algorithm to detect encoding is a bug. > > > Files with they .txt extension should always be treated as ANSI > > > even if they contain binary data. > > > Why ANSI? > > Because that's the absence of encoding? Are you kidding? > > Because it's convenient to *you*? > > No, it's ANSI unless told otherwise. Oh, yes, it's a joke surely. (Anyway, *which* ANSI standard? AFAIK, the Windows character set has never been standardized by ANSI). > > What about the rest of the world that don't speak > > English or even worse, don't use the Latin alpabet? > > When the rest of the world creates the next > generation of computers, THEY can chosse the > defaults. No comments. > > What do you mean by "binary data"? > > 8-bit, ASCII is only 7-bit. Being "binary" as opposed to "text" has nothing to do with the number of bits. "?Ol?!" is text, and contains characters outside the ASCII set. A signal with range 0-63 can be encoded into 6 bits, but it's binary data, not text. > > Notepad is not interpreting the file as > > "binary", it's text, > > And will treat non-ASCII data as if it were ASCII. I think you were complaining about the opposite situation. > > but interpreted using the wrong encoding. > > So that's not a serious bug? To decide that a file > is Unicode despite the absence of the appropriate > markers? Which are "the appropiate markers"? A BOM is not always required, and Notepad supported Unicode even before the BOM was invented. Please redirect your bug reports to bugs at microsoft.com > > As every character goes into the same code block the heuristics concludes > > that the text is some Estern language encoded in UTF16. > > But...but...Notepad doesn't have a UTF16 option. What it calls "Unicode" is in fact UTF16, or UCS2 on some previous Windows versions. > > This is the "Well you are speed" phrase interpreted as UTF16: > > u'\u6557\u6c6c\u7920\u756f\u6120\u6572\u7320\u6570\u6465' > > How can you tell from that that it's UTF16? If there's > something stored in addition to those 18 bytes, you're > being misleading. *I* can tell it's not, but Notepad (which presumibly calls IsTextUnicode) cannot, and I can't blame it given a so small sample of less than 20 bytes. > > > Notepad should never be > > > allowed to try to decide what the encoding is if the the open > > > dialog has the encoding set to ANSI. > > > I'm using notepad.exe version 5.1.2600.2180 (XP SP2 fully updated) and > > that's exactly what happens. I have to explicitely select Unicode in order > > to see those Han characters. > > So which is worse, you having to tell it that it's > Unicode or Notepad deciding on its own that a file > is Unicode when it isn't. I don't know, and I don't care, and I don't use Notepad. -- Gabriel Genellina From carsten at uniqsys.com Wed Sep 19 10:58:56 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 19 Sep 2007 10:58:56 -0400 Subject: Find the ID, but how to select/copy the whole string by ID? In-Reply-To: <79b79e730709190741i2deb95c8m2982b3201a3fc4be@mail.gmail.com> References: <1190209195.493784.133340@q3g2000prf.googlegroups.com> <79b79e730709190741i2deb95c8m2982b3201a3fc4be@mail.gmail.com> Message-ID: <1190213936.3371.34.camel@dot.uniqsys.com> On Wed, 2007-09-19 at 16:41 +0200, Francesco Guerrieri wrote: > On 9/19/07, Leon wrote: > > stringID = str(raw_input('Enter the string ID : ')) > > file = open('strings.txt') > > sourcefile = file.read() > > file.close() > > sourcefile.find (stringID) > > > > but how can I select and copy the specific string from to > > with id I input? > > If the file you are parsing is in xml, there are many parser out there > which can help you (this is discussed very often on this list, even > today) . > > If the format is very simple and you really want to do it by hand, you > could do something like: > > stringID = raw_input('Enter the string ID:') > for line in open('strings.txt'): > if line.find(stringID) > -1: > print 'Found!' Using find() for XML parsing is like using a machine gun to pound a nail into a wall. It is absolutely the wrong tool for the job. If the input file looks something like this: blah spam , then looking for id 12 is going to match on the wrong ID. Besides, that code only tells you where something that looks like the ID you're looking for is in the file. There is no guarantee that the match actually occurs inside an ID attribute. It also doesn't help in retrieving the text contents of the tag that has this ID. If your input is an XML file, using an actual XML parser is the only correct solution. -- Carsten Haese http://informixdb.sourceforge.net From http Tue Sep 4 02:42:56 2007 From: http (Paul Rubin) Date: 03 Sep 2007 23:42:56 -0700 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> Message-ID: <7xabs39bin.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > > No the idea is that once there's enough entropy in the pool to make > > one encryption key (say 128 bits), the output of /dev/urandom is > > computationally indistinguishable from random output no matter how > > much data you read from it. > > If you were talking about /dev/random I would agree. But this is what > the man page on my system says about /dev/urandom. ... > the returned values are theoretically vulnerable to a > cryptographic attack on the algorithms used by the driver. Right. The idea is that those attacks don't exist and therefore the output is computationally indistinguishable from random. Of course whether the idea is correct, an unproven conjecture, but it looks pretty good; certainly finding any problem with the specific algorithms in urandom would be a significant research discovery and not likely to affect the application being discussed. Finding a general attack that couldn't be fixed with some simple tweak would be a major crypto breakthrough that would probably reshape a lot of complexity theory. This is unlike the situation with Mersenne Twister, which was not designed for indistinguishability against an opponent who knew what to look for. In short, using /dev/random is fairly silly once you know there's enough entropy in the randomness pool to make a good key. If /dev/urandom's algorithms are broken then whatever you're doing with the /dev/random output is probably also broken. From bbxx789_05ss at yahoo.com Sat Sep 15 07:15:23 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 15 Sep 2007 04:15:23 -0700 Subject: Just bought Python in a Nutshell In-Reply-To: References: <1189784843.896396.108960@g4g2000hsf.googlegroups.com> <59f9c5160709141412q1098a4cbi989b6eed2f2cc899@mail.gmail.com> <46EB5B10.2020100@gmail.com> <96f089100709150107t10275d23p6b8cb7be6e748b7f@mail.gmail.com> Message-ID: <1189854923.148481.294830@n39g2000hsh.googlegroups.com> Used copies of computer books for out of date editions are always cheap. "Python in a Nutshell (2nd ed)" is a reference book with a frustratingly poor index--go figure. It also contains errors not posted in the errata. From bh at izb.knu.ac.kr Sun Sep 30 14:46:55 2007 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Mon, 01 Oct 2007 03:46:55 +0900 Subject: Can you please give me some advice? In-Reply-To: <1191173228.756531.225860@o80g2000hse.googlegroups.com> References: <13fuv0gh7342r27@corp.supernews.com> <1191173228.756531.225860@o80g2000hse.googlegroups.com> Message-ID: <1191178015.1510.21.camel@viola.izb.knu.ac.kr> On Sun, 2007-09-30 at 17:27 +0000, cmpython at gmail.com wrote: > I know nothing of Ruby, but just the fact that in Ruby the Hello World > program is > > puts 'Hello, World!' > > whereas the Python Hello World program is > > print 'Hello, World!' > > suggests to me that Python is more intuitive because the word "print" > has a meaning in English that makes sense given what you want to do, > but "puts" just doesn't. And, as someone who has been learning Python > from almost no knowledge of programming, I've found it is not too bad > in trying to keep as reasonably close to a natural language like > English > as possible. > > I also think the mandatory indenting of Python is helpful in forcing > new programmers to be neat and see code blocks quickly. Plus I doubt > the Ruby community has such a large group of helpful people and > libraries > and such (but I could be wrong about that, just assuming it based on > the > fact that Python has been around longer). > > On the other hand, perhaps because Ruby is newer it has been able to > freshly start with advantages learned from the difficulties of other > languages. Byung-Hee Hwang ought to go the Ruby group and see what > they are saying. > > As far as English goes, Byung-Hee, you have to admit English grammar > is easy (though spelling is not so easy). That anyone can speak and > write Chinese is impressive to me, as the language looks completely > impossible! Good luck! > I read above your comments all. It will be good reason for my decision must be Python. Anyway, your guidance has been useful and is greatly appreciated. Okay, I will study English very hardly, as well. Thanks, again! Byung-Hee From kf9150 at gmail.com Sat Sep 29 02:08:19 2007 From: kf9150 at gmail.com (kf9150 at gmail.com) Date: Sat, 29 Sep 2007 06:08:19 -0000 Subject: your opinion on book "Foundations of Python Network Programming"? In-Reply-To: <1191017421.527084.104240@n39g2000hsh.googlegroups.com> References: <1191016773.834049.8940@19g2000hsx.googlegroups.com> <1191017421.527084.104240@n39g2000hsh.googlegroups.com> Message-ID: <1191046099.184895.139470@r29g2000hsg.googlegroups.com> On Sep 28, 12:10 pm, TheFlyingDutchman wrote: > I have not read this book but just wanted to say, in case you don't > already know, they have Chapter 13 on FTP available as a free download > at the publisher's web site: > > http://www.apress.com/book/view/1590593715 thanks for the link, i just downloaded the chapter. From bjourne at gmail.com Mon Sep 17 03:37:53 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 17 Sep 2007 09:37:53 +0200 Subject: Try this In-Reply-To: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> Message-ID: <740c3aec0709170037m47a64dcaub008b83c6788b171@mail.gmail.com> On 9/16/07, GeorgeRXZ wrote: > Well you are speed That's an awesome party trick! But before I mail this to everyone at the office, must have a better sentence. Well you are speed is to gibberish. Something microsoft+evil... hm.. -- mvh Bj?rn From horpner at yahoo.com Tue Sep 18 08:17:29 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 18 Sep 2007 12:17:29 GMT Subject: can Python be useful as functional? References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> <46ef8895$0$21882$426a34cc@news.free.fr> <1190106829.680544.159250@g4g2000hsf.googlegroups.com> Message-ID: On 2007-09-18, Kay Schluehr wrote: > On 18 Sep., 10:13, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Lorenzo Stella a ?crit : >> >> > Hi all, >> > I haven't experienced functional programming very much, but now I'm >> > trying to learn Haskell and I've learned that: 1) in functional >> > programming LISTS are fundmental; >> >> Not exactly. They are used quite a lot, yes, but that's also >> the case in other paradigms. What's important in functional >> programming is *functions*. > > Functional lists are not quite the same. They are actually > recursive datastructes. In Python you would model them as > nested tuples: > > t = (a, (b, (c, ...(d, None))))) Tuples won't work for cyclic data, though. -- Neil Cerutti From gh at gregor-horvath.com Mon Sep 3 07:40:49 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Mon, 03 Sep 2007 13:40:49 +0200 Subject: advice about `correct' use of decorator In-Reply-To: References: Message-ID: <47ebd$46dbf2e2$547078de$8282@news.chello.at> Gerardo Herzig schrieb: > > @is_logued_in > def change_pass(): > bla > bla > > And so on for all the other functions who needs that the user is still > loged in. > > where obviosly the is_logued_in() function will determine if the dude is > still loged in, and THEN execute change_pass(). If the dude is not loged > in, change_pass() is NOT executed at all. Instead, it will be redirected > to the `login' screen. > > Something in my mind tells me that this is not the pythonic way...But i > like the idea, so please tell me that im in the right way :) > That's how turbogears does it. See: http://docs.turbogears.org/1.0/UsingIdentity?highlight=%28identity%29 Greg From Scott.Daniels at Acm.Org Sat Sep 22 10:39:17 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 22 Sep 2007 07:39:17 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <13f8unjjeqs5p97@corp.supernews.com> Message-ID: <13faa66cb1phre1@corp.supernews.com> Ron Adam wrote: > > > Scott David Daniels wrote: >> Cristian wrote: >>> On Sep 21, 3:44 pm, Ron Adam wrote: >>> >>>> I think key may be to discuss names and name binding with your friend. >> >> Here's an idea: >> >> import math >> >> def sin_integral(start, finish, dx): ... >> def cos_integral(start, finish, dx): ... >> generalize and separate the integration technique from the >> function it integrates. > > How about this? > It's based on the apple basic program example in How to Enjoy Calculus. > Ron > > import math > def integrate(fn, x1, x2, n=100):... > def fn(x): ... > print "Area of fn:", integrate(fn, 0, 2) > print "Area of cos fn:", integrate(math.cos, 1, 2) The point was a pedagogic suggestion, i.e. "Try taking your friend along this path." I wasn't trying to do a particularly good job integrating, simply trying to show how you could motivate first-class functions by showing a "useful" and "fun" (at least to an engineer) function that cries out for higher order functions. In my experience engineers often want a "reason its useful" before engaging with an idea. I'll bet that after a few such experiences he'll see how passing around functions and (later) making functions from from functions is a great tool to have in his toolbox. Once he sees that, there will be no problem. -Scott David Daniels Scott.Daniels at Acm.Org From m.n.summerfield at googlemail.com Fri Sep 14 12:43:17 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Fri, 14 Sep 2007 16:43:17 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> <1189753968.917636.310120@19g2000hsx.googlegroups.com> <1189767415.814718.312870@k79g2000hse.googlegroups.com> <1189778191.529829.293320@19g2000hsx.googlegroups.com> Message-ID: <1189788197.234522.197750@22g2000hsm.googlegroups.com> On 14 Sep, 15:35, Antoon Pardon wrote: [snip] > I wish you all the luck you can get. Maybe if you succeed I'll change > my mind about writing a PEP myself. > > However I think your chances will increase if you write your module > and have it available in the cheese shop. If people start using your > module regularly, your chances of it being included in the standard > library will increase greatly. I've taken your advice and put it on PyPI. PyPI isn't as easy to use as CPAN, and the classifiers don't include "algorithms" or "data structures" which I find surprising. From laurent.pointal at limsi.fr Tue Sep 11 08:44:18 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 11 Sep 2007 14:44:18 +0200 Subject: memcpy In-Reply-To: <1189512598.410810.224340@y42g2000hsy.googlegroups.com> References: <1189449530.171049.323230@22g2000hsm.googlegroups.com> <5klnsbF3vfqqU10@mid.uni-berlin.de> <1189512598.410810.224340@y42g2000hsy.googlegroups.com> Message-ID: Tim a ?crit : > Can I initialize something in Python that I can get access to it's > pointer? No, there is no pointer in Python semantic (they exist behind the scene in C-Python). > How about: > > self.data = > TOTAL_OUTPUT_PARMETERS*[TOTAL_PARAMETER_ENTRIES*[c_float()] > > or > > self.data = TOTAL_OUTPUT_PARMETERS*[c_char_p("temp")] > > or > > self.data = [TOTAL_OUTPUT_PARMETERS*1.0]*TOTAL_PARAMETER_ENTRIES > > I need to be able to copy the contents of a pointer to shared memory > into an array of floats so I can index into that array and see my > data. I have a pointer to shared meory but I don't know how to access > it. See module ctypes (14.14 in library reference manual). A+ Laurent. From gagsl-py2 at yahoo.com.ar Tue Sep 4 14:46:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Sep 2007 15:46:37 -0300 Subject: Noob: What is a slot? Me trying to understand another's code References: Message-ID: En Tue, 04 Sep 2007 15:03:16 -0300, Carnell, James E escribi?: > MY QUESTION: > What is a slot? In class Object below the __init__ has a slot. Note: > The slot makes use of a data object called 'percept' that is used in the > TableDrivenAgent(Agent) at the bottom of this post. I am guessing this > is a type of Finite State Machine (I haven't bought the book yet so I am > guessing). The authors appear to be using the term in a very general sense - meaning "something that has to be filled in". That is, you (the programmer) is supposed to "fill" the slot with meaningful code or data. > [...] You subclass Object to get the objects you want. Each object can > have a .__name__ slot (used for output only). > [...] An Agent is a subclass of Object with one required slot, > .program, which should hold a function that takes one argument, the > percept, and returns an action. Note that 'program' is a slot, not a > method. Here they're trying to bind a simple function (not a method) to a name. I don't see the point in forcing things that way, maybe the authors have good reasons. But I'd use a staticmethod instead, perhaps. Note: The C Python source code does use "slots", fields in a structure holding function pointers. For example, filling the nb_add slot in a type object, one can evaluate a+b for instances of that type. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Sep 6 11:32:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Sep 2007 08:32:14 -0700 Subject: Getting original working directory In-Reply-To: References: Message-ID: <1189092734.750184.317490@y42g2000hsy.googlegroups.com> On 6 sep, 12:19, rave247 rave247 wrote: > I' am unable to solve this problem. I've got python program, it is installed in standard location. I run this program from some location X (note that I just type relative "myscript", leaving operating system to look up script itself using PATH variable) and this program somewhere in the code calls os.chdir() to change it is current working directory and I would need in python code to get the *original* directory location *after* os.chdir() is performed. This means the location X from which script was performed - it is the location I am in after script is finished. Use os.getcwd() http://docs.python.org/lib/os-file-dir.html -- Gabriel Genellina From aleax at mac.com Mon Sep 3 23:44:30 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 3 Sep 2007 20:44:30 -0700 Subject: Can you use -getattr- to get a function in the current module? References: Message-ID: <1i3vtib.1y4lrkw6rojnvN%aleax@mac.com> Sergio Correia wrote: > This works: > > # Module spam.py > > import eggs > > print getattr(eggs, 'omelet')(100) > > That is, I just call the function omelet inside the module eggs and > evaulate it with the argument 100. > > But what if the function 'omelet' is in the module where I do the > getattr (that is, in spam.py). If I do any of this > > print getattr(spam, 'omelet')(100) > print getattr('','omelet')(100) > print getattr('omelet')(100) > > It wont work. Any ideas? globals() returns a dict of all globals defined so far, so, _after_ 'def omelet ...' has executed, globals()['omelet'](100) should be OK. Alex From bdesth.quelquechose at free.quelquepart.fr Mon Sep 17 18:41:16 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 00:41:16 +0200 Subject: What's with "long running processes" ? In-Reply-To: <1190137468.694220.126180@d55g2000hsg.googlegroups.com> References: <1190137468.694220.126180@d55g2000hsg.googlegroups.com> Message-ID: <46f02389$0$32214$426a74cc@news.free.fr> walterbyrd a ?crit : > I understand that Python has them, but PHP doesn't. Really ? > I think that is because mod_php is built into apache, but mod_python > is not usually in apache. Language etc aside, what the difference between mod_php and mod_python (or mod_whatever) from apache's POV ? > If mod_python was built into apache, would > python still have long running processes (LRP)? mod_php is not more 'built into' apache than mod_python. Both are extension modules for apache. FWIW, when apache is configured to use mod_python, it starts a first python interpreter process at startup, then some more python "sub-interpreters" when needed, according to your configuration. > Do LRPs have to do with a Python interpreter running all the time? Or > is it something else? The notion of "long running process" is nothing Python-specific. The most basic way to deliver dynamic content from a web server like apache is to use CGI - which means that on each http request, the web server starts a new (Python | Perl | PHP | Whatever) process. A more elaborate solution is to have another process running independently, and some way for both processes (web server and application) to communicate. This was is usually known as a "long running process". > I also understand that LRPs are the reason that shared hosting is less > common, and more expensive for python than php. Yes and no. You can use Python with apache without a LRP - either with CGI or mod_python - but the first solution is very inefficient, and the second is not really appropriate for shared hosting given how mod_python works. Also, while LRPs have a big advantage (you don't need to rebuild the whole world for each and every request), they have a couple drawbacks when it comes to shared hosting. The first one is that your host must provide some way to manage (run/stop/restart/monitor) the process. The second is that, while CGI scripts are (more or less) under control of the web server (IOW : they won't hang out forever), it's not true for LRPs. Which means that a program error (ie: an endless loop allocating memory on each iteration...) can potentially bring the while server down. Not that there are no ways to limit the risks and consequences, but this requires much more work for the host (and believe me, shared hosting administration is not simple...). > The LRP have a major > effect on how many users can packed onto a single server. Not necessarily. From a purely technical POV, they are usually less wasteful wrt/ resources than CGI or mod_php. > As to LRPs: does it matter if you're using mod_python, fastcgi, wsgi, > scgi, cgi, or whatever? > > Obviously, I am a little foggy about LRPs, can somebody help me out? You can help yourself out, by installing apache on your own machine and learning the different ways to deploy web applications with it. While you won't have the same constraints as a shared hosting admin, you'll at least get a better understanding of the whole damn thing. From sjmachin at lexicon.net Sat Sep 15 07:22:49 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Sep 2007 04:22:49 -0700 Subject: regexp search on infinite string? In-Reply-To: <1189838192.090251.292620@g4g2000hsf.googlegroups.com> References: <1189802940.518794.129130@r29g2000hsg.googlegroups.com> <1189838192.090251.292620@g4g2000hsf.googlegroups.com> Message-ID: <1189855369.578539.14600@50g2000hsm.googlegroups.com> On Sep 15, 4:36 pm, Paddy wrote: > On Sep 15, 2:57 am, James Stroud wrote: > > > > > Paddy wrote: > > > Lets say i have a generator running that generates successive > > > characters of a 'string' > > >>From what I know, if I want to do a regexp search for a pattern of > > > characters then I would have to 'freeze' the generator and pass the > > > characters so far to re.search. > > > It is expensive to create successive characters, but caching could be > > > used for past characters. is it possible to wrap the generator in a > > > class, possibly inheriting from string, that would allow the regexp > > > searching of the string but without terminating the generator? In > > > other words duck typing for the usual string object needed by > > > re.search? > > > > - Paddy. > > > re.search & re.compile checks for str or unicode types explicitly, so > > you need to turn your data into one of those before using the module. Aaaarbejaysus. Since when? >>> import array >>> ba = array.array('c', 'A hollow voice says "Plugh".') >>> import re >>> mobj = re.search('voi', ba) >>> mobj <_sre.SRE_Match object at 0x00B99598> >>> mobj.span() (9, 12) >>> > > > buffer = [] > > while True: > > buffer.append(mygerator.next()) > > m = re.search(pattern, "".join(buffer)) > > if m: > > process(m) > > buffer = [] > > > James > > Thanks James. So: buffer = array.array('c') and flick the "".join() etc etc HTH, John From luismgz at gmail.com Mon Sep 3 01:10:39 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 03 Sep 2007 05:10:39 -0000 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <1188785779.956824.143860@w3g2000hsg.googlegroups.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1188785779.956824.143860@w3g2000hsg.googlegroups.com> Message-ID: <1188796239.144793.239370@r29g2000hsg.googlegroups.com> On Sep 2, 11:16 pm, llothar wrote: > On 3 Sep., 07:38, "Eduardo O. Padoan" > wrote: > > > > No.http://www.artima.com/weblogs/viewpost.jsp?thread=211430 > > > Ops, I meant:http://www.artima.com/forums/threaded.jsp?forum=106&thread=211200 > > Thanks. I whish there would be a project for rewritting the C > interpreter > to make it better and more useable for threading use. > > But the CPU infrastructure is also not perfect enough so maybe it's > good to > wait with this a few more years until Intel and AMD know what they are > doing. I read somewhere that PYPY won't have the interpreter lock (I may be wrong though). Check it out: http://codespeak.net/pypy From duncan.booth at invalid.invalid Sat Sep 29 10:23:06 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Sep 2007 14:23:06 GMT Subject: sorteddict [was a PEP proposal, but isn't anymore!] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190829592.800804.242260@50g2000hsm.googlegroups.com> <1190881576.186259.313720@57g2000hsv.googlegroups.com> <1190897445.179828.291720@y42g2000hsy.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2007-09-27, gatti at dsdata.it wrote: > >> Is this a practical use case? When are sequential visits of all >> elements in order frequently suspended to make insertions and >> deletions, with a need for efficient lookup by key? > > Does it need to be a sequential visit of *all* elements? > > Suppose you have a mapping of start times to tasks. You can then want > to iterate over all tasks that need to be started between noon en 4 pm > next monday. If you have a hashtable you still will need to sort all > the keys even if you will visit only 10%. If you have a tree you can > just visit the specified keys. > It still depends on the exact pattern of use. If you have an implementation which tracks additions and deletions and sorts them into the list when required (as we came up with earlier) then this is much more efficient that re-sorting the whole list every time. Sorting a large sorted list with a few unsorted elements on the end is comparable to inserting the elements individually into a tree, and you still have the hashtable benefits on accessing elements to help level the playing field. For me though, the most convincing use-case for a sorted dictionary is one that I don't think has been mentioned yet: There are situations when you want to use a dictionary with existing library code that doesn't care about the random key ordering, but you have additional requirements which the original code didn't know about. For example, in the sorteddict code I added an implementation for the __repr__ method and an associated doctest. Unlike iteration over sorteddict itself, I didn't bother to make __repr__ stable, so in that particular doctest it only tests the repr of a sorteddict with a single element. If that was fixed to make the repr stable it would be a real benefit for writing any doctests which want to produce a dictionary as a result. Another example would be if you had a library which serialised a dictionary to xml. There is nothing wrong with the library if it doesn't care about order, but if you have some other reason why you want the xml to be stable (e.g. because you store it in a version control system and want to compare revisions) then a sorteddict would allow you to impose that behaviour on the library from outside. Contrary to my earlier insistence that sorteddict is only really useful if you can have a key parameter, both of these examples simply want an arbitrary but defined order of iteration for dictionary keys. A much simpler sorteddict that has been discussed earlier would be sufficient. From zachREMOVE at MEin.tu-clausthal.de Fri Sep 28 15:00:45 2007 From: zachREMOVE at MEin.tu-clausthal.de (Gabriel Zachmann) Date: Fri, 28 Sep 2007 21:00:45 +0200 Subject: Bug with lists of pairs of lists and append() Message-ID: Well, could some kind soul please explain to me why the following trivial code is misbehaving? #!/usr/bin/python s = [] l = [ 0 ] r = [0, 0] while r: x = (l,r) print x s.append( x ) l.append( r.pop(0) ) print s The output I get is: ([0], [0, 0]) ([0, 0], [0]) [([0, 0, 0], []), ([0, 0, 0], [])] and the error is in the last line: the two pairs in the outer list are identical and they should be equal to the pairs one the first and the 2nd line, respectively! Shouldn't they? I think I'm going nuts -- for the life of me I don't see what's going on ... Thanks a lot in advance for any insights, etc. Best regards, Gabriel. From dkixk at earthlink.net Fri Sep 28 19:27:04 2007 From: dkixk at earthlink.net (Damien Kick) Date: Fri, 28 Sep 2007 18:27:04 -0500 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <873b0fhokz.fsf@kobe.laptop> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> Message-ID: <13frd6vtarbee75@corp.supernews.com> Giorgos Keramidas wrote: > On Fri, 22 Jun 2007 23:08:02 -0000, nebulous99 at gmail.com wrote: >> So much for the "free" in "free software". If you can't actually use >> it without paying money, whether for the software or for some book, it >> isn't really free, is it? > > Please do not confuse the term 'free' in 'free software' with 'gratis'. > > 'Gratis', i.e. 'lacking a monetary price tag' is something *very* > different from the meaning of 'free' in 'free software'. If you were referring to the "free" in "free Mumia Abu Jamal", I would agree with you. I don't think anyone would imagine that this phrase meant that someone was going to get Mumia Abu Jamal gratis. Like it or not, "free software" referring to "free as in beer" is probably the most common interpretation of the phrase for a native English speaker. Admittedly, I do not have a "scientific" survey handy. However, I just asked my wife--who has absolutely no interest in anything related to programming, has never heard of the FSF, Eric Raymond, nor the disagreement between those two camps, nor probably will she ever have an interest--what she thinks I mean when I say "free software". After getting over the "why are you asking such a stupid question" phase, the first thing that jumped to her mind was "free as in beer". You can stamp, growl, swagger, spit, curse, and bluster all you want on this point, but millions of English speakers are going to ignore you anyway. Lucky for most of them, they do not have to suffer the lectures of sociopolitically motivated language mavens trying to "correct" them from the error of mistaking the meaning of a phrase to be the normal meaning of that phrase. From rainwatching at gmail.com Sat Sep 1 11:54:09 2007 From: rainwatching at gmail.com (=?iso-8859-1?q?S=F6nmez_Kartal?=) Date: Sat, 01 Sep 2007 15:54:09 -0000 Subject: reload(sys) In-Reply-To: References: <1188521143.421431.119100@l22g2000prc.googlegroups.com> <1188564816.430863.219560@w3g2000hsg.googlegroups.com> Message-ID: <1188662049.337034.58220@w3g2000hsg.googlegroups.com> On 31 A ustos, 20:09, Steven Bethard wrote: > S?nmez Kartal wrote: > > On 31 A ustos, 04:24, Steven Bethard wrote: > >> S?nmez Kartal wrote: > >>> I've had an encoding issue and solved it by > >>> "sys.setdefaultencoding('utf-8')"... > >>> My first try wasn't successful since setdefaultencoding is not named > >>> when I imported sys module. After, I import sys module, I needed to > >>> write "reload(sys)" also. > >>> I wonder why we need to call "reload(sys)" to get setdefaultencoding > >>> named? > >> sys.setdefaultencoding is purposely deleted from the sys module after > >> it's loaded because you really shouldn't be using it. The reload() call > >> restores the deleted attribute. > > >> If you'd like a less brittle solution to your encoding issue, explain > >> what the issue was, and people here can probably help you find a better > >> solution. > > >> STeVe > > > I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as > > "f.write(str(xml))". At execution of that line, it gives error with > > description, configure your default encoding... > > Could you post the actual traceback you're getting? > > STeVe Steve, I get this when it happens: "Decoding Error: You must configure default encoding" which comes from in the code excerpt in xmlbuilder.py (http://rafb.net/p/9rURi822.html) From cjt22 at bath.ac.uk Tue Sep 4 10:54:10 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Tue, 04 Sep 2007 07:54:10 -0700 Subject: Printing lists in columns In-Reply-To: <46dd69b1$0$24998$426a74cc@news.free.fr> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> <1188913394.763871.218660@d55g2000hsg.googlegroups.com> <46dd69b1$0$24998$426a74cc@news.free.fr> Message-ID: <1188917650.826116.252470@19g2000hsx.googlegroups.com> On Sep 4, 3:20 pm, Bruno Desthuilliers wrote: > cj... at bath.ac.uk a ?crit : > (snip) > > > Thanks guys > > > I have a list of lists such as > > a = ["1" , "2"] b = ["4", "5", "6"] c = ["7",8", "9"] > > Stored in another list: d = [a,b,c] > > > I know this makes me sound very stupid but how would I specify > > in the parameter the inner lists without having to write them all out > > such as: > > > for row in izip_longest(d[0], d[1], d[2], fillvalue='*'): > > print ', '.join(row) > > > i.e. How could I do the following if I didn't know how many list of > > lists I had. > > for row in izip_longest(*d, fillvalue='*'): > print ', '.join(row) > > HTH I thought that, but when I tried it, I recieved a "Syntax error: invalid syntax" message with ^ pointing to the 'e' of fillvalue From usenet at solar-empire.de Thu Sep 27 13:45:06 2007 From: usenet at solar-empire.de (Marc Christiansen) Date: Thu, 27 Sep 2007 19:45:06 +0200 Subject: True of False References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> <1190912324.363127.26100@r29g2000hsg.googlegroups.com> Message-ID: <2q6ts4-gjv.ln1@pluto.solar-empire.de> Casey wrote: > I would recommend the OP try this: > > run the (I)python shell and try the following: > >>>> a = [x for x in "abcdefg"] >>>> a > ['a','b','c','d','e','f','g'] >>>> "c" in a > True >>>> "c" in a == True > False >>>> ("c" in a) == True > True > > The reason your conditional failed is that it was interpreted as "c" > in (a == True) which is False. That was my first thought, too. But watch: >>> a = list("abcde") >>> a ['a', 'b', 'c', 'd', 'e'] >>> "c" in (a == True) Traceback (most recent call last): File "", line 1, in TypeError: argument of type 'bool' is not iterable Then it dawned on me (is this the right phrase?): It's the same situation as e.g. x < y >= 1, which means the same as "x < y and y >= 1" (except that y is only evaluated once). So '"c" in a == True' gets evaluated as '"c" in a and a == True'. > the "==" operator binds at a higher precedence level than the "in" > operator, just as multiplication binds higher than addition Operator precedence plays no role in this case. It is a case of 'chained' comparisons. Hope that clears it up Marc From jstroud at mbi.ucla.edu Sun Sep 9 15:36:02 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 09 Sep 2007 12:36:02 -0700 Subject: Python syntax wart In-Reply-To: References: Message-ID: Lawrence D'Oliveiro wrote: > The one thing I don't like about Python syntax is using backslashes to > continue lines. Yes, you can avoid them if you can include parentheses > somehow, but this isn't always possible. > > Possible: > > if ( > quitting > and > len(client["to_write"]) == 0 > and > len(client["read"]) + client["to_read"] == 0 > ) : > close_client(client, "shutting down") > #end if > > Not possible: > > for \ > Link \ > in \ > GetEachRecord \ > ( > "links", > ("from_episode",), > "to_episode = %s", > [EpisodeID], > "order by when_created" > ) \ > : > out.write \ > ( > "

Back to episode %d\n" > % > ( > LinkToMe({"ep" : Link["from_episode"]}), > Link["from_episode"] > ) > ) > #end for > I usually write my code in a way that can be understood by looking at it, with self-documenting names, clear organization, and lines that fit under 72 characters (if I can help it). But if you insist on making perl noise, go 'head. record_type = "links" episodes = ("from_episode",) format = "to_episodes = %s" ids = [EpisodeID] order = "order by when_created" records = GetEachRecord(record_type, episodes, format, ids, order) for Link in records: template = "

Back to episode %d\n" the_link = Link["from_episode"] target = LinkToMe({"ep" : Link["from_episode"]}) msg = template % (target, the_link) out.write(msg) James From Graham.Dumpleton at gmail.com Wed Sep 5 21:22:38 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 06 Sep 2007 01:22:38 -0000 Subject: Module for mod_python In-Reply-To: References: <12506829.post@talk.nabble.com> Message-ID: <1189041758.262088.60520@y42g2000hsy.googlegroups.com> On Sep 6, 9:32 am, rieh25 wrote: > Is it such a bad idea that it doesn't deserve a reply? You only posted the question six hours ago. Maybe the people who might want to comment are asleep. BTW, have you done an analysis of the various existing database object relational mapper systems for Python that already exist? There are also some systems for automatic web application forms generation based on database data as well. How is what you have in mind different to or not covered by these existing packages? If you describe how what you want to do isn't satisfied by the existing systems then people may be more interested in commenting. If you aren't aware of these existing systems then perhaps use Google to do some research on them first. Graham > rieh25 wrote: > > > I've been thinking about a module (actually I have it partially > > implemented in Zope), that would do the following things: > > > - Read the structure of a MySql database (fill a dictionary with it) > > > In order to: > > > - Quickly create detail/filter/update forms given a table name (without > > specifying the fields because they have already been detected) > > - Keep state of record selection. In order to implement Master-Detail form > > processing, with unlimited levels of parent-child table relations, which > > have also been detected already (foreign keys) > > - Management of interrelation between security and menus (a user can only > > access certain parts of the application) > > > I think that Ruby on Rails does something similar, but still I thing it > > would be interesting to implement it in Python. What do you think? > > -- > View this message in context:http://www.nabble.com/Module-for-mod_python-tf4386823.html#a12513012 > Sent from the Python - python-list mailing list archive at Nabble.com. From steve at holdenweb.com Wed Sep 12 20:37:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Sep 2007 20:37:43 -0400 Subject: Search path for python script In-Reply-To: <1189633230.265179.58780@19g2000hsx.googlegroups.com> References: <1189633230.265179.58780@19g2000hsx.googlegroups.com> Message-ID: grt wrote: > I'm new to python, running it under cygwin. This must be easy but I > haven't figured it out. I'm trying to run a script by typing: > > python test.py > > where test.py is in a directory I've added to PYTHONPATH, but test.py > is not found. Perhaps PYTHONPATH only applies to modules imported > within a script. I didn't notice an option to python to search the > standard path, like Perl -S. > > How is this done? > The PYTHONPATH is only used to augment sys.path, which in turn is only used for locating modules to import. If you want to locate scripts then just put them on your PATH, and make sure they are +x with a shebang line (#!/usr/bin/env python is the commonest) at the head. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at REMOVE-THIS-cybersource.com.au Sun Sep 2 18:40:50 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 02 Sep 2007 22:40:50 -0000 Subject: howto reload Python module? References: <1188764906.354022.86370@50g2000hsm.googlegroups.com> Message-ID: <13dmevig2cn53b8@corp.supernews.com> On Sun, 02 Sep 2007 13:28:26 -0700, dmitrey wrote: > my Python module was changed in HDD (hardware disk drive), moreover, > changed its location (but still present in sys.path). how can I reload a > func "myfunc" from the module? (or howto reload whole module)? > Thank you in advance, D. You're moving the LOCATION of modules while they are running??? WHY??? Nevertheless, and much to my surprise, a quick test suggests that so long as the new location is in sys.path, reload() continues to do what it is supposed to do. -- Steven. From bscrivener42 at gmail.com Wed Sep 12 19:06:00 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Wed, 12 Sep 2007 23:06:00 -0000 Subject: Search path for python script In-Reply-To: <1189633230.265179.58780@19g2000hsx.googlegroups.com> References: <1189633230.265179.58780@19g2000hsx.googlegroups.com> Message-ID: <1189638360.283791.273910@50g2000hsm.googlegroups.com> On Sep 12, 4:40 pm, grt wrote: > > I'm trying to run a script by typing: > > python test.py > What happens if you just type: test.py or test and hit Enter? rd From perl4hire at softouch.on.ca Thu Sep 13 12:10:46 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Thu, 13 Sep 2007 12:10:46 -0400 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: Tim Golden wrote: > Amer Neely wrote: >> Richie Hindle wrote: >>>> [Amer] >>>> #!/usr/bin/python >>>> [...] On my home PC [...] >>>> [Thu Sep 13 04:16:03 2007] [error] [client 0.0.0.0] (OS 2)The system >>>> cannot find the file specified. >>> That's because on your home PC Python is somewhere like >>> C:\Python25\python.exe, not /usr/bin/python. >>> >>> Are you sure /usr/bin/python is correct for your hosting environment? >>> >> >> It's my understanding that the Windows shell doesn't pay much >> attention to the shebang line if the file type is associated with the >> proper application. >> >> But I tried your suggestion and got the same results. > See my reply to this post - I had a typo in the shebang line and it now works on my home PC. > The Windows shell doesn't, but Apache does. (Haven't followed > this thread closely, but I seem to remember it has to do with > running CGI scripts). This seems to indicate that maybe my host needs to configure Apache to run python scripts? But I didn't need to do anything with mine. -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From rcdailey at gmail.com Tue Sep 4 14:26:36 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 4 Sep 2007 13:26:36 -0500 Subject: Rendering API for python? Message-ID: <496954360709041126l2c1d4a3cg821b263acb9fa9c2@mail.gmail.com> Hi, I'm developing a quick python script to test an algorithm of mine. I would like to be able to plot the algorithm results to a diagram (much like you can do in Matlab). I was wondering if there's an API around that would allow me to quickly do this? Perhaps some sort of rendering API or plotting API for python? Any help is greatly appreciated. Thanks. PS: I'm using Python on Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Wed Sep 12 10:54:34 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 12 Sep 2007 14:54:34 -0000 Subject: Dynamically removing methods in new-style classes In-Reply-To: <1189607295.676704.215210@r34g2000hsd.googlegroups.com> References: <1189607295.676704.215210@r34g2000hsd.googlegroups.com> Message-ID: <1189608874.316142.64050@g4g2000hsf.googlegroups.com> On Sep 12, 4:28 pm, agupta0... at gmail.com wrote: > I am trying unsuccessfully to remove some methods from an instance, Usuall one does not remove methods, but wraps the object and delegates only to a restricted number of methods. Is this solution viable? If not, you may be forced to change the class of the instance, or to play trick such as def removed_method(self): raise NotImplementedError self.test1 = removed_method.__get__(self) Michele Simionato From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 12 03:54:46 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 12 Sep 2007 09:54:46 +0200 Subject: Generating HTML In-Reply-To: References: <9e2f512b0709112133l41ce5ef1g815962a81becf6b9@mail.gmail.com> Message-ID: <46e79b40$0$28082$426a74cc@news.free.fr> Evan Klitzke a ?crit : > On Wed, 2007-09-12 at 01:33 -0300, Sebastian Bassi wrote: >> Hello, >> >> What are people using these days to generate HTML? I still use >> HTMLgen, but I want to know if there are new options. I don't >> want/need a web-framework a la Zope, just want to produce valid HTML >> from Python. > > It's not applicable for everything, but if you're planning on using > Python to generate web pages you should really be using Cheetah > templates. Very simple to use template system that is also very > powerful, and you don't need to use it in conjunction with a heavy web > application framework. See http://www.cheetahtemplate.org/ > Same for Mako (http://www.makotemplates.org), which has IMHO a much nicer syntax (Cheetah looks too much like line noise IMHO). From wizzardx at gmail.com Sun Sep 23 12:34:48 2007 From: wizzardx at gmail.com (David) Date: Sun, 23 Sep 2007 18:34:48 +0200 Subject: Writing Object Data to Disk In-Reply-To: <1190443648.5838.6.camel@ubuntu-laptop> References: <1190443648.5838.6.camel@ubuntu-laptop> Message-ID: <18c1e6480709230934k61504fa1r528c2f4ade9722f0@mail.gmail.com> > I would like to know if "Pickling" the class object is the only way of > writing it to disk for persistent storage. Also, do we have a concept > similar to "array of objects" in Python? The number of objects is only > known at "run-time". Have a look at YAML. http://freshmeat.net/projects/syck/ Also it is possible to persist python data to and from XML. See xml.marshal.generic.dumps From duncan.booth at invalid.invalid Sun Sep 16 09:09:17 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Sep 2007 13:09:17 GMT Subject: Can't see the arguements when use Python in WSH. References: <1189945728.024735.3960@w3g2000hsg.googlegroups.com> Message-ID: GaryLee wrote: > Does anyone have the same situation? Is it my pywin32 package > corrupted? I've downloaded the last pywin32 package and executed the > site-packages\win32comext\axscript\client\pyscript.py to register the > PyScript. But, the problem is still there. > I've no idea why pyscript.py doesn't set up the registry correctly, but it should all work if you run the command: ftype pysFile=%SystemRoot%\System32\WScript.exe "%1" %* (If you wish you can try "ftype pysFile" first to see the current setting. On my system the file association wasn't set at all but it sounds like on yours it may be set but missing the %*) From ed at leafe.com Wed Sep 19 14:14:04 2007 From: ed at leafe.com (Ed Leafe) Date: Wed, 19 Sep 2007 14:14:04 -0400 Subject: super() doesn't get superclass In-Reply-To: <1190199134.791808.267110@22g2000hsm.googlegroups.com> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> Message-ID: <7442D29C-FC2E-4E31-A82F-D1F8F7D1ECF5@leafe.com> On Sep 19, 2007, at 6:52 AM, Michele Simionato wrote: > Well, I am personally *against* multiple inheritance (i.e. IMO it > gives more troubles than advantages) For the sorts of examples that have been used in this thread, it isn't MI that's problematic; it's the poor quality of the design. Mixing two complete classes to create a multiply-inherited class is almost always the sign of poor design. OTOH, mixin-style classes are a wonderful way to ensure consistency across several different classes that all need a common behavior added to them. We use mixins extensively throughout Dabo, and they allow us to give several classes the desired behaviors, while only having one mixin class to maintain. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From jjl at pobox.com Tue Sep 11 16:51:11 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 11 Sep 2007 20:51:11 GMT Subject: Car-ac-systems References: <1189532573.728913.306470@g4g2000hsf.googlegroups.com> <5ko2rjF4om2bU1@mid.uni-berlin.de> Message-ID: <87odg9lydc.fsf@pobox.com> "John Timney (MVP)" writes: [...] > I like top posted threads, its my preferred response method - and actually [...] http://en.wikipedia.org/wiki/Apostrophe#English_language_usage John From robert.kern at gmail.com Fri Sep 28 17:03:21 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 28 Sep 2007 16:03:21 -0500 Subject: List search In-Reply-To: References: Message-ID: Kevin Walzer wrote: > I'm having a problem with searching a list. Here's my code: > > mylist = ['x11', 'x11-wm', 'x11-system'] > > for line in mylist: > if 'x11' in line: > print line > > This results in the following output: > > x11 > x11-wm > x11-system > > I'm looking to return the list item that just has 'x11'. How can I > structure my search term so that this output is returned? line == 'x11' -- 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 robyn.sword at phs.com Mon Sep 24 11:39:11 2007 From: robyn.sword at phs.com (Sword, Robyn) Date: Mon, 24 Sep 2007 10:39:11 -0500 Subject: CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS! Message-ID: how do you claim your tickets? CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS! CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS! lisawill4u at yahoo.com Sat Nov 20 21:35:53 CET 2004 * Previous message: Python Tutorials, about 100 and sorted by Topic or Category * Next message: CGI email script * Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] ________________________________ An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20041120/341599 3d/attachment.htm ________________________________ * Previous message: Python Tutorials, about 100 and sorted by Topic or Category * Next message: CGI email script * Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] ________________________________ More information about the Python-list mailing list This e-mail, including attachments, may include confidential and/or proprietary information, and may be used only by the person or entity to which it is addressed. If the reader of this e-mail is not the intended recipient or his or her authorized agent, the reader is hereby notified that any dissemination, distribution or copying of this e-mail is prohibited. If you have received this e-mail in error, please notify the sender by replying to this message and delete this e-mail immediately. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Tue Sep 18 16:37:43 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 18 Sep 2007 13:37:43 -0700 Subject: Metatest 0.1.0 In-Reply-To: <46F006D5.3060609@pytex.org> References: <1190130384.753009.142150@i13g2000prf.googlegroups.com> <46F006D5.3060609@pytex.org> Message-ID: <1190147863.968759.229330@g4g2000hsf.googlegroups.com> On Sep 18, 7:11 pm, Jonathan Fine wrote: Jonathan Fine schrieb: > Kay Schluehr wrote: > >>> http://metatest.sourceforge.net/doc/pyconuk2007/metatest.html > >>> From the HTML slides: >> >> Assertion tests are easy to write but report and run poorly. >> >> I tend to think this is a prejudice that leads to ever more ways to >> write tests perform test discoveries, invent test frameworks etc. >> >> When I thought about organizing my tests for EasyExtend I was seeking >> for a strategy being adapted to my own behaviour. The very first step >> I made when creating a new language, modifying a grammar rule, >> changing the Transformer etc. was starting an interactive shell and >> typing some commands. > > Yes, Python is really good for that. I do it a lot also. > >> This is just checking out or smoke testing my >> application and I wanted to reproduce it. So I recorded the >> interactive shell session and replayed it as another shell session. I >> enabled to set breakpoints in the logged output and implemented a >> command for proceeding the replay. > > This is similar, I think, to what Metatest does. See http://metatest.sourceforge.net/doc/pyconuk2007/metatest.html#slide5 > >> Then I discovered I actually wrote an interactive test runner. I don't >> have to care for all the exceptions being thrown in the session and >> don't care for cleanups but just assign parts of the session as tests >> using assert for getting an overview at the end. The only additonal >> command I implemented was raises to capture the side-effect of raising >> an exception. > > Sounds interesting. Is this code, or examples of its use, available? Sure, it's part of EasyExtend. See also www.fiber-space.de Checkout the documentation for consoletest. I guess in the current release recording and replaying can't be done in the same run. I've got a corrected version on my disk but I didn't uploaded it yet and corrected the docs. The reason why consoletest is bundled with EasyExtend is the use of a different, more flexible and somewhat simpler InteractiveConsole implementation than available in the stdandard library that can execute code of arbitrary languages. This was a projects requirement but there is no fundamental reason why it can't be separated from eeconsole.py. >> So I'm going to argue here that there isn't anything particular about >> writing/coding a test ( planning tests, specifying tests, reviewing a >> testspecification etc. are another issue ). Instead you can keep a >> seemingly unrelated practice and turn it into a test by a tiny >> signification. > > I'm all in favour of making tests easier to write, easier to run, and the outputs easier to understand. > > I've submitted a feature request for command line use of Metatest (something I've been thinking of a while): > http://sourceforge.net/tracker/index.php?func=detail&aid=1797187&group_id=204046&atid=988038 > > Here's how I'd like the feature to look (from the above URL): > === > Python 2.4.1a0 (#2, Feb 9 2005, 12:50:04) > [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> from metatest.py.mymod import plus > >>> import metatest > >>> plus(2, 3) == 6 > > >>> metatest.immediate = True # New command > >>> plus(2, 3) == 6 > TestError: Expected '6', got '5' > >>> > === > > OK. So now here's a problem. We can create stuff like the above that states clearly (I hope) what is required. How can we write a test for this sort of behaviour? So that's another feature request. How does metatest analyze the tested expression? Lets say I try to check this expression >>> plus( f(1) == True, f(2) != False) == plus( f(2) == True, f(1) != False) metatest must have decent knowledge about the expression structure of Python expressions to detect the top level comparison and separate it from the right and left hand side in order to generate the message of the example. Since consoletest uses Pythons assert it is obviously primitive in this respect and lacks expressivity of error messages. So it fails with respect of one of your criteria. But note that EasyExtend has the full power of a python parser in the background and is a framework for analyzing and transforming expressions. I refused to filter assert here or nest transformers since they might interfere with more general purposes of EasyExtend. Regards, Kay From rave247 at seznam.cz Thu Sep 6 11:19:35 2007 From: rave247 at seznam.cz (=?us-ascii?Q?rave247=20rave247?=) Date: Thu, 06 Sep 2007 17:19:35 +0200 (CEST) Subject: =?us-ascii?Q?Getting=20original=20working=20directory?= Message-ID: <1520.1657-1856-1993609010-1189091974@seznam.cz> Hi, I' am unable to solve this problem. I've got python program, it is installed in standard location. I run this program from some location X (note that I just type relative "myscript", leaving operating system to look up script itself using PATH variable) and this program somewhere in the code calls os.chdir() to change it is current working directory and I would need in python code to get the *original* directory location *after* os.chdir() is performed. This means the location X from which script was performed - it is the location I am in after script is finished. Thanks for any help From bj_666 at gmx.net Fri Sep 7 09:42:30 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2007 13:42:30 GMT Subject: exponential float formmating References: <1189170499.945175.275210@57g2000hsv.googlegroups.com> Message-ID: <5kd2q6F31i6hU4@mid.uni-berlin.de> On Fri, 07 Sep 2007 06:08:19 -0700, zunbeltz wrote: > For compatibility reasons with an old program I have to format string > in exponential format with the following format > > 0.xxxxxE-yy > > This means that the number start always by 0 and after the exponent > there should be alway the sing and 2 number for the exponent. > > for example 13 shoud be 0.13000E+02 > I always get 1.30000E001 I don't know if this is platform dependent but this works for me: In [41]: '%e' % 1.3 Out[41]: '1.300000e+00' In [42]: ('%e' % 1.3).upper() Out[42]: '1.300000E+00' Ciao, Marc 'BlackJack' Rintsch From carsten at uniqsys.com Tue Sep 18 13:58:03 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 18 Sep 2007 13:58:03 -0400 Subject: Writing to multiple excel worksheets In-Reply-To: References: <969892.43175.qm@web50103.mail.re2.yahoo.com> Message-ID: <1190138283.3388.19.camel@dot.uniqsys.com> On Tue, 2007-09-18 at 18:49 +0200, Tommy Nordgren wrote: > Excel files are in a binary and proprietary format. True, but that doesn't mean you can't create them with free software. PyExcelerator (http://sourceforge.net/projects/pyexcelerator) can create Excel files. HTH, -- Carsten Haese http://informixdb.sourceforge.net From s.mientki at id.umcn.nl Thu Sep 13 09:27:57 2007 From: s.mientki at id.umcn.nl (stef) Date: Thu, 13 Sep 2007 15:27:57 +0200 Subject: wxstyledtextctrl and xml markup In-Reply-To: <1189689993.338662.267340@k79g2000hse.googlegroups.com> References: <1189689993.338662.267340@k79g2000hse.googlegroups.com> Message-ID: <4abcb$46e93adc$83aef404$31489@news2.tudelft.nl> > I highly recommend the wxPython mailing list. Right now it is down > (see their website), its'up again. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 19 07:55:07 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 13:55:07 +0200 Subject: super() doesn't get superclass In-Reply-To: <1190199134.791808.267110@22g2000hsm.googlegroups.com> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> Message-ID: <46f10e0e$0$27681$426a34cc@news.free.fr> Michele Simionato a ?crit : > On Sep 19, 12:36 pm, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >> The next class in the MRO *is* a superclass of the *instance*. Else it >> wouldn't be in the MRO !-) > > Bruno, there is no such a thing as a superclass in a multiple > inheritance May I disagree ? Of course, with MI, there's no such thing as "the" superclass, but there are still superclasses - the classes listed in the MRO. At least according to a commonly agreed definition of "superclass"... (snip) >> Well, I understand that you disagree with both the documention and the >> name of super. As far as I'm concerned, the mere fact that this >> discussion happens is probably a sign that there's something to be fixed >> here - at least wrt documentation, possibly wrt/ naming. But the >> *feature* by itself is certainly something we do want to keep, whatever >> some may argue. > > Well, I am personally *against* multiple inheritance (i.e. IMO it > gives more > troubles than advantages) Given Python's type system and support for delegation, it's a fact that MI is not that necessary - FWIW, I don't remember having ever used it except in Zope2 (where it's commonly a PITA). Now I don't think there's any reason to remove from MI, since it's already there, and about as usable as it can be. From __peter__ at web.de Sun Sep 23 03:29:12 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 Sep 2007 09:29:12 +0200 Subject: newb: glob on windows os.renames creates many nested folders References: <1190515183.389916.92240@19g2000hsx.googlegroups.com> Message-ID: crybaby wrote: > when I do this in my python code and run it in windows xp, it creates > ctemp/..../.../.../../ so on and creates file t. Not file starting > with the name complist and ending with .txt (complist*.txt). Any idea > why this may be? glob only works in *nix not on windows? > > os.renames(glob.glob('complist*.txt') > [0],r'temp/'.join(glob.glob('complist*.txt')[0])) Python does what you tell it. Let's assume >>> glob.glob("complist*.txt") ['complist001.txt', 'complist002.txt'] The first argument to os.renames() is then 'complist001.txt' and the second is 'temp/'.join('complist001.txt'), or >>> "temp/".join("complist001.txt") 'ctemp/otemp/mtemp/ptemp/ltemp/itemp/stemp/ttemp/0temp/0temp/1temp/.temp/ttemp/xtemp/t' that is the join() method interprets the string "complist001.txt" as the character sequence ["c", "o", "m", ...] and stuffs a "temp/" between "c" and "o", "o" and "m", ... What you want instead is just "temp/" + "complist001.txt" or, written in an os-independent way, os.path.join("temp", "complist001.txt") where a path separator is added automatically. Your code then becomes fn = glob.glob("complist*.txt")[0] # don't call stuff like that twice os.renames(fn, os.path.join("temp", fn)) Peter From lucaberto at libero.it Thu Sep 6 09:09:41 2007 From: lucaberto at libero.it (luca72) Date: Thu, 06 Sep 2007 06:09:41 -0700 Subject: Sip4.7 Message-ID: <1189084181.385917.253950@d55g2000hsg.googlegroups.com> Hello i have python2.5 with sip4.6 installed on a linux machine, i need to install sip4.7 but i get a lot of error like this: sip.h:525: error: expected specifier-qualifier-list before 'PyMethodDef' sip.h:609: error: expected specifier-qualifier-list before 'sipForceConvertToFunc' sip.h:666: error: expected specifier-qualifier-list before 'PyObject' sip.h:902: error: expected specifier-qualifier-list before 'PyTypeObject sipint.h:81: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token sipint.h:86: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token sipint.h:87: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token siplib.c:39: error: expected ')' before '*' token siplib.c:41: error: expected ')' before '*' token siplib.c:43: error: expected ')' before '*' token siplib.c:45: error: expected ')' before '*' token siplib.c:48: error: expected ')' before '*' token plib.c:285: error: expected specifier-qualifier-list before 'PyObject' siplib.c:290: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'sipWrapperType_Type' Have you some idea why? Regards Luca From mensanator at aol.com Sun Sep 9 16:12:09 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 09 Sep 2007 13:12:09 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> Message-ID: <1189368729.821382.85430@50g2000hsm.googlegroups.com> On Sep 9, 2:15???pm, "J. Cliff Dyer" wrote: > Dotan Cohen wrote: > > FIrst of all, how is the % symbol (as in 70%6=4) called in English? > > > Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or > > the other in error? Is this a known gotcha? I tried to google the > > subject however one cannot google the symbol %. Thanks in advance. > > > Dotan Cohen > > The % operator is called "modulo" in English. ?I don't think the > difference in implementation is an error. ?It's just a difference of > calculation method. > > Python will always yield a number x = m%n such that 0 <= x < n, but > Turbo C will always yield a number such that if x = m%n -x = -m%n. ?That > is, since 111 % 10 = 1, -111 % 10 = -1. ?The two values will always > differ by n (as used above). > > I'm sure there are mathematicians on the list who can give you a more > technical, precise explanation of the reasons for the different results. > > Cheers, > Cliff Think of clock arithmetic: / 0 -1 / / 9 1 8 2 7 3 6 4 5 1 step counter-clockwise is the same as 9 steps clockwise, so -1 is congruent to 9 (mod 10), so both are correct. A common mistake is to assume -1 and +1 to be the same. Remember, in Python, sequential negative numbers % n is equivalent to going counter-clockwise: >>> for i in xrange(-1,-12,-1): print i % 12, 11 10 9 8 7 6 5 4 3 2 1 From fakeaddress at nowhere.org Wed Sep 26 03:28:39 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 26 Sep 2007 07:28:39 GMT Subject: database persistence with mysql, sqlite In-Reply-To: <1190650748.590245.221490@n39g2000hsh.googlegroups.com> References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> <1190650748.590245.221490@n39g2000hsh.googlegroups.com> Message-ID: coldpizza wrote: > It turned out that the method above ('SELECT * FROM TABLE LIMIT L1, > L2') works ok both with mysql and sqlite3, therefore I have decided to > stick with it until I find something better. With Sqlite3 you are > supposed to use LIMIT 10 OFFSET NN, but it also apparently supports > the mysql syntax (LIMIT NN, 10) for compatibility reasons. A more reliable form is along the lines: SELECT keyfield, stuff FROM table WHERE keyfield > ? ORDER BY keyfield LIMIT 10 With the right index, it's efficient. -- --Bryan From carsten at uniqsys.com Fri Sep 7 13:40:35 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 07 Sep 2007 13:40:35 -0400 Subject: passing command line arguments In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE32D@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE32D@efmailx> Message-ID: <1189186835.3367.59.camel@dot.uniqsys.com> On Fri, 2007-09-07 at 12:47 -0400, Brian McCann wrote: > > Hi, > > when I run the script show_args2.py > > # ./show_args2.py 1 2 3 > > I get the following error > > Traceback (most recent call last): > File "./show_args2.py", line 4, in ? > print 'The arguments of %s are "%s"' %s \ > NameError: name 's' is not defined Start here: http://catb.org/~esr/faqs/smart-questions.html#before -- Carsten Haese http://informixdb.sourceforge.net From martin at v.loewis.de Sat Sep 29 03:00:16 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 Sep 2007 09:00:16 +0200 Subject: python 2.5 and 3gb switch In-Reply-To: References: Message-ID: <46FDF800.5030504@v.loewis.de> > The code runs successfully in lesser missions it just wont run in the extra > memory available when I try to run it along with my other programs in a 3gb > space. Still, it would be helpful if you explained how "wont run" manifests: does it fail to start, does it give you an exception, does it crash, does it erase your hard disk? I'm not aware of a 3gb Python build, but you should be able to build it yourself. Regards, Martin From zzbbaadd at aol.com Fri Sep 28 13:24:46 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 10:24:46 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <5m4oi1Fbic8sU1@mid.uni-berlin.de> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> <5m4oi1Fbic8sU1@mid.uni-berlin.de> Message-ID: <1191000286.256156.49530@n39g2000hsh.googlegroups.com> On Sep 28, 9:30 am, "Diez B. Roggisch" wrote: > > You said it was a most basic language feature. I still haven't heard > > anything that leads me to believe that statement is correct. What > > languages implemented decorators as a most basic language feature? > > I was talking about Python, the programming language that is discussed in > this NG > > > Python didn't have them for over a decade so it doesn't qualify. > > Says who? For further comments, see below. I had the impression you were saying it was a basic language feature of most languages. In any event Guido Van Rossum didn't include them for over a decade. If he felt they were a basic language feature it seems that he would have included them in 1991. > > > > >> >> Maybe you should start using python more and _then_ start discussions > >> >> about it's features, when you have good grounds and can provide viable > >> >> alternatives? But I guess that's a wish that won't be granted.... > > >> > static and abstract keywords would seem to be very viable > >> > alternatives. Viable enough that several language designers used them. > > >> As I said - you don't get it. The decorators (in conjunction with the > >> descriptor protocol - ever heard of that?) are very powerful yet lead as > >> an artifact to simple, declarative implementations of features you like, > >> namely static and abstract methods. > > > You said I had to provide a viable alternative. I did that. I haven't > > heard of the descriptor protocol. > > Where did you do provide that alternative? def static def abstract I was not providing an alternative for decorators. > > > One of the problems with "getting" decorators is that they are not in > > older books at all and newer books like Beginning Python from Novice > > to Professional (c) 2005 Magnus Lie Hetland, that I own, devote almost > > nothing to them. Out of 640 pages they are only mentioned > > in one paragraph that is in a section titled "Static Methods and Class > > Methods",(and followed by a class example with @staticmethod and > > @classmethod). > > > So it seems like Magnus Lie Hetland didn't think they were very > > important and he had Professional in his book title. > > I consider "core features of a language" the features that are part of the > specification and implementation. Neither do I care if there is anecdotal > evidence of prior usage in other languages, nor who or who not thinks they > are important enough to be dealt with in a book. By that definition isn't anything that is part of a language a core feature? Weren't we talking about basic features? > > And above all, I don't consider the time things have been around _without_ > any feature as proof of their irrelevance - or do you consider cars being > not core to western culture because they only have been around about 100 > years, whereas horses have been there for thousands of years? Happy riding, > cowboy! A relevant analogy would talk about a feature of cars that was not on them in the beginning but has been added later and whether it was a basic (or now, core) feature. Your definition of core feature given above means that anything on a car when it comes out of the factory is a core feature. > > Python 2.4 has been released in 2003, btw - so decorators are around for 4 > years now. > > So unless you come up with a definition of "core feature of a language" that > someone respectable in the CS-community wrote that features "time being > around" or "random book authors consider worthy" or "persons lacking the > motivation to really dig into do finally get it", I consider your > definition worthless. Agreed? > Since you defined a core feature (haven't seen your definition of a basic feature) as anything in the specification or implementation, I agree that it makes sense for you to disregard anything that limits core features to something less than everything. > >> Besides, those 'several language designers' seem to think that the > >> introduction of keywords isn't enough, but a general purpose annotation > >> scheme seems to be viable - or how do you explain e.g. JDK 1.5 > >> Annotations? > > > I certainly wouldn't call them a basic language feature. Java 1.0 came > > out in January 1996, Java 1.5 in September 2004. It doesn't appear > > that the language designer of Java, James Gosling, is still at the > > wheel or BDFL. But yes, Java is showing signs of "complexity creep". > > You'll be happy to know that I really dislike the C++ template syntax > > and Java has decided to add something similar. > > Again, your anecdotal language feature definition is nonsense. > > By the way, considering generics and C++-templates as "something similar" > shows the inclined beholder that there are other languages out there you > don't really understand. For me understanding is all I can hope to attain. Really understanding is something I must yield to the corps d'elite. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Sep 11 13:41:43 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 11 Sep 2007 19:41:43 +0200 Subject: mod_python and pysvn References: <1189525797.361829.69380@g4g2000hsf.googlegroups.com> Message-ID: <5ko2anF4iuuiU1@mid.individual.net> Tim Golden wrote: > Sjoerd wrote: >> ClientError: Unable to open an ra_local session to URL >> Unable to open repository 'file:///P:/tools/builds/repository' >> >> does anyone know how I can fix this? > > Usually means that the process which Apache is running under > (may well be LocalSystem) doesn't know about or doesn't have > access to p:/tools etc. Isn't this an SVN client error? Seems to me that the repository URL is invalid. Tim, try accessing the repository using svn list from the command line. Regards, Bj?rn -- BOFH excuse #350: paradigm shift...without a clutch From lasses_weil at klapptsowieso.net Thu Sep 13 12:37:24 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 13 Sep 2007 18:37:24 +0200 Subject: Help to start python In-Reply-To: <1189694381.957459.232350@y42g2000hsy.googlegroups.com> References: <1189693144.493878.130220@w3g2000hsg.googlegroups.com> <1189693433.545822.89580@o80g2000hse.googlegroups.com> <1189694381.957459.232350@y42g2000hsy.googlegroups.com> Message-ID: <46e96744$0$7702$9b4e6d93@newsspool2.arcor-online.net> python_lover wrote: > Please guide me some good sites to start web based programing on > python. > Here's a good one: Always remember: GIYF If you don't know what that means: /W From bignose+hates-spam at benfinney.id.au Wed Sep 26 05:30:53 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 26 Sep 2007 19:30:53 +1000 Subject: setuptools without unexpected downloads References: <87ejgmklep.fsf@benfinney.id.au> <878x6ukkvq.fsf@benfinney.id.au> <5luhb0Faal8aU1@mid.uni-berlin.de> <874phhlupi.fsf@benfinney.id.au> <5lumarFae888U1@mid.uni-berlin.de> Message-ID: <87ve9xkc36.fsf@benfinney.id.au> "Diez B. Roggisch" writes: > Ben Finney wrote: > > How would I modify my 'setup.py' script so that its default > > behaviour, when dependencies are not met, is not "download and > > install dependencies via setuptools" but instead "exit with error > > message"? > > easy_install has the --no-deps commandline argument. As am I. > I'm not sure if that is triggerable from inside setup.py Thanks for this answer. > - but in the end, you wanted user choice, didn't you? No. In the end, I want the default to be as described above. User choice is desirable, but not necessary for this requirement. > Generally speaking, I think the real problem here is the clash > between "cultures" of dependency-handling. But it's certainly beyond > setuptools scope to cope with every imaginable package management > system out there, and provide means to trigger an installation of > say e.g. debian packages that are needed. Indeed, and that's beyond the scope of what I'm asking about. -- \ "As soon as I get through with you, you'll have a clear case | `\ for divorce and so will my wife." -- Groucho Marx | _o__) | Ben Finney From ptmcg at austin.rr.com Mon Sep 24 16:01:52 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 24 Sep 2007 13:01:52 -0700 Subject: Nested For and While Statements In-Reply-To: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> Message-ID: <1190664112.564911.13480@57g2000hsv.googlegroups.com> On Sep 24, 2:28 pm, kou... at hotmail.com wrote: > I start my code with some constants then a while statement. But I > have some For statements towards the end within the While statement > where I start getting some errors. I'm hoping I won't have to post my > code, but it looks something like this: > > Import os, string > > while this: > > All Code indented like it should > > Last line in While. > > For i in range(1) > class = [] > class2 = [] > For i in range(2) > Do this > And this > And that. > > Next Line hits snag here? Where should this line > be? Why are the for loops further indented than the body of the while? If they are part of the while, "For i in range(1)" should line up with "Last line in While." If they are not part of the while, but come after, then "For i in range(1)" should line up with "while this:". Also, as James Stroud said, your for loop indexes are the same variable. -- Paul From mensanator at aol.com Sun Sep 16 17:54:39 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 16 Sep 2007 14:54:39 -0700 Subject: Try this In-Reply-To: References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> Message-ID: <1189979679.969074.216490@y42g2000hsy.googlegroups.com> On Sep 16, 2:22?pm, Steve Holden wrote: > mensana... at aol.com wrote: > > On Sep 16, 1:10?pm, Dennis Lee Bieber wrote: > >> On Sun, 16 Sep 2007 01:46:34 -0700, GeorgeRXZ > >> declaimed the following in comp.lang.python: > > >>> Then Open the Notepad and type the following sentence, and save the > >>> file and close the notepad. Now reopen the file and you will find out > >>> that, Notepad is not able to save the following text line. > >>> Well you are speed > >>> This occurs not only with above sentence but any sentence that has > >>> 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) > >> I tried. I also opened the saved file in SciTE... > >> And the text WAS there... > > >> It is Notepad that can not properly render what it, > >> itself, saved. > > > C:\Documents and Settings\mensanator\My Documents>type huh.txt > > Well you are speed > > > Yes, file was saved correctly. > > But reopening it shows 9 unprintable characters. > > If I copy those to a new file (huh1.txt): > > > C:\Documents and Settings\mensanator\My Documents>type huh1.txt > > ????????? > > > But wait...the new file is 20 characters, not 9. > > > 09/16/2007 01:44 PM 18 huh.txt > > 09/16/2007 01:54 PM 20 huh1.txt > > > C:\Documents and Settings\mensanator\My Documents>dump huh.txt > > huh.txt: > > 00000000 5765 6c6c 2079 6f75 2061 7265 2073 7065 Well you are spe > > 00000010 6564 ed > > > Here's what it's actually doing: > > > C:\Documents and Settings\mensanator\My Documents>dump huh1.txt > > huh1.txt: > > 00000000 fffe 5765 6c6c 2079 6f75 2061 7265 2073 .~Well you are s > > 00000010 7065 6564 peed > > One word: Unicode. > > The "open" and "save" dialogs allow you to specify an encoding. And the encoding specified was ANSI. > If you > specify Unicode the you will get what you see above. And if you specify ANSI _before_ you click the file name, the specification switches to Unicode and has to then be manually switched back to ANSI. > If you specify ANSI > you will get the text you entered. It's still a bug in the "open" dialog. > > By the way, this has precisely what to do with Python? I've been known to use Notepad to create Python source code. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline- Hide quoted text - > > - Show quoted text - From sajmikins at gmail.com Wed Sep 26 17:01:01 2007 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 26 Sep 2007 14:01:01 -0700 Subject: Matplotlib TkAgg WindowsXP ImportError In-Reply-To: <1190827160.282738.293770@k79g2000hse.googlegroups.com> References: <1190827160.282738.293770@k79g2000hse.googlegroups.com> Message-ID: <1190840461.990352.152900@k79g2000hse.googlegroups.com> On Sep 26, 1:19 pm, Simon Forman wrote: > Hello, > > I just installed Matplotlib (and NumPy) on a windows XP machine, and > I'm getting the following traceback when I try to use the TkAgg > backend. > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information.>>> import matplotlib > >>> matplotlib.use('TkAgg') > >>> from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\Lib\site-packages\matplotlib\backends > \backend_tkagg.py", > line 8, in > import tkagg # Paint image to Tk photo blitter > extension > File "C:\Python25\lib\site-packages\matplotlib\backends\tkagg.py", > line 1, in > import _tkagg > ImportError: DLL load failed: The specified module could not be found. > > > > I found one old (2004) posthttp://mail.python.org/pipermail/python-list/2004-April/258963.html > that seems to indicate that some sort version mismatch of the Tk/Tcl > libraries may be to blame. But I don't know how to diagnose that or > what to do about it. > > FWIW, I installed using matplotlib-0.90.1.win32-py2.5.exe and > numpy-1.0.3.1.win32-py2.5.exe. > > Thanks in advance for any help. > Sincerely, > ~Simon Ah, nevermind. I was missing MSVCP71.dll. Once I included that in the system folder matplotlib ran fine. Sorry for the "noise". ~Simon From raj.amal at gmail.com Fri Sep 28 00:40:59 2007 From: raj.amal at gmail.com (Amal) Date: Fri, 28 Sep 2007 10:10:59 +0530 Subject: ImportError: /usr/lib/python2.4/site-packages/_xmlplus/parsers/pyexpat.so: undefined symbol: PyUnicodeUCS4_Decode Message-ID: <3bfbb0bb0709272140n394315ddu2266eff99840db44@mail.gmail.com> When I am compiling some code, I am getting the following the above mentioned error. So how can i go about solving this issue. Should I recompile python using -enable-unicode=UCS4 option. Is there no other way to solve this issue. Amal. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Tue Sep 18 11:46:24 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 18 Sep 2007 08:46:24 -0700 Subject: Metatest 0.1.0 In-Reply-To: References: Message-ID: <1190130384.753009.142150@i13g2000prf.googlegroups.com> On Sep 18, 3:55 pm, Jonathan Fine wrote: > Hello > > This announcement also appears on the Metatest web sitehttp://metatest.sourceforge.net > > === > *** Metatest - a Python test framework > > Metatest is a simple and elegant Python framework for writing tests. > > Metatest is mostly about writing tests and by design is not tied to any > particular test runner. Hence the name. > > Here's how to write some tests using Metatest. We can think of the tests > as an executable specification. > > from metatest.py.mymod import plus, Point > > # Function plus adds two numbers. > plus(2, 2) == 4 > plus(2, '', _ex=TypeError) > > # Class Point represent a point in the plane. > p = Point(2, 5) > p.x == 2 > p.y == 5 > p.area == 10 > > And here's one way to run them. > > if __name__ == '__main__': > import metatest > metatest.run() > > It's not hard to write an adapter that will run these tests in a > different test runner framework. > > We gave a talk about Metatest at PyCon UK 2007 and here are the slides > (HTML). > http://www.pyconuk.org > http://metatest.sourceforge.net/doc/pyconuk2007/metatest.html > > Please visit Sourceforge to download Metatest. > http://sourceforge.net/project/showfiles.php?group_id=204046 > > -- > Jonathan Fine >From the HTML slides: Assertion tests are easy to write but report and run poorly. I tend to think this is a prejudice that leads to ever more ways to write tests perform test discoveries, invent test frameworks etc. When I thought about organizing my tests for EasyExtend I was seeking for a strategy being adapted to my own behaviour. The very first step I made when creating a new language, modifying a grammar rule, changing the Transformer etc. was starting an interactive shell and typing some commands. This is just checking out or smoke testing my application and I wanted to reproduce it. So I recorded the interactive shell session and replayed it as another shell session. I enabled to set breakpoints in the logged output and implemented a command for proceeding the replay. Then I discovered I actually wrote an interactive test runner. I don't have to care for all the exceptions being thrown in the session and don't care for cleanups but just assign parts of the session as tests using assert for getting an overview at the end. The only additonal command I implemented was raises to capture the side-effect of raising an exception. So I'm going to argue here that there isn't anything particular about writing/coding a test ( planning tests, specifying tests, reviewing a testspecification etc. are another issue ). Instead you can keep a seemingly unrelated practice and turn it into a test by a tiny signification. From theller at ctypes.org Fri Sep 7 13:58:00 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 07 Sep 2007 19:58:00 +0200 Subject: py2exe - change name of exe created In-Reply-To: <1189182302.680374.172940@k79g2000hse.googlegroups.com> References: <1189164934.705547.156670@r34g2000hsd.googlegroups.com> <1189165183.727542.47640@19g2000hsx.googlegroups.com> <1189182302.680374.172940@k79g2000hse.googlegroups.com> Message-ID: imageguy schrieb: [...] >> > Note that every thing works fine with this and creates an exe program >> > called >> > "myprogram.exe" >> >> > I would like to setup program to create an output called; >> > "MyBestProgram.exe" >> >> > IS that at all possible ? >> >> Yes. Use a 'dest_base' key in the dictionary, like so: >> >> > setup(windows = [{"script":"myprogram.py", >> > "icon_resources":[(0,"nabbitt.ico")], >> >> "dest_base": "MyBestProgram",> "other_resources": [(24,1,manifest)]} >> >> ... >> >> 'dest_base' is the basename of the destination program that py2exe creates. >> >> Thomas- Hide quoted text - >> >> - Show quoted text - > > Thanks. > I really appreciate the response. > Where would I find that in the docs ? Thought I had searched > everywhere. If you have searched everywhere then it isn't in the docs. You can probably learn a lot about py2exe when you try out and study the supplied samples; they are in the Lib\site-packages\py2exe\samples subdirectories. The next step would be to consult the source code ;-) The current maintainer of pyexe, Jimmy Retzlaff, seems to have disappeared from the net as it seems; I hope he is well. So, the current state of py2exe itself and the documentation is not so good; OTOH there is a wiki on www.py2exe.org where anyone can contribute tips tricks and docs. Thomas From steve at REMOVE-THIS-cybersource.com.au Tue Sep 25 08:45:30 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 25 Sep 2007 12:45:30 -0000 Subject: sorting a list numbers stored as strings References: Message-ID: <13fi0na7rhfl90d@corp.supernews.com> On Tue, 25 Sep 2007 12:46:54 +0800, Delaney, Timothy (Tim) wrote: > Carsten Haese wrote: > >> On Mon, 2007-09-24 at 19:58 +0800, Delaney, Timothy (Tim) wrote: >>> I'm sure that in some version of Python it would have given a >>> ValueError (due to the default radix being 0) but it appears to have >>> changed to a default radix of 10 somewhere along the way. >> >> Not even Python 1.5.2 seems to have a problem with leading zeroes: >> >> Python 1.5.2 (#1, Nov 6 1999, 14:53:40) [C] on sco_sv3 Copyright >> 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>>>> int("08") >> 8 > > Yep - appears I must have been misremembering from another language > (dunno which) or I misinterpreted the docs. I also remember something in Python about leading zeroes leading to "surprising" effects... ah, I got it! >>> int("020") 20 >>> 020 16 -- Steven. From deets at nospam.web.de Wed Sep 26 09:24:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Sep 2007 15:24:52 +0200 Subject: Test-driven development and code size References: <5ls95aF9pq3gU1@mid.uni-berlin.de> <87ejgmmgc2.fsf_-_@benfinney.id.au> Message-ID: <5lv4t4Faeqk8U1@mid.uni-berlin.de> Joel Hedlund wrote: >> test-driven development merely means that you take that test case and >> *keep it* in your unit test. Then, once you're assured that you will >> find the bug again any time it reappears, go ahead and fix it. > > My presumption has been that in order to do proper test-driven development > I would have to make enormous test suites covering all bases for my small > hacks before I could getting down and dirty with coding (as for example in > http://www.diveintopython.org/unit_testing). This of course isn't very > appealing when you need something done "now". But if I understand you > correctly, if I would formalize what little testing I do, so that I can > add to a growing test suite for each program as bugs are discovered and > needs arise, would you consider that proper test-driven development? (or > rather, is that how you do it?) Sounds good to me. IMHO there are two ways one gathers tests: - concrete bugs appear, and one writes a test that reproduces the bug & eventually after the fix runs smoothly - new features are planned/implemented, and the tests accompany them right from the start, to allow .. .well, to test them :) I always found it difficult to "just think" of new tests. Of course if you _start_ with TDD, point two is applied right from the start and should apply. Diez From sjmachin at lexicon.net Mon Sep 24 18:03:03 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Sep 2007 15:03:03 -0700 Subject: Newbie completely confused In-Reply-To: References: <1190434069.108503.281930@y42g2000hsy.googlegroups.com> Message-ID: <1190671383.685768.237010@d55g2000hsg.googlegroups.com> On Sep 25, 1:51 am, Jeroen Hegeman wrote: > > Your code does NOT include any statements that could have produced the > > above line of output -- IOW, you have not posted the code that you > > actually ran. > > Oh my, I must have cleaned it up a bit too much, hoping that people > would focus on the issue instead of the formatting of the output > strings! Did you miss your morning coffee??? The difference was not a formatting difference; it was complete absence of a statement, raising the question of what other non-obvious differences there might be. You miss the point: if it is obvious that the posted code did not produce the posted output (common when newbies are thrashing around trying to solve a problem), some of the audience may not bother trying to help with the main issue -- they may attempt to help with side issues (as I did with the fugly code bloat) or just ignore you altogether. > > > Your code is already needlessly monstrously large. > > Which I realised and apologised for beforehand. An apology does not change the fact that the code was needlesly large (AND needed careful post-linefolding reformatting just to make it runnable) and so some may not have bothered to read it. > > > And Python 2.5.1 does what? Strike 3. > > Hmm, I must have missed where it said that you can only ask for help > if you're using the latest version... You missed the point again: that your problem may be fixed in a later version. > In case you're wondering, 2.5.1 > is not _really_ that wide-spread as most of the older versions. I wasn't wondering. I know. I maintain a package (xlrd) which works on Python 2.5 all the way back to 2.1. It occasionally has possibly similar "second iteration goes funny" issues (e.g. when reading 120MB Excel spreadsheet files one after the other). You mention that removing some attributes from a class may make your code stop exhibiting cliff-face behaviour. If you can produce two versions of your code that actually demonstrate the abrupt change, I'd be quite interested in digging into it, to our possible mutual benefit. > > For handling the bit extraction stuff, either > [snip] > > (b) do a loop over the bit positions > > Now that sounds more useful. I'll give that a try. > I'm glad you found something possibly more useful in my posting :-) Cheers, John From listserver at tdw.net Thu Sep 6 11:29:47 2007 From: listserver at tdw.net (Tim Williams) Date: Thu, 6 Sep 2007 16:29:47 +0100 Subject: startswith( prefix[, start[, end]]) Query In-Reply-To: <46e00d7e$0$16413$426a74cc@news.free.fr> References: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> <46e00d7e$0$16413$426a74cc@news.free.fr> Message-ID: <9afea2ac0709060829y507806d6hc1bd94111a69b938@mail.gmail.com> On 06/09/07, Bruno Desthuilliers wrote: > > You may want to try with a regexp, but I'm not sure it's worth it (hint: > the timeit module is great for quick small benchmarks). > > Else, you could as well write your own testing function: > > def str_starts_with(astring, *prefixes): > startswith = astring.startswith > for prefix in prefixes: > if startswith(prefix): > return true > return false > > for line in f: > if str_starts_with(line, 'abc, 'de', 'xxx'): > # CODE HERE > Isn't slicing still faster than startswith? As you mention timeit, then you should probably add slicing to the pot too :) if astring[:len(prefix)] == prefix: do_stuff() :) From python at hope.cz Tue Sep 25 10:31:58 2007 From: python at hope.cz (Johny) Date: Tue, 25 Sep 2007 07:31:58 -0700 Subject: HTTPS request Message-ID: <1190730718.341771.215970@19g2000hsx.googlegroups.com> If I need to log in to a site using https protocol must I use certification file and key file? The class HTTPSConnection syntax is class HTTPSConnection( host[, port, key_file, cert_file]) and I do not know if it is nescessary or not. Thanks for help. L. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 28 06:26:33 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 28 Sep 2007 12:26:33 +0200 Subject: ValueError: too many values to unpack,>>> In-Reply-To: References: <5m24sfFatlbuU1@mid.uni-berlin.de> <46FBED79.6070207@comcast.net> <46fc09ae$0$22333$426a74cc@news.free.fr> Message-ID: <46fcd6ae$0$6780$426a74cc@news.free.fr> J. Clifford Dyer a ?crit : > On Thu, Sep 27, 2007 at 09:50:26PM +0200, Bruno Desthuilliers wrote > regarding Re: ValueError: too many values to unpack,>>>: >> Shawn Minisall a ?crit : (snip) >>> I did and it printed everything up until the 3rd line with 3 >>> numbers for deposits. I have since figured it out...the teacher >>> put in an extra tab after the last value so python thought it was >>> 4 values for three. I went back into the file and deleted the >>> extra tab after the 3rd number and saved it...now it's working >>> fine. I'm going to kill her... >> You'd better learn how to deal with "this-cant-happen-here" >> situation, because it's how it is in real-life. >> > > And preferably learn how to deal with it in your code, not in the > data that's given to you. Thanks for clarifying this point, which is of course what I meant. From tokland at gmail.com Sat Sep 15 13:20:48 2007 From: tokland at gmail.com (tokland at gmail.com) Date: Sat, 15 Sep 2007 17:20:48 -0000 Subject: how to join array of integers? In-Reply-To: <13eo0pbiab4spdf@corp.supernews.com> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <13eo0pbiab4spdf@corp.supernews.com> Message-ID: <1189876848.763453.8190@o80g2000hse.googlegroups.com> Grant Edwards ha escrito: > > Or, if you happen to like the itertools modules: > > > > from itertools import imap > > ",".join(imap(str, [1, 2, 3])) > > It's nice people have invented so many ways to spell the > builting "map" ;) Did you wonder why the Python developers bother to implement "imap" if "map" was already there? > >>> ",".join(map(str,[1,2,3])) > '1,2,3' Of course the result is the same, but "map" returns a list while "itertools.imap" returns an iterator. Fortunately, "map" will become lazy on Py3000: http://mail.python.org/pipermail/python-3000/2007-August/009207.html As you said, it won't be noticeable for short lists, but it's a good programming practice to use generators instead of lists (if you don't really need a list!) arnau From gagsl-py2 at yahoo.com.ar Mon Sep 10 04:49:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 10 Sep 2007 01:49:11 -0700 Subject: Python syntax wart In-Reply-To: <5ki2sdF3nr68U1@mid.individual.net> References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> <5ki2sdF3nr68U1@mid.individual.net> Message-ID: <1189414151.003351.229860@r34g2000hsd.googlegroups.com> On 9 sep, 08:14, Bjoern Schliessmann wrote: > How can a statement be two-dimensional? Like a two-dimensionalTuringMachine? Do you know the Befunge language? Program flow is not lineal but along a 2D grid. There are variants over toroids and more bizarre surfaces, even using 3D. "Befunge is believed to be the first two-dimensional, ASCII-based, general-purpose programming language." -- Gabriel Genellina From mensanator at aol.com Thu Sep 13 16:59:07 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 13 Sep 2007 13:59:07 -0700 Subject: Decimal formatting In-Reply-To: <1189716651.810481.260850@y42g2000hsy.googlegroups.com> References: <1189716651.810481.260850@y42g2000hsy.googlegroups.com> Message-ID: <1189717147.538624.189890@19g2000hsx.googlegroups.com> On Sep 13, 3:50 pm, Harlin Seritt wrote: > Cant believe I have to post this and get help... and can't believe I > couldnt Google it reasonably well enough... I need to take a float > variable and have it display as a string to always have two decimal > places: > > 12.3333 -> 12.33 > 1.0 -> 1.00 > etc... > > Anyone willing to help with this one? >>> a 12.33333 >>> print '%0.2f' % a 12.33 >>> a = 1 >>> print '%0.2f' % a 1.00 > > thanks, > > Harlin From http Thu Sep 20 19:30:04 2007 From: http (Paul Rubin) Date: 20 Sep 2007 16:30:04 -0700 Subject: I could use some help making this Python code run faster using only Python code. References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> Message-ID: <7xbqbwrk3n.fsf@ruckus.brouhaha.com> Python Maniac writes: > I am new to Python however I would like some feedback from those who > know more about Python than I do at this time. Use the array module and do 32-bit or 64-bit operations with it. See http://nightsong.com/phr/crypto/p3.py for a more serious encryption module written that way. From ben at benfinney.id.au Wed Sep 26 02:09:34 2007 From: ben at benfinney.id.au (Ben Finney) Date: Wed, 26 Sep 2007 16:09:34 +1000 Subject: setuptools without unexpected downloads Message-ID: <87ejgmklep.fsf@benfinney.id.au> Howdy all, The Python distutils has been built upon by setuptools, providing features asked for by many developers. One of these is the ability for the 'setup.py' program to declare package dependencies in a fairly standardised way, and determine if they're met before attempting to install the package. This is good for distributing one's software to folks whose operating system is stuck somewhere in the mid-20th century by not providing such a dependency system. However, one of the areas where setuptools clashes with existing package dependency systems is its default of *downloading* those packages declared as dependencies, and installing them in its own way getting in the way of the existing package dependency system. How can I, as the distributor of a package using setuptools, gain the benefits of dependency declaration and checking, without the drawback of unexpected and potentially unwanted download and installation? I know that a user can choose (if they've read the mass of setuptools documentation) to disallow this download-and-install-dependencies behaviour with a specific invocation of 'setup.py'. But how can I disallow this from within the 'setup.py' program, so my users don't have to be aware of this unexpected default behaviour? -- \ "I disapprove of what you say, but I will defend to the death | `\ your right to say it." -- Evelyn Beatrice Hall, _The Friends | _o__) of Voltaire_, 1906 | Ben Finney From python at cx.hu Tue Sep 4 16:36:37 2007 From: python at cx.hu (Ferenczi Viktor) Date: Tue, 4 Sep 2007 22:36:37 +0200 Subject: doctest and decorators In-Reply-To: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> Message-ID: <200709042236.37712.python@cx.hu> > I assume this is a FAQ, but I couldn't find much helpful information > googling. I'm having trouble with doctest skipping my functions, if I'm > using decorators (that are defined in a separate module). If I'm > understanding what is happening correctly, it's because doctest checks if > the function's func_global attribute is the same as the module's __dict__ > attribute. The decorator in question returns a wrapping function, though, > so this check fails. > What are some solutions to this? I can define __test__, but it seems rather > cumbersome. Please take a look at the documentation of the functools standard module in the Python manual, especially the wraps decorator. It could probably help. Viktor From kollasb+news at gmail.com Sun Sep 23 01:57:58 2007 From: kollasb+news at gmail.com (Suresh Babu Kolla) Date: Sun, 23 Sep 2007 05:57:58 GMT Subject: subprocess -popen - reading stdout from child - hangs In-Reply-To: <1190518129.356844.242710@19g2000hsx.googlegroups.com> References: <1190518129.356844.242710@19g2000hsx.googlegroups.com> Message-ID: gregpinero at gmail.com wrote: > Let's say I have this Python file called loop.py: > > import sys > print 'hi' > sys.stdout.flush() > while 1: > pass > > And I want to call it from another Python process and read the value > 'hi'. How would I do it? > > So far I have tried this: > >>>> proc = subprocess.Popen('python /home/chiefinnovator/loop.py',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE) >>>> proc.stdout.read() > From python documentation `read([size])' Read at most SIZE bytes from the file (less if the read hits `EOF' before obtaining SIZE bytes). If the SIZE argument is negative or omitted, read all data until `EOF' is reached. The bytes are returned as a string object. An empty string is returned when `EOF' is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an `EOF' is hit.) Note that this method may call the underlying C function `fread()' more than once in an effort to acquire as close to SIZE bytes as possible. Also note that when in non-blocking mode, less data than what was requested may be returned, even if no SIZE parameter was given. read call in your code is waiting for EOF, since the script never exits EOF is not reached. Change read code to proc.stdout.readline() or remove while 1 loop from loop.py. HTH Kolla From mccredie at gmail.com Mon Sep 10 01:29:38 2007 From: mccredie at gmail.com (Matt McCredie) Date: Sun, 9 Sep 2007 22:29:38 -0700 Subject: help - error when trying to call super class method In-Reply-To: <584090.28836.qm@web51105.mail.re2.yahoo.com> References: <584090.28836.qm@web51105.mail.re2.yahoo.com> Message-ID: <9e95df10709092229k321d46cbvaded47cdddc1362@mail.gmail.com> > I am trying to extend list class to build a stack class -- see code below--- > but I got an error when I try to call len method from list class here.. why? > Thanks in advance! Jeff did a good job of answering your questions. I just wanted to note that your pop is broken, but that doesn't matter since list already has a pop method that will do what you want. Actually it has a push method that does what you want too, it is called `append'. If you really want a push method, you could just do this: [code] >>> class Stack(list): ... push = list.append >>> s = Stack() >>> s.push(1) >>> s.push(2) >>> s.push(3) >>> s.pop() 3 >>> s.pop() 2 >>> s.pop() 1 [/code] Matt From no at spam.com Mon Sep 10 14:47:40 2007 From: no at spam.com (Farshid Lashkari) Date: Mon, 10 Sep 2007 11:47:40 -0700 Subject: C API (embedded Python): How to get and set named variables In-Reply-To: <1189447804.880483.175290@50g2000hsm.googlegroups.com> References: <1189447804.880483.175290@50g2000hsm.googlegroups.com> Message-ID: <%igFi.98606$Vk6.77403@newsfe07.phx> mrabens at gmail.com wrote: >>From the C API (I'm using Python embedded), how can I get and set the > value of named variables? Right now, I'm using hacks like > PyRun_SimpleString("foobar = 12\n"), but I'd really like to access the > named objects directly. > You can use the following C functions to set/get named attributes of an object: PyObject_SetAttrString PyObject_GetAttrString If the attributes belong to the global scope of a module, then you can use "PyImport_AddModule" to get a handle to the module object. For example, if you wanted to get the value of an integer in the __main__ module named "foobar", you would do the following: PyObject *m = PyImport_AddModule("__main__"); PyObject *v = PyObject_GetAttrString(m,"foobar"); int foobar = PyInt_AsLong(v); Py_DECREF(v); You will probably want to add some error checking in your code. -Farshid From gh at gregor-horvath.com Tue Sep 11 13:26:26 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Tue, 11 Sep 2007 19:26:26 +0200 Subject: Python code-writing for the blind. Was (Re: newbie: stani's python editor if-else) In-Reply-To: <1189531123.283413.160870@22g2000hsm.googlegroups.com> References: <1189484688.520933.25000@22g2000hsm.googlegroups.com> <46e6aa30$0$22433$426a74cc@news.free.fr> <1189531123.283413.160870@22g2000hsm.googlegroups.com> Message-ID: madzientist schrieb: > > Is Python a bad choice for the blind programmer, as a result of a > tight linkage between visual aspects of the code and its function ? I > wish the site blindprogramming.com weren't so lifeless... There was a thread regarding blind people and python indentation shortly: http://groups.google.com/group/comp.lang.python/browse_thread/thread/80654a87bfa89e3b Gregor From zentraders at gmail.com Tue Sep 4 18:39:21 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 04 Sep 2007 15:39:21 -0700 Subject: Python is overtaking Perl In-Reply-To: <1188925737.869396.316750@19g2000hsx.googlegroups.com> References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> <20070904024908.b8aca60c.sulsa@gazeta.pl> <1188869347.102325.119830@w3g2000hsg.googlegroups.com> <1188873133.137684.147260@r29g2000hsg.googlegroups.com> <1188925737.869396.316750@19g2000hsx.googlegroups.com> Message-ID: <1188945561.400276.186770@k79g2000hse.googlegroups.com> >So, all the decline means is that the number of searches > for "Python programming" releative to all searches done is declining. Which makes sense. There are an many python tutorial/code snippet sites, sites that list those type of python sites, as well as the python.org site which means that a Google search is becoming less and less necessary. I think the language is gaining more people because it's an excellent language and don't really care what rank it has. From paul.hankin at gmail.com Wed Sep 26 18:25:09 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 26 Sep 2007 22:25:09 -0000 Subject: ~ bit-wise unary operator In-Reply-To: References: Message-ID: <1190845509.225196.88460@19g2000hsx.googlegroups.com> On Sep 26, 11:14 pm, Ladislav Andel wrote: > Hello, > why ~ bit-wise unary operator returns -(x+1) and not bit inversion of > the given integer? > > example: > a = 7978 > a = ~a > python returns -7979 > > but I need to get back 57557 as in C language. > > which is also in binary > 0001111100101010 > and inverted > 1110000011010101 > > Is here any other operator or do I have to write it on my own? The size of int is an implementation detail in C, so you may not get 57557 (in fact, you're only likely to get that answer if a is an unsigned short on any modern architecture. But if that's what you want, try def invert(x): return ~x & 0xffff -- Paul Hankin From nutsbreaker4 at gmail.com Sat Sep 15 14:04:38 2007 From: nutsbreaker4 at gmail.com (nutsbreaker4 at gmail.com) Date: Sat, 15 Sep 2007 11:04:38 -0700 Subject: World's most popular traveling destinations Message-ID: <1189879478.488113.36740@k79g2000hse.googlegroups.com> http://world-traveling-destinations.blogspot.com/ From gagsl-py2 at yahoo.com.ar Wed Sep 12 23:52:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Sep 2007 00:52:14 -0300 Subject: MemoryError on reading mbox file References: <1189589259.662667.149730@w3g2000hsg.googlegroups.com> <1189607986.628841.215930@50g2000hsm.googlegroups.com> Message-ID: En Wed, 12 Sep 2007 11:39:46 -0300, Istvan Albert escribi?: > On Sep 12, 5:27 am, Christoph Krammer > wrote: > >> string = self._file.read(stop - self._file.tell()) >> MemoryError > > This line reads an entire message into memory as a string. Is it > possible that you have a huge email in there (hundreds of MB) with > some attachment encoded as text? Printing start,stop,stop-start inside that method would be an easy way to find if that is the case. The following idea could help to fix it - at least, avoiding to read the whole message at once: self._message_factory will eventually call the mailbox.Message constructor, which accepts a file object too (instead of a huge string). In that same module there is an utility class, _PartialFile ("A read-only wrapper of part of a file"). _mboxMMDF.get_file() does return a _PartialFile object, so I'd try this code (untested!): def get_message(self, key): """Return a Message representation or raise a KeyError.""" msg = self._message_factory(self.get_file(key, True)) msg.set_from(msg.get_unixfrom()[5:]) return msg -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Tue Sep 25 22:49:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Sep 2007 23:49:22 -0300 Subject: Regular Expressions: Can't quite figure this problem out References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> <496954360709251421l578b9dfdwcc0e67d293ede1f3@mail.gmail.com> Message-ID: En Tue, 25 Sep 2007 18:21:08 -0300, Robert Dailey escribi?: > One thing I noticed is that it is placing an arbitrary space between " > and > />. For example: > > > > > Notice that there's a space between "image" and /> Just remove the space in the replacement string: >> py> print re.sub(r"<(\w+)([^>]*)>", r"<\1\2 />", source) ^ | -- Gabriel Genellina From apardon at forel.vub.ac.be Thu Sep 27 02:49:31 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Sep 2007 06:49:31 GMT Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> <1190799759.367001.106400@r29g2000hsg.googlegroups.com> <87fy11lo22.fsf@mulj.homelinux.net> <1190804538.469582.96950@22g2000hsm.googlegroups.com> <1190814263.104358.158090@n39g2000hsh.googlegroups.com> Message-ID: On 2007-09-26, Mark Summerfield wrote: > On 26 Sep, 13:22, Antoon Pardon wrote: >> >> Well you should decide what you want. In a previous exchange one of the >> things that was wanted was that you could already seed a tree by using >> key word arguments so that you could do the following: >> >> t=Tree(a=15, b=30) >> >> which would be equivallent to: >> >> t=Tree() >> t.update(a=15,b=30) >> >> But with the above proposal >> >> t=Tree(cmp=cmp) >> >> is not equivallent to >> >> t=Tree() >> t.update(cmp=cmp) >> >> So it seems the API needs some more sorting out. > > I think you missed some of the previous postings. That is possible. > > The sorteddict API that has emerged so far is (1) apart from the > constructor, everything is identical to dict, (2) the constructor > takes the same args as sorted(), so if you want to seed with a dict or > with keywords you write sorteddict(dict(a=1,b=2), ...), (or you could > create a sorteddict and use update() since that takes the same args as > dict's constructor). > > Could your AVLTree support cmp and keys and reverse? It already supports cmp. Although for the moment it is done by subclassing. Like the following. class myTree(AVLTree): @staticmethod def cmp(a, b); return .... I don't think adding support for keys will be difficult but it may be tedious. I would prefer not to support reverse because the effect can be acquired by the other two and in contradiction with sorting, I think using it will slow things down instead of speeding things up. -- Antoon Pardon From semanticist at gmail.com Mon Sep 24 21:27:19 2007 From: semanticist at gmail.com (Miles) Date: Mon, 24 Sep 2007 21:27:19 -0400 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> Message-ID: On 9/24/07, Robert Dailey wrote: > Hi, > > I'm attempting to create a regular expression that removes redundancy in > empty XML elements. For example: > > > > The regular expression would convert the XML above into: > > If you can guarantee that the XML is well-formed, then this should work: pattern = r'<([^/>][^>]*(?]+>' replace = r'<\1/>' -Miles From hat at se-162.se.wtb.tue.nl Tue Sep 18 06:48:49 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 18 Sep 2007 12:48:49 +0200 Subject: How can I know how much to read from a subprocess References: <1190070896.332844.23080@22g2000hsm.googlegroups.com> <1190072376.600475.254260@y42g2000hsy.googlegroups.com> Message-ID: On 2007-09-17, spam.noam at gmail.com wrote: > It seems that another solution is gobject.io_add_watch, but I don't > see how it tells me how much I can read from the file - if I don't > know that, I won't know the argument to give to the read() method in > order to get all the data: > > http://www.pygtk.org/docs/pygobject/gobject-functions.html#function-gobject--io-add-watch > Usually, gobject only tells you that data is there (that is all it knows). Therefore a read(1) should be safe. If that is too slow, consider os.read() which reads all data available (afaik, never tried it myself). Albert From gagsl-py2 at yahoo.com.ar Sat Sep 29 02:04:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Sep 2007 03:04:09 -0300 Subject: Bug: spurious indentation error References: <33dffc910709282143y76151e66r2f8641ed2972661a@mail.gmail.com> Message-ID: En Sat, 29 Sep 2007 01:43:53 -0300, Mridula Ramesh escribi?: > Lol, nope, I checked today too, and it happened again. Try running this > as a > script, not from the prompt - I got a SyntaxError on line 10 as expected. After correcting it, I got an `IndentationError: expected an indented block` on line 23, due to a long line being wrapped onto the next line. A syntax error may be reported some lines later than the actual mistake, if the following lines build a good construct. For example, a missing close parenthesis. -- Gabriel Genellina From steve at holdenweb.com Tue Sep 18 11:51:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Sep 2007 11:51:20 -0400 Subject: Using pseudonyms (was Re: Python 3K or Python 2.9?) In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46ee2d9d$0$26213$426a74cc@news.free.fr> <46ef893c$0$21882$426a34cc@news.free.fr> Message-ID: <46EFF3F8.7000303@holdenweb.com> Aahz wrote: > In article <46ef893c$0$21882$426a34cc at news.free.fr>, > Bruno Desthuilliers wrote: >> Aahz a ?crit : >>> In article <46ee2d9d$0$26213$426a74cc at news.free.fr>, >>> Bruno Desthuilliers wrote: >>>> But what, given that I'm an AOL user still thinking it's kewl to hide >>>> behind a pseudo, what else would you expect ? >>> What exactly is a "pseudo", pray tell? >> Sorry : a pseudonym (a nickname). > > You apparently missed the thrust of my sarcasm. You can't tell what is > or is not a pseudonym online. For all I know, "Bruno Desthulliers" is a > pseudonym. While I recognize that there is some social advantage to > linking consistent identifiers with people, I have I think understandable > irritation with people who insist that names follow certain patterns. > > (For those joining only recently, my full legal name is "Aahz", which I > changed from my former name precisely because of attitudes like Bruno's.) > ... coupled with a certain bloody-mindedness that forces you to rub people's noses in your ability to choose to do so? ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From xiaoyisheng at gmail.com Thu Sep 13 04:48:45 2007 From: xiaoyisheng at gmail.com (Pacino) Date: Thu, 13 Sep 2007 08:48:45 -0000 Subject: read part of jpeg file by pure python In-Reply-To: References: <1189671634.712690.154580@o80g2000hse.googlegroups.com> Message-ID: <1189673325.083163.210630@d55g2000hsg.googlegroups.com> On 9 13 , 4 43 , Laurent Pointal wrote: > Pacino a ?crit : > > > Hi, everyone, > > > I am wondering whether it's possible to read part (e.g. 1000*1000) of > > a huge jpeg file (e.g. 30000*30000) and save it to another jpeg file > > by pure python. I failed to read the whole file and split it, because > > it would cost 2GB memory. > > > Can anyone help me? Any comments would be appreciated. > > > Thanks. > > > Robert > > Just reading parts of the *file* is easy (see tell() seek() and read() > methods on files). > But to extract a part of the *picture*, you must uncompress the picture > in memory, grab the sub-picture, and save it back - generally with > compression. I can't see how you can bypass the uncompress/compress > phases and the corresponding memory use. > > A+ > > Laurent. The most difficult part is the uncompress part. I don't want the whole picture to be uncompressed in the memory, because it will consume a lot of memory (2GB, as I mentioned). My goal is to uncompress part of the picture into the memory. I just read some article on this subject (http://mail.python.org/ pipermail/image-sig/1999-April/000713.html) , but haven't test it out yet. Robert From bdesth.quelquechose at free.quelquepart.fr Sat Sep 22 09:07:03 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 22 Sep 2007 15:07:03 +0200 Subject: Nested For and While Statements In-Reply-To: <1190666585.281623.228920@22g2000hsm.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190664112.564911.13480@57g2000hsv.googlegroups.com> <1190666585.281623.228920@22g2000hsm.googlegroups.com> Message-ID: <46f82621$0$9017$426a34cc@news.free.fr> koutoo at hotmail.com a ?crit : (snip) > My actual code has different variables, but thanks for pointing that > out. I'm so used to coding in VB, where indenting isn't a problem, so > all this indenting is new to me how Python wants it dictated. statement: block line 1 block line 2 # end statement block I made > the changes and still get an error at the same point after the second > For statement? So: > > While : > Code under while > More under while. > > For (x) > Part of x > Last of x > > For(y) > Part of y > Still part of y > last part of y. # end for(y) > New line part of x #where does this belong? # end for(x) > Last line under while not in For #Should go under While, right? # end while From idzwan.nizam at gmail.com Thu Sep 6 14:34:38 2007 From: idzwan.nizam at gmail.com (idzwan.nizam at gmail.com) Date: Thu, 06 Sep 2007 11:34:38 -0700 Subject: library to launch program in linux Message-ID: <1189103678.484278.321650@r34g2000hsd.googlegroups.com> Hi there, I'm a new user. What library should I use so that I can launch program in linux using python? Thank you in advance. From ricaraoz at gmail.com Sun Sep 2 07:36:35 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 08:36:35 -0300 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1i3s2rz.1pkz4z1i1e3a1N%aleax@mac.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <1i3rxit.1750ghi14bbcm3N%aleax@mac.com> <1i3s2rz.1pkz4z1i1e3a1N%aleax@mac.com> Message-ID: <46DAA043.5010300@bigfoot.com> Alex Martelli wrote: > Ricardo Ar?oz wrote: > ... >>>> We should remember that the level >>>> of security of a 'System' is the same as the level of security of it's >>>> weakest component, > ... >> You win the argument, and thanks you prove my point. You typically >> concerned yourself with the technical part of the matter, yet you >> completely ignored the point I was trying to make. > > That's because I don't particularly care about "the point you were > trying to make" (either for or against -- as I said, it's a case of ROI > for different investments [in either security, or, more germanely to > this thread, reliability] rather than of useful/useless classification > of the investments), while I care deeply about proper system thinking > (which you keep failing badly on, even in this post). And here you start, followed by 'F- at system thinking', 'glib and false assertions', 'falsities', etc. I don't think you meant anything personal, how could you, we don't know each other. But the outcome feels like a personal attack instead of an attack on the ideas exposed. If that's not what you intended, you should check your communication abilities and see what is wrong. If that is what you meant well... So I will not answer your post. I'll let it rest for a while till I don't feel the sting, then I'll re-read it and try to learn as much as I can from your thoughts (thank you for them). And even though some of your thinking process I find objectionable I will not comment on it as I'm sure it will start some new flame exchange which will have a lot to do with ego and nothing to do with python. From bloominator at hotmail.com Thu Sep 13 22:50:39 2007 From: bloominator at hotmail.com (Gary Bloom) Date: Thu, 13 Sep 2007 22:50:39 -0400 Subject: PIL DPI trouble Message-ID: Howdy! I notice that the PIL has trouble playing with the DPI of other programs and image standards: when I create a file with Paint Shop Pro or Photoshop, the PIL routines can't properly recognize the DPI. And when I create an image file (via the save method) of PIL, setting the DPI, those same two programs can't read the DPI as set by them. Is there a workaround for this? Other than this one issue, I have found the PIL to be a BLAST! :) Thanks! Gary Bloom -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at hope.cz Fri Sep 28 02:02:25 2007 From: python at hope.cz (Johny) Date: Thu, 27 Sep 2007 23:02:25 -0700 Subject: Python and SSL Message-ID: <1190959345.041723.108130@k79g2000hse.googlegroups.com> I need to use Python with SSL comunication betweeen servers. (I use hhtplib but I think urllib2 can also be used ) I think I need to use SSL root certificate and tell a program to trust this certificate. But how can I tell my Python program to trust my SSL certificate? When I tried before I received the error 503 Thank you for help L, From blackmh at gmail.com Sun Sep 2 15:22:49 2007 From: blackmh at gmail.com (Kveldulv) Date: Sun, 02 Sep 2007 12:22:49 -0700 Subject: Glade + Python = No GUI In-Reply-To: <46db09e1$0$7697$9b4e6d93@newsspool2.arcor-online.net> References: <1188750465.530463.271750@22g2000hsm.googlegroups.com> <46db09e1$0$7697$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1188760969.316987.214410@w3g2000hsg.googlegroups.com> On Sep 2, 9:07 pm, Wildemar Wildenburger wrote: > Kveldulv wrote: > > When interrupted, I get > > > File "gui.py", line 11, in > > gtk.main() > > Ah, I see now. Thats just telling you that *you* interrupted the > function/method/whateverthatis. > > > When GUI coded manually, all works. > > Hence: Something in your (generated) code or XML file is corrupt or > missing. Perhaps some sort of show() call or attribute. I really only > have marginal experience with pygtk so I'm just stabbing at thin air. > > sorry :( > /W I sorted it out and you're right. I didn't found out why this thing didn't work since it's c/pasted straight from the book I'm learning from but this did the trick: class TwoButtonsGUI: def __init__(self): xml = gtk.glade.XML("buttons.glade") self.window = xml.get_widget("window1") self.window.show() etc Thanks for help! From tim at tdw.net Fri Sep 28 08:29:40 2007 From: tim at tdw.net (Tim Williams) Date: Fri, 28 Sep 2007 13:29:40 +0100 Subject: recipient validation with smtplib In-Reply-To: <46FCEA9E.3030700@chamonix.reportlab.co.uk> References: <46FCE387.9070601@chamonix.reportlab.co.uk> <9afea2ac0709280433n361ce4fx2a26a05de2b1b1ae@mail.gmail.com> <46FCEA9E.3030700@chamonix.reportlab.co.uk> Message-ID: <9afea2ac0709280529o349a004mb5f2295a8f1f5907@mail.gmail.com> On 28/09/2007, Robin Becker wrote: > Tim Williams wrote: > > On 28/09/2007, Robin Becker wrote: > >> Is there a way to use smtplib to get recipient validation. I can use smtplib > >> quite happily to send emails using the locahost's sendmail, but sendmail is just > >> fire and forget, so some bad addresses eg idiot at www.dingo.zzz don't cause any > >> error in the sending application. I know some smtp setups do enforce recipient > >> validation, but it doesn't seem terribly easy to do this with sendmail. I > >> wondered if there were some way to do this in python? > > > > There is no way of validating *every* email address you send to using > > SMTP alone. Some servers accept every address and bounce later - as > > you have found out. So for the purpose of the SMTP client, or relaying > > server, the address is valid at sending time to those servers. > > > > Checking DNS for MX records is a possibility for removing some bad > > addresses, but it's not fool proof as the RFCs don't require MX > > records to exist for a domain to be able to receive email. If no MX > > records are present, one (and only one!) IP address returned from the > > domain's A record(s) should be tried. > > > > HTH :) > Thanks, it's at least ammunition for me to say it cannot easily be done. I found > this milter > > http://www.jmaimon.com/sendmail/callahead-milter/ > > but I think this will cause every send to be checked which is probably not what > we need. Hmm, call-ahead functions just initiate the first part of the SMTP dialogue - to the RCPT TO, unless you cache the results so that the call-ahead only checks each address once a day or so there is no benefit. Without caching it will just slow down sending process as you will get 1.5 SMTP conversations per outgoing message instead of just 1. However, they still won't catch invalid email addresses when the server accepts all addresses* and bounces later. * all addresses = all addresses on domains local to that server. I have written functions like this in the past for outbound/inbound (recipient/sender) address checking, using combinations of SMTP dialogue, DNS and port checking, bounce-collection, SPF and other techniques over the years. There is no guaranteed way of checking that all email addresses in your list are either VALID or INVALID. Valid email addresses can get refused/bounce for a variety of reasons, and invalid addresses sometimes get accepted/don't bounce at all. You should work on either a best-effort basis, running some checks but accepting that its not foolproof -OR- use no checks at all knowing that most invalid email addresses will be handled correctly by the SMTP processes HTH :) From kib2 at free.fr Sat Sep 8 18:03:47 2007 From: kib2 at free.fr (tool69) Date: Sun, 09 Sep 2007 00:03:47 +0200 Subject: Parsing nested constructs In-Reply-To: References: <46e308d3$0$9153$426a74cc@news.free.fr> Message-ID: <46e31bf8$0$26727$426a34cc@news.free.fr> David a ?crit : > On 9/8/07, tool69 wrote: >> Hi, >> >> I need to parse some source with nested parenthesis, like this : >> > > If this is exactly how your data looks, then how about a loop which > searches for "{item" and the following "}"? You can use the "find" > string method for that. > > Otherwise, if the items don't look exactly like "{item", but the > formatting is otherwise exactly the same as above, then look for lines > that have both "{" and "}" on them, then get the string between them. > > Otherwise, if { and } and the item aren't always on the same line, > then go through the string character by character, keep track of when > you encounter "{" and "}". When you encounter a "}" and there was a > "{" before (ie, not a "}"), then get the string between the "{" and > the "}" Hi David, thanks for answering, I will choose the last one as my strings are not on the same line and may contain a lot of stuff inside. cheers, 6TooL9 From redtiger84 at googlemail.com Wed Sep 12 10:18:21 2007 From: redtiger84 at googlemail.com (Christoph Krammer) Date: Wed, 12 Sep 2007 14:18:21 -0000 Subject: MemoryError on reading mbox file In-Reply-To: References: <1189589259.662667.149730@w3g2000hsg.googlegroups.com> Message-ID: <1189606701.345077.213410@d55g2000hsg.googlegroups.com> On 12 Sep., 12:20, David wrote: > It may be that Python's garbage collection isn't keeping up with your app. > > You could try periodically forcing it to run. eg: > > import gc > gc.collect() I tried this, but the problem is not solved. When invoking the garbage collection after every loop run, the amount of memory indicated by top stays the same for a very long time until at some point (at different messages), while it is executing the loop header, the memory increases until it hits 100% and swap hit also 100% => MemoryError Can there be a problem within the mailbox module while processing too large files? Regards, Christoph From davigoli at gmail.com Mon Sep 24 20:53:46 2007 From: davigoli at gmail.com (David) Date: Tue, 25 Sep 2007 00:53:46 -0000 Subject: PIL GIF transparency Message-ID: <1190681626.499676.14620@n39g2000hsh.googlegroups.com> Hello alll, Apologies if this isn't the correct list. I'm getting my feet wet with the Python Imaging Library (PIL) 1.1.6 on Python 2.5.1. I have played around quite a bit with transparent GIFs, and from what I can tell, PIL should support what I want to do - except I can't seem to get it to work. I have a large number of smallish icons (GIFs with transparency) that I'd like to tile into a grid in one large GIF image. The background color of the image should be GIF-transparent. Currently, I can set it to be white or black or any other color I want, just not transparent. My current code: import os, sys from PIL import Image, ImageColor # size in pixels of each row/col ROWSIZE = 50 COLSIZE = 50 # maxwidth of sprite grid SPRITEWIDTH = 20 MAXWIDTH = COLSIZE*SPRITEWIDTH FILENAME = '/static/images/icons.gif' def merge(): pwd = os.getcwd() imagePath = os.path.join(pwd, 'images') # Somehow, I need to ensure the palette used in the sprite image # is the same as the individual icons sprites = Image.new('RGBA', (MAXWIDTH, MAXWIDTH), (253,253,253,0)) sprites.putalpha(0) palette = None colors = [] col = 10 row = 10 for f in os.listdir(imagePath): try: im = Image.open(os.path.join(imagePath, f)) if im.size[0] <= 20 and im.size[1] <= 20 and im.format == 'GIF': sprites.paste(im.copy(), (col, row)) print 'url(/static/images/%s) => url(%s) -%dpx -%dpx' % (f, FILENAME, col, row) col += COLSIZE if col >= MAXWIDTH: row += ROWSIZE col = 10 if row >= sprites.size[1]: break except IOError, ex: pass sprites = sprites.crop((0,0,MAXWIDTH, row)).point(lambda pt: pt == (253, 253, 253, 0) and 0 or pt) return sprites So this code is obviously littered with the detritus of failed attempts to get transparency to work. Has anyone out there had any experience with this? Thanks, David From ivonet at gmail.com Fri Sep 21 16:20:00 2007 From: ivonet at gmail.com (Ivo) Date: Fri, 21 Sep 2007 22:20:00 +0200 Subject: Resolving windows shortcut to url In-Reply-To: <46f422d8$0$3030$e4fe514c@dreader31.news.xs4all.nl> References: <46f422d8$0$3030$e4fe514c@dreader31.news.xs4all.nl> Message-ID: <46f4268d$0$3030$e4fe514c@dreader31.news.xs4all.nl> Ivo wrote: > Richard Townsend wrote: >> If I have a windows shortcut to a URL, is there a way to get the URL >> in a Python app? >> >> I found some code that uses pythoncom to resolve shortcuts to local >> files, but I haven't found any examples for URLs. >> >> The PyWin32 help mentions the PyIUniformResourceLocator Object, but I >> couldn't find an example of how to use it. >> > do you mean a *.lnk file or a *.url file? if an *.url file just open it as a properties file (ConfigParser) because it looks something like: [InternetShortcut] URL=http://ivonet.nl/ IDList= IconFile=http://ivonet.nl/favicon.ico IconIndex=1 [{000214A0-0000-0000-C000-000000000046}] Prop3=19,2 From perl4hire at softouch.on.ca Thu Sep 13 11:39:22 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Thu, 13 Sep 2007 11:39:22 -0400 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: Richie Hindle wrote: >> [Amer] >> #!/usr/bin/python >> [...] On my home PC [...] >> [Thu Sep 13 04:16:03 2007] [error] [client 0.0.0.0] (OS 2)The system >> cannot find the file specified. > > That's because on your home PC Python is somewhere like > C:\Python25\python.exe, not /usr/bin/python. > > Are you sure /usr/bin/python is correct for your hosting environment? > It's my understanding that the Windows shell doesn't pay much attention to the shebang line if the file type is associated with the proper application. But I tried your suggestion and got the same results. -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From domma at procoders.net Mon Sep 3 09:06:57 2007 From: domma at procoders.net (Achim Domma) Date: Mon, 03 Sep 2007 06:06:57 -0700 Subject: 400 Bad Request calling urllib2.urlopen() Message-ID: <1188824817.761125.190520@k79g2000hse.googlegroups.com> Hi, I have an url which redirects the client to another url. If I paste the url into a browser, it works fine. If I open it via urllib2.urlopen() I get the following error: Traceback (most recent call last): File "...\crawlRawDocuments.py", line 16, in body = urlopen(url).read() File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 412, in error result = self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 575, in http_error_302 return self.parent.open(new) File "C:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 418, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 499, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 400: Bad Request I'm using Python 2.5.1 and Google did not help. Any hint on how to fix or debug this problem? regards, Achim From tjreedy at udel.edu Thu Sep 20 14:29:10 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Sep 2007 14:29:10 -0400 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com><1190263363.496695.83300@57g2000hsv.googlegroups.com> <7xwsulv0y4.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xwsulv0y4.fsf at ruckus.brouhaha.com... | It does sound like removing the GIL from CPython would have very high | costs in more than one area. Is my hope that Python will transition | from CPython to PyPy overoptimistic? I presume you mean 'will the leading edge reference version transition... Or more plainly, "will Guido switch to PyPy for further development of Python?" I once thought so, but 1) Google sped the arrival of Py3.0 by hiring Guido with a major chunk of time devoted to Python development, so he started before PyPy was even remotely ready (and it still is not); and 2) PyPy did not focus only or specifically on being a CPython replacement but became an umbrella for a variety of experiment (including, for instance, a Scheme frontend). From luismgz at gmail.com Mon Sep 24 21:36:38 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: Tue, 25 Sep 2007 01:36:38 -0000 Subject: TRying to import files from my folder not pythons lib folder In-Reply-To: References: <1190395964.541835.114350@50g2000hsm.googlegroups.com> <1190396569.732154.234270@r29g2000hsg.googlegroups.com> <1190595699.093793.100960@w3g2000hsg.googlegroups.com> Message-ID: <1190684198.266529.85020@y42g2000hsy.googlegroups.com> On Sep 24, 5:00 am, "Gabriel Genellina" wrote: > En Sun, 23 Sep 2007 22:01:39 -0300, Luis M. Gonz?lez > escribi?: > > > This is exactly what I did, but I have a new problem now: > > After setingPYTHONPATHI'm no longer able to start IDLE from the > > start menu. > > It seems the system cannot find the file. > > But if I eliminatePYTHONPATH, everything works as it used to. > > > I setPYTHONPATHbecause I wanted to import any existing file in my > > desktop without having to use sys.path.append... > > It works when using the command line but strangely, something get > > messed up with IDLE. > > Any hint? > > Perhaps a python module in your desktop has a name conflicting with a > standard module? > > - On the Start menu, navigate to the IDLE item, but dont click it. > - RIGHT click on it, and select Properties. Copy the Destination field. > Should be something like "C:\Python25\Lib\idlelib\idle.bat" > - Open a cmd window (console), paste the above text and press Enter. > - Almost certainly you'll get an error; post here the full error and > traceback. > > -- > Gabriel Genellina I solved the problem! You were right. It seems there was a module that was causing problems, although I don't know which one... I just moved all the .py files on my desktop to a new folder, and everything worked just fine. The list of .py files in my desktop were: 'code.py', 'code2.py', 'code22.py', 'code3.py', 'draft.py', 'flups.py', 'forma.py', 'fx.py', 'nuevo.py', 'nwind', 'ops', 'pages.py', 'qqq.py', 'sample.py', 'ses.py', 'sess.py', 'sess2.py', 'soup.py', 'style.py', 'test_session.py', 'up.py', 'up2.py', 'ww.py', 'xx.pyw', 'xx.rsrc.py', 'xxxx.py' Any idea of which one was causing trouble? Gracias, che! Luis From ebgssth at gmail.com Mon Sep 17 03:25:22 2007 From: ebgssth at gmail.com (js) Date: Mon, 17 Sep 2007 16:25:22 +0900 Subject: A short question about non-ascii characters in list In-Reply-To: <1190006587.185218.168340@22g2000hsm.googlegroups.com> References: <1190006587.185218.168340@22g2000hsm.googlegroups.com> Message-ID: Thank you for your quick reply. > It's intentional. __str__ of a list uses the __repr__ of its > elements. This helps reduce confusion (e.g., between ['a', 'b, c'] > and ['a, b', 'c']). That's make sence, but it's also true that sometimes we want to see the contents of a list in pretty format. So for now I need to write and use crappy mylist like this. class mylist(list): def __str__(self): return '[' + ', '.join(self) + ']' l = mylist([u"???", u"???", u"???"]) print unicode(l) very ugly, but just works. From kishore at mindriver-it.com Tue Sep 25 05:24:59 2007 From: kishore at mindriver-it.com (kishore at mindriver-it.com) Date: Tue, 25 Sep 2007 14:54:59 +0530 Subject: URGENT REQUIREMENT FOR PYTHON DEVELOPERS Message-ID: <20070926221048.CD77B1E4009@bag.python.org> HI THIS IS KRISHNA KISHORE FROM MindRiver. We have an Urgent requirement for Python Developers who have 5-7 YRS of EXP. SKILLS :PYTHON AND C/C++ WORK LOCATION : BANGALROE PLEASE REVERT US WITH YOUR UPDATED PROFILES. Thanks & Regards, Kishore Seethanraju |Senior Associate-People Consulting| MindRiver Information Technologies Pvt. Ltd. Suite# 512, 4th Floor and Suite # 104, Ground Floor ,Oxford Towers, 139, Airport Road, Bangalore 560 008| Tel: +91.80.3052.1600 |Direct: +91.80.3057.5799| Mobile: + 91.9901 96 1696 | Fax: +91.80.3057.5797| Email: kishore at mindriver-it.com | Web www.mindriver-it.com Information transmitted by this-mail is proprietary to MindRiver and / or its Customers and is intended for use only by the individual or entity to which it is addressed, and may contain information that is privileged, confidential or exempt from disclosure under applicable law. If you are not the intended recipient or it appears that this mail has been forwarded to you without proper authority, you are notified that any use or dissemination of this information in any manner is strictly prohibited. In such cases, please notify us immediately at the above mentioned telephone number or email to services at mindriver-it.com and delete this mail from your records. We believe this email to be virus free but do not warrant that this is the case and we will not accept liability for any losses arising from any virus being transmitted unintentionally by us' -------------- next part -------------- An HTML attachment was scrubbed... URL: From sergio.correia at gmail.com Tue Sep 4 00:15:50 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Mon, 3 Sep 2007 23:15:50 -0500 Subject: Can you use -getattr- to get a function in the current module? In-Reply-To: References: Message-ID: Alex, Gabriel, Thanks for the reply. Works great! On 9/3/07, Gabriel Genellina wrote: > En Mon, 03 Sep 2007 20:13:43 -0300, Sergio Correia > escribi?: > > > # Module spam.py > > > > import eggs > > > > print getattr(eggs, 'omelet')(100) > > > > That is, I just call the function omelet inside the module eggs and > > evaulate it with the argument 100. > > > > But what if the function 'omelet' is in the module where I do the > > getattr (that is, in spam.py). If I do any of this > > Use globals(): > > print globals()['omelet'](100) > > (Of course this only makes sense when using a variable instead of > 'omelet'...) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list From e.expelliarmus at yahoo.com Sun Sep 16 14:41:48 2007 From: e.expelliarmus at yahoo.com (e.expelliarmus at yahoo.com) Date: Sun, 16 Sep 2007 11:41:48 -0700 Subject: best site for hacking tricks , computer tweaks Message-ID: <1189968108.948320.282940@o80g2000hse.googlegroups.com> check this out buddies... a kool site for anti hacking and hacking tips and tricks , computer tweaks to enhance ur pc,small virus creation ,etc.... it's the best site ... www.realm-of-tricks.blogspot.com From fakeaddress at nowhere.org Wed Sep 5 05:58:47 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 05 Sep 2007 09:58:47 GMT Subject: Python is overtaking Perl In-Reply-To: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> Message-ID: The expression "faint praise" comes to mind. -- --Bryan From python at jayloden.com Sun Sep 30 23:42:51 2007 From: python at jayloden.com (Jay Loden) Date: Sun, 30 Sep 2007 23:42:51 -0400 Subject: Command-line does work when scheduled In-Reply-To: References: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> <1191104269.578536.56470@g4g2000hsf.googlegroups.com> <1191114246.668635.327080@o80g2000hse.googlegroups.com> <1191163376.067339.34740@d55g2000hsg.googlegroups.com> Message-ID: <47006CBB.9060300@jayloden.com> I sometimes see issues like this at work because certain processes, including scheduled tasks if I remember right, can run as Local System user instead of as your user account. That tends to be a real pain for Python or Perl scripts because that means that they don't have the associations configured properly. You can play around a bit as Local System to find out, using an old trick: open a command prompt and type the following: at nn:nn /interactive cmd where nn:nn is one minute from the current time (24 hour clock, so 11:30 pm would be 24:30). This will launch a cmd prompt on your desktop, but running as Local System instead of as yourself. From there you can see what your script does when you run it as the System user, and see what assoc .py says etc. If you still can't figure it out, the only other things I can think of would be to wrap it in a .bat file and try using that for your scheduled task, or using py2exe to compile your script to an exe which should eliminate the whole file association/PATH issue altogether ;) Hope that helps, -Jay Gabriel Genellina wrote: > No more ideas... I think the scheduler just executes the command line, and > if it works in a console, should work in the scheduler too... Unless you > execute the job under another user, who has a different association for > .py files, that's the only reason I can think of. From http Fri Sep 21 16:53:57 2007 From: http (Paul Rubin) Date: 21 Sep 2007 13:53:57 -0700 Subject: Google and Python References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> Message-ID: <7xejgr68pm.fsf@ruckus.brouhaha.com> David writes: > Another method is for the apps to run continuously and serve on non-80 > port (or on 80 from another host), and your main web server on port 80 > reverse proxies to it when appropriate. You can also pass the open sockets around between processes instead of reverse proxying, using the SCM_RIGHTS message on Unix domain sockets under Linux, or some similar mechanism under other Unixes (no idea about Windows). Python does not currently support this but one of these days I want to get around to writing a patch. From mark at qtrac.eu Tue Sep 25 06:34:23 2007 From: mark at qtrac.eu (Mark Summerfield) Date: Tue, 25 Sep 2007 11:34:23 +0100 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <59e9fd3a0709250313v76a7626dn69908b39e4ba100b@mail.gmail.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <59e9fd3a0709250313v76a7626dn69908b39e4ba100b@mail.gmail.com> Message-ID: <200709251134.23398.mark@qtrac.eu> On 2007-09-25, Andrew Durdin wrote: > On 9/25/07, Mark Summerfield wrote: > > Since the sorteddict's data is always kept in key order, indexes > > (integer offsets) into the sorteddict make sense. Five additional > > methods are proposed to take advantage of this: > > > > key(index : int) -> value > > > > item(index : int) -> (key, value) > > > > value(index : int) -> key > > > > set_value(index : int, value) > > > > delete(index : int) > > But what about using non-sequential integer keys (something I do quite > often)? > > e.g. sorteddict({1:'a', 3:'b': 5:'c', 99:'d'})[3] should return 'b', not > 'd'. > > Andrew The sorteddict really does work in key order, so: d = sorteddict({1:'a', 3:'b', 5:'c', 99:'d'}) d.items() [(1, 'a'), (3, 'b'), (5, 'c'), (99, 'd')] If you do d[3] you will get 'd' since that is the 4th sequential item. If you want to get the item with _key_ 3 then use value(): d.value(3) 'd' PS In my previous reply I got my example wrong a second time: should have been: for item in itemsByDate.values():... -- Mark Summerfield, Qtrac Ltd., www.qtrac.eu From deets at nospam.web.de Mon Sep 3 07:23:50 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Sep 2007 13:23:50 +0200 Subject: TypeError: 'module object is not callable' References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> Message-ID: <5k2966F1prguU1@mid.uni-berlin.de> christophertidy at hotmail.com wrote: > Thank you for your help that seems to have done the trick. > You are correct Diez B. Roggisch that I come from a java background! > > I have a new tiny problem I can't understand either. > Withing Step.py I have the following method > > def isCompleted(self): > "Check whether data step has been processed" > return self.isCompleted > > Then within main.py I simply wish to print the value of isCompleted > which I try to do by the following > print 'Magn completed status is',a.isCompleted() > > Which returns the following error: > a.isCompleted() > TypeError: 'int' object is not callable > > I have tried ideas such as int(a.isCompleted) but to no prevail. Any > ideas? Without more code, not really. It seems as if a is an integer, and not an instance of Step. Diez From arkanes at gmail.com Mon Sep 24 12:09:10 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 24 Sep 2007 11:09:10 -0500 Subject: Can a base class know if a method has been overridden? In-Reply-To: <1190648887.051630.168520@r29g2000hsg.googlegroups.com> References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> <46f7d897$0$25150$426a74cc@news.free.fr> <1190648887.051630.168520@r29g2000hsg.googlegroups.com> Message-ID: <4866bea60709240909h3c40bddcv7c4cce70d5c9b382@mail.gmail.com> On 9/24/07, Ratko wrote: > > If your use case is to make sure a given ('abstract') method has been > > overriden, the canonical solution is to raise NotImplementedError in the > > base class's implementation > > I am not really interested in forcing the subclass to implement a > method. I am interested in knowing *whether* it did implement it or > not. > > > > Else, this may be possible using a custom metaclass (or possibly just > > specializing the __new__ method), but there may be better solutions > > (depending on what you're really trying to do).. > > I have a base class EvtHandler that has methods defined to handle > certain events. You then subclass from EvtHandler and override the > methods for the events you want to receive. If a method has been > overridden, the base class will automatically register for those > events to make sure that they are even delivered to this handler > (which is why I would need to know whether a method has been > overridden or not). Of course, there are other ways of doing this > which would require a bit more work from the subclass... I just > thought this would be a neat "automatic" way of registering for > events. > > For example: > > class EvtHandler: > def __init__(self): > if onKey is overridden: > register_for_key_events() > > def onKey(self): > pass > > > class MyHandler(EvtHandler): > def onKey(self): > # do something here.... Clumsy, but it seems to work. Using a sentinel value as Marc Rintsch suggests might be better: >>> class A(object): ... def vMethod(self, x): ... raise NotImplemented ... def is_implemented(self, method): ... if getattr(type(self), method.__name__).im_func is not method.im_func: ... return True ... def otherMethod(self, x): ... raise NotImplemented ... >>> class B(A): ... def vMethod(self, x): ... print x ... >>> b = b() Traceback (most recent call last): File "", line 1, in TypeError: 'B' object is not callable >>> b = B() >>> b.otherMethod(10) Traceback (most recent call last): File "", line 1, in File "", line 8, in otherMethod TypeError: exceptions must be classes, instances, or strings (deprecated), not NotImplementedType >>> b.vMethod(10) 10 >>> b.is_implemented(A.vMethod) True >>> b.is_implemented(A.otherMethod) >>> (Note that I accidentally raised NotImplemented instead of NotImplementedError, oops.) From steve at holdenweb.com Tue Sep 11 14:46:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 14:46:30 -0400 Subject: Car-ac-systems In-Reply-To: <1189532573.728913.306470@g4g2000hsf.googlegroups.com> References: <1189532573.728913.306470@g4g2000hsf.googlegroups.com> Message-ID: Zentrader wrote: > > What is it about "please do not top-post" that you have difficulty > understanding? Or do "MVP"s feel that their time is so much more > valuable than anyone else's that they are free to ignore the norms? > [Actually I wrote the bit above [to a third party], but apparently zentrader doesn't feel the need to conform with the norm about quoting other people's messages]. > Who made this the norm? In my travels through web-land, it appears to > be the opposite. Don't waste space repeating everything in every > post, and it wastes everyone's time by have to go over the same thing > again and again. Perhaps this thread has a purpose after all, anyway > it has been reported as spam. > I wasn't talking about "webland". I was talking about the comp.lang.python newsgroup/python-list mailing list. And please don;t complain that you don't have time to establish the norms for each group you post to, since it's long been accepted netiquette that you should *read* any group you intend to post to for a while, giving you time to discover what the accepted norms *are* ... and on c.l.py the norm is definitely "avoid top-posting". regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From zentraders at gmail.com Thu Sep 6 19:28:46 2007 From: zentraders at gmail.com (Zentrader) Date: Thu, 06 Sep 2007 16:28:46 -0700 Subject: Beginners Query - Simple counter problem In-Reply-To: References: Message-ID: <1189121326.783000.313180@50g2000hsm.googlegroups.com> On Sep 6, 10:29 am, David Barr wrote: > yields no results. Since every response so far has answered everything __Except The Question You Asked__, your code runs fine on my Linux machine and prints 15. The error may be before this bit of code so it isn't getting called. Add some print statements and try again def d6(i): print "start of d6()" roll = 0 count = 0 while count <= i: print "d6 count =", count, "of", i roll = roll + random.randint(1,6) count += 1 print "returning roll =", roll return roll print d6(3) From carl.dhalluin at gmail.com Wed Sep 5 10:45:11 2007 From: carl.dhalluin at gmail.com (carl.dhalluin at gmail.com) Date: Wed, 05 Sep 2007 14:45:11 -0000 Subject: python exec behaves inconsistent with respect to module imports In-Reply-To: References: <1188997944.162811.33640@r34g2000hsd.googlegroups.com> Message-ID: <1189003511.666050.293060@22g2000hsm.googlegroups.com> Hi Thank you for the explanation It seems that python behaves different for variables created in the toplevel namespace, versus deeper namespaces. CODE: def g(): a=2 print "a in LOC:",locals().has_key('a') print "a in GLO:",globals().has_key('a') def f(): print "a in LOC:",locals().has_key('a') print "a in GLO:",globals().has_key('a') print a f() g() b=3 print "b in LOC:",locals().has_key('b') print "b in GLO:",globals().has_key('b') def h(): print "b in LOC:",locals().has_key('b') print "b in GLO:",globals().has_key('b') print b h() RESULT: a in LOC: True a in GLO: False a in LOC: True a in GLO: False 2 b in LOC: True b in GLO: True b in LOC: False b in GLO: True 3 DISCUSSION: locals() are passed through from a function to a nested function locals() are not passed if you go from top-level to a nested function. globals() are visible from all levels globals() are auto-populated at top level So now get back to my exec code in the previous post. The exec applies a mixture of both rules 1. The exec looks at its namespace to apply the rule for globals(). Since I'm not at top-level, variables are not auto-populated in the globals(), unless I add the keyword 'global' like you suggested. 2. However, the exec applies the other rule for locals(). It does NOT copy the locals() from one level to the nested one, although it should. To me this seems a bug in python exec: - exec should look at its context to find out if the exec is called top-level or deeper - if top-level: auto-populate globals, and do not allow inheritance of locals to nested levels - if non top-level: dont populate globals, but allow inheritance of locals to nested levels. What do you think? From steve at holdenweb.com Mon Sep 24 14:19:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Sep 2007 14:19:27 -0400 Subject: xml-rpc timeout In-Reply-To: References: <2_WdnTQ86eZNY27bnZ2dnUVZ_jCdnZ2d@comcast.com> Message-ID: Lawrence D'Oliveiro wrote: > In message , Steve > Holden wrote: > >> Timeouts shouldn't be a normal feature of TCP communications. > > On the contrary, they should. How else are you going to detect that the > other side has died? You missed the point, which is that TCP hosts shouldn't normally die. In other words, if timeout code is regularly invoked in communicating with a specific host, that host is likely at fault. Naturally timeouts are useful for detecting dropped communications. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From sdeibel at wingware.com Fri Sep 28 09:56:48 2007 From: sdeibel at wingware.com (Stephan Deibel) Date: Fri, 28 Sep 2007 09:56:48 -0400 Subject: Python 3.0 migration plans? In-Reply-To: References: Message-ID: <46FD0820.7010705@wingware.com> Ian Dickinson wrote: > Never would look like a good time scale to me given that a lot of the stuff I use is being ripped out!!!! Has any one actually converted any real code or significant bits of code using the 3.0 converter (in the sandbox somewhere), and if so what kinds of things actually failed? Nothing I've read about 3.0 has alarmed me that much yet, but I've not yet actually tried converting code for it (except a few extension modules, which at least _compiled_ just fine against 3.0). - Stephan From perl4hire at softouch.on.ca Thu Sep 13 09:30:19 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Thu, 13 Sep 2007 09:30:19 -0400 Subject: Coming from Perl In-Reply-To: <87y7fa52ru.fsf@benfinney.id.au> References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Amer Neely writes: > >> Well, I have checked everything I can but I'm getting '500 Internal >> Server Error'. > > This is the HTTP response code saying that the program that should > have served the response document instead exited with an error. > > To debug, you should first run the program (or at least the part that > you're trying to implement) *outside* the context of a web server. Do > it at a command line, and any errors will show up as exception > tracebacks. > > Only when you have something that performs correctly outside a web > server context should you consider how to wrap it in that new > (harder-to-debug) context. > That is where I'm stuck. It runs fine on my home computer, but I don't have shell access to my hosted site. Can you or anyone see anything in the posted code that might be the cause? Why is it so much harder to debug? There is no syntax error that I can tell. I've set the file permissions to rwxr-xr-x. I've printed the correct content type. It's a simple print statement, as per several examples I've seen. Is it an Apache thing? I've not seen any mention in the documentation on that. -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From kyosohma at gmail.com Thu Sep 13 13:38:21 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 13 Sep 2007 10:38:21 -0700 Subject: Help to start python In-Reply-To: <1189694381.957459.232350@y42g2000hsy.googlegroups.com> References: <1189693144.493878.130220@w3g2000hsg.googlegroups.com> <1189693433.545822.89580@o80g2000hse.googlegroups.com> <1189694381.957459.232350@y42g2000hsy.googlegroups.com> Message-ID: <1189705101.661806.255580@19g2000hsx.googlegroups.com> On Sep 13, 9:39 am, python_lover wrote: > On Sep 13, 7:23 pm, kyoso... at gmail.com wrote: > > > > > python_lover wrote: > > > Hi All, > > > > I'm new to python. I installed python 2.5 and IDLE 1.2.1 . I'm able > > > to run shell commands. > > > > But I don't know how to execute a python program using this. When I'm > > > opeing a py program a seperate IDLE window opeing with program text. > > > But I don't know to to execute the prg. > > > > Please help me on this . > > > > thank you > > > > regards > > > Sat > > > When in IDLE, you can go to the Run menu and choose Run Module (or > > press F5) in the window that has the program code. > > > Hope that helps! > > > Mike- Hide quoted text - > > > - Show quoted text - > > Thankx mike. > > It is working well. > > Please guide me some good sites to start web based programing on > python. > > thank you. > > sat Check out http://wiki.python.org/moin/WebProgramming http://www.boddie.org.uk/python/HTML.html http://www.crummy.com/software/BeautifulSoup/ And the many Python web frameworks, like Django, TurboGears, Zope/ Plone, etc. Mike From nospam at nowhere.com Sun Sep 2 06:28:10 2007 From: nospam at nowhere.com (DavidM) Date: 2 Sep 2007 22:28:10 +1200 Subject: ANN: Python bindings for mjpegtools (yuv4mpeg) Message-ID: <46da903a$1@news.orcon.net.nz> Hi, I've built some bindings for the yuv4mpeg API, supporting both Python and C++. http://www.freenet.org.nz/pyyuv4mpeg/ Based on SWIG, implements virtually the whole API as given in yuv4mpeg.h, and also implements a high-level 'Stream' class in both C++ and Python. These bindings allow easy creation of video filters, in Python or C++, that work to the mjpegtools 'yuv4mpegpipe' standard - reading YUV4MPEG frames into stdin and/or writing YUV4MPEG frames to stdout. Enjoy Cheers David From Dominic at PLEASEASK.co.uk Thu Sep 6 06:01:49 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Thu, 6 Sep 2007 11:01:49 +0100 Subject: SQLite and coercing to Unicode - please help. Message-ID: <46dfcbea$0$89178$7b0f0fd3@mistral.news.newnet.co.uk> Hello! First, the problem: the program below falls over with the following error: TypeError: coercing to Unicode: need string or buffer, NoneType found. and gives the following line: "' WHERE secBoardId='"+Values[0]+"'" My first thought was that Values[0] was containing nothing at all, that would allow a NoneType to be found, but it has data in that position of the list - you'll see below. So I thought that Values[0] was 'losing' its type somewhere, so I checked it just by having the program print out type(Values[0]), it says it's a string - also seen below. So given it's not a NoneType and it's a string, I don't understand why I'm getting the error. I tried forcing it to a particular type (I think that's the right word), so I put lines like: Values[0]=unicode(Values[0]) or WHERE ... ='"str(Values[0]+"'" but neither worked. I've put my code below, I'm sorry it's so long, I've commented the line where it's falling over. If it's useful, I am using Python 2.5.1, ElementTree 1.2.6 and pySQLite 2.3.5 If this is a silly mistake ( one where RTFM is a valid response, can you point me at the place where I can get the answer please?), otherwise any help is greatly appreciated as I'm out of ideas. :( Dominic The output: At top of function: GBP/PLUS-ofn-GB00B12T7004 Values list contains: ['GBP/PLUS-ofn-GB00B12T7004', u'GBP', u'GB00B12T7004 ', u'All Star Minerals plc ', 'ASMO', 'DE', 'PLUS', u'B12T700', u' ', u'A', None, None, None, '000000000000000000', '0', '0'] Type of Values[0] is: The code: def dealwithSecBRep(text_buffer): # text_buffer contains a sequential string of xml Elements=['secBoardId','currencyId','issuerId','secName','secShortName','secClassId',\ 'sectorId','isin','issueDate','inheritedState','bidPrice','offerPrice','midPrice',\ 'standardMarketSize','openPrice','closePrice'] Values=[] dom=get_a_document(text_buffer) # this function returns an xml document. branch=dom.getiterator(Elements[0]) Values.append(GetUniqueId(branch[0])) # Combo of secCode and secBoardId print "At top of function:",Values[0] sql=cursor.execute('SELECT*FROM SecB WHERE secBoardId='+"'"+Values[0]+"'").fetchall() SQL2=sql flag=0 if len(sql)>0: #Prior database exists try: branch=dom.getiterator(Elements[1]) Values.append(branch[0].text) # currencyID except: value=GetFromDB('currencyCode',text_buffer) Values.append(value) try: branch=dom.getiterator(Elements[2]) Values.append(branch[0].text) # issuerName except: value=GetFromDB('issuerName',text_buffer) Values.append(value) try: branch=dom.getiterator(Elements[3]) Values.append(branch[0].text) # Tradable Instrument Name except: value=GetFromDB('Tradable Instrument Name',text_buffer) Values.append(value) try: branch=dom.getiterator(Elements[4]) Values.append(branch[0].text) # Tradable Instrument Short Name except: value=GetFromDB('Tradable Instrument Short Name',text_buffer) Values.append(value) try: branch=dom.getiterator(Elements[5]) Values.append(branch[0].text) # Tradable Instrument Type except: value=GetFromDB('Tradable Instrument Type',text_buffer) Values.append(value) try: branch=dom.getiterator(Elements[6]) Values.append(branch[0].text) # SectorCode except: Values.append('PLUS') # SectorCode if one does not naturally exist try: branch=dom.getiterator(Elements[7]) value=str(branch[0].text) Values.append(value[4:11]) # SEDOL except: value=GetFromDB('SEDOL Code',text_buffer) Values.append(value) try: branch=dom.getiterator(Elements[8]) Values.append(branch[0].text) # Date except: value=GetFromDB('Tradable Instrument Effective Date',text_buffer) Values.append(value) try: branch=dom.getiterator(Elements[9]) Values.append(branch[0].text) # inherited State except: value=GetFromDB('inheritedState',text_buffer) Values.append(value) try: branch=dom.getiterator(Elements[10]) Values.append(branch[0].text) # bidPrice if available except: Values.append("0"*18) # bidPrice if not available try: branch=dom.getiterator(Elements[11]) Values.append(branch[0].text) # offerPrice if available except: Values.append("0"*18) # offerPrice if not available try: branch=dom.getiterator(Elements[12]) Values.append(branch[0].text) # midPrice if available except: Values.append("0"*18) # midPrice if not available try: branch=dom.getiterator(Elements[13]) Values.append(branch[0].text) # standardMarketSize if available except: Values.append("0"*18) # standardMarketSize if not available try: branch=dom.getiterator(Elements[14]) Values.append(branch[0].text) # Stock Open except: Values.append("0") # Stock Close try: branch=dom.getiterator(Elements[15]) Values.append(branch[0].text) # Stock Close except: Values.append("0") # Stock Open flag=0 else: #Fill missing fields with blanks. try: branch=dom.getiterator(Elements[1]) Values.append(branch[0].text) # currencyID except: Values.append(" "*3) try: branch=dom.getiterator(Elements[2]) Values.append(branch[0].text) # issuerName except: Values.append(" "*35) try: branch=dom.getiterator(Elements[3]) Values.append(branch[0].text) # Tradable Instrument Name except: Values.append(" "*40) try: branch=dom.getiterator(Elements[4]) Values.append(branch[0].text) # Tradable Instrument Short Name except: Values.append(" "*15) try: branch=dom.getiterator(Elements[5]) Values.append(branch[0].text) # Tradable Instrument Type except: Values.append(" ") #It's length 2 try: branch=dom.getiterator(Elements[6]) Values.append(branch[0].text) # SectorCode except: Values.append('PLUS') # SectorCode if one does not naturally exist try: branch=dom.getiterator(Elements[7]) value=str(branch[0].text) Values.append(value[4:11]) # SEDOL except: Values.append(" "*7) try: branch=dom.getiterator(Elements[8]) Values.append(branch[0].text) # Date except: Values.append(" "*8) try: branch=dom.getiterator(Elements[9]) Values.append(branch[0].text) # inherited State except: Values.append('A') # Means Active try: branch=dom.getiterator(Elements[10]) Values.append(branch[0].text) # bidPrice if available except: Values.append("0"*18) # bidPrice if not available try: branch=dom.getiterator(Elements[11]) Values.append(branch[0].text) # offerPrice if available except: Values.append("0"*18) # offerPrice if not available try: branch=dom.getiterator(Elements[12]) Values.append(branch[0].text) # midPrice if available except: Values.append("0"*18) # midPrice if not available try: branch=dom.getiterator(Elements[13]) value=string.ljust(string.rjust(branch[0][0].text,10,"0"),18,"0") Values.append(value) # standardMarketSize if available except: Values.append("0"*18) # standardMarketSize if not available print "Values currenctly:",Values try: branch=dom.getiterator(Elements[14]) value=string.ljust(string.rjust(branch[0][0].text,10,"0"),18,"0") Values.append(branch[0].text) # Stock Open except: Values.append("0") # Stock Close try: branch=dom.getiterator(Elements[15]) value=string.ljust(string.rjust(branch[0][0].text,10,"0"),18,"0") Values.append(branch[0].text) # Stock Close except: Values.append("0") # Stock Open flag=1 if flag==0: print "Values list contains:",Values,"\n" print "Type of Values[0] is:",type(Values[0]),"\n" longstring="UPDATE SecB SET currencyCode='"+Values[1]+"',issuerName='"+Values[2]+"',instrName='"+Values[3]+\ "',instrShortName='"+Values[4]+"',instrType='"+Values[5]+"',secCode='"+Values[6]+\ "',SEDOL='"+Values[7]+"',Date='"+Values[8]+"',SuspendedState='"+Values[9]+\ "',bidPrice='"+Values[10]+"',offerPrice='"+Values[11]+"',midPrice='"+Values[12]+\ "',standardMarketSize='"+Values[13]+"',openOrClosed='"+Values[14]+\ "' WHERE secBoardId='"+Values[0]+"'" # This is the line it falls over on. cursor.execute(longstring) connection.commit() currentStatus=SQL2[0][13] #current Stock Status if currentStatus==1: # Open if Values[14]!='0': # xml says open oldStart("",text_buffer) #5SE elif Values[15]!='0': # xml says closed oldStart("",text_buffer) elif Values[14]==0 and Values[15]==0: # neither openPrice nor closePrice exist in xml oldStart("",text_buffer) # just 5ER and 5IS else: # currently Closed if Values[14]!='0': #xml says open oldStart("",text_buffer) # 5PR else: #xml says closed oldStart("",text_buffer) # 5ER,5IS else: cursor.execute('INSERT INTO SecB VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',\ (Values[0],Values[1],Values[2],Values[3],Values[4],Values[5],\ Values[6],Values[7],Values[8],Values[9],Values[10],Values[11],\ Values[12],Values[13],Values[14])) connection.commit() if Values[14]!='0': # xml says open test=dom.getiterator('openPrice') oldStart("",text_buffer) # 5ER, 5IS oldStart("",text_buffer) # 5PR else: # xml says closed, or neither options exist. oldStart("",text_buffer) # 5ER, 5IS From kib2 at free.fr Sat Sep 8 16:42:06 2007 From: kib2 at free.fr (tool69) Date: Sat, 08 Sep 2007 22:42:06 +0200 Subject: Parsing nested constructs Message-ID: <46e308d3$0$9153$426a74cc@news.free.fr> Hi, I need to parse some source with nested parenthesis, like this : >cut------------- { {item1} { {item2} {item3} } } >cut------------- In fact I'd like to get all start indexes of items and their end (or lenght). I know regexps are rather limited for this type of problems. I don't need an external module. What would you suggest me ? Thanks. From json.barnes at gmail.com Fri Sep 28 19:29:54 2007 From: json.barnes at gmail.com (Jason M Barnes) Date: Fri, 28 Sep 2007 19:29:54 -0400 Subject: Bug with lists of pairs of lists and append() In-Reply-To: References: Message-ID: <833263a00709281629x6de213c4w13a93e8c37389bd8@mail.gmail.com> On 9/28/07, Gabriel Zachmann wrote: > Well, > > could some kind soul please explain to me why the following trivial code is > misbehaving? > > #!/usr/bin/python > > lst = [ 0, 1, 2 ] > > s = [] > > l = [ lst[0] ] > r = lst[1:] > while r: > x = (l,r) > print x > s.append( x ) > > l.append( r.pop(0) ) > > print s > > > > The output I get is: > > ([0], [1, 2]) > ([0, 1], [2]) > [([0, 1, 2], []), ([0, 1, 2], [])] > > and the error is in the last line: the two pairs in the outer list are > identical and they should be as the pairs on the first and the 2nd line, > respectively! > > I think I'm going nuts -- for the life of me I don't see what's going on ... > (I've been tracking down a bug in my larger python script, and the cause > seems to boil down to the above snippet.) > > Thanks a lot in advance for any insights, etc. > > Best regards, > Gabriel. > > -- > http://mail.python.org/mailman/listinfo/python-list > If you're familiar with C or C++, think of s as holding a pointer to x which in turn holds a pointer to l and r, so when you change l or r, x (and s indirectly) is still pointing to the same lists which by the end of your loop have changed to r=[] and l=[0,1,2]. BTW: It's not really "misbehaving." It's doing exactly what you're telling it to do ;-) Jason From DouhetSukd at gmail.com Fri Sep 14 03:18:27 2007 From: DouhetSukd at gmail.com (DouhetSukd at gmail.com) Date: Fri, 14 Sep 2007 00:18:27 -0700 Subject: funny little 190 lines command line math tutor I wrote for my 7-year old. In-Reply-To: <1189753950.569402.186370@g4g2000hsf.googlegroups.com> References: <1189753950.569402.186370@g4g2000hsf.googlegroups.com> Message-ID: <1189754307.528472.7590@w3g2000hsg.googlegroups.com> Ok, it does look a bit mangled. I re-posted it on www.pastebin.com, at http://python.pastebin.com/m7b1f9ab5. Cheers From antroy at gmail.com Mon Sep 10 03:50:56 2007 From: antroy at gmail.com (Ant) Date: Mon, 10 Sep 2007 00:50:56 -0700 Subject: python 2.5 problems In-Reply-To: References: <3nVEi.98555$Vk6.66626@newsfe07.phx> Message-ID: <1189410656.649807.63640@r29g2000hsg.googlegroups.com> On Sep 9, 6:57 pm, "O.R.Senthil Kumaran" wrote: > > Finally deleted 2.2 and loaded 2.5 (see below), using > > Dont delete. Uninstall python 2.2 and additional modules if you have installed them. But since you've already deleted 2.2, download and reinstall 2.2, uninstall 2.2 and 2.5 via Add/Remove Programs and then reinstall 2.5 again. -- Ant... From hall.jeff at gmail.com Sat Sep 29 14:32:07 2007 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Sat, 29 Sep 2007 18:32:07 -0000 Subject: Program inefficiency? In-Reply-To: <1191090293.017485.225470@y42g2000hsy.googlegroups.com> References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> <1191087234.915654.182370@k79g2000hse.googlegroups.com> <1191090293.017485.225470@y42g2000hsy.googlegroups.com> Message-ID: <1191090727.614819.292550@50g2000hsm.googlegroups.com> It think he's saying it should look like this: # File: masseditor.py import re import os import time p1= re.compile('(href=|HREF=)+(.*)(#)+(.*)(\w\'\?-<:)+(.*)(">)+') p2= re.compile('(name=")+(.*)(\w\'\?-<:)+(.*)(">)+') p100= re.compile('(a name=)+(.*)(-)+(.*)(>)+') q1= r"\1\2\3\4_\6\7" q2= r"\1\2_\4\5" def massreplace(): editfile = open("C:\Program Files\Credit Risk Management\Masseditor \editfile.txt") filestring = editfile.read() filelist = filestring.splitlines() for i in range(len(filelist)): source = open(filelist[i]) starttext = source.read() for i in range (13): interimtext = p1.sub(q1, starttext) interimtext= p2.sub(q2, interimtext) interimtext= p100.sub(q2, interimtext) source.close() source = open(filelist[i],"w") source.write(finaltext) source.close() massreplace() I'll try that and see how it works... From steve at holdenweb.com Wed Sep 19 08:22:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Sep 2007 08:22:11 -0400 Subject: How to know the starting point In-Reply-To: <96489.19792.qm@web8706.mail.in.yahoo.com> References: <96489.19792.qm@web8706.mail.in.yahoo.com> Message-ID: Raj kumar wrote: > Hi, > I need help regarding the starting point in python project, > As we can find main() function in java class to know the starting class > in java, > what is the starting point in python project? > How to find the starting point. > Thank you The starting point is the top of the file. Class and def statements are executable, and bind their names to the definitions. The bodies are this compiled, but the compiled code is only executed when a call is made (which avoids forward referencing problems, by and large: names are late-bound). So the interpreter just starts at the top and runs through the code in sequence. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From daniel.j.larsson at gmail.com Fri Sep 7 06:03:10 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Fri, 7 Sep 2007 12:03:10 +0200 Subject: Class design (information hiding) In-Reply-To: References: Message-ID: <2bfa72fa0709070303m66c791cbn7e87d64944dd104c@mail.gmail.com> On 9/7/07, Alexander Eisenhuth wrote: > > Hi all, > > I'm wodering how the information hiding in python is ment. As I understand > there > doesn't exist public / protected / private mechanism, but a '_' and > '__' > naming convention. > > As I figured out there is only public and private possible as speakin in > "C++ > manner". Are you all happy with it. What does "the zen of python" say to > that > design? (protected is useless?) Strictly speaking, everything is public in python. Members prefixed with "__" just get name mangled. But conceptually, yes, there is only public and private members. Information hiding is based on convention, otherwise it would be hard to write debuggers in python, which by definition wants to break the information hiding principle. If you're not writing a debugger, doc generator, or other type of meta level program, follow the conventions of not peeking under the hood. class A: > def __init__(self): > self.__z = 1 > self._z = 2 > self.z = 3 > def _getX(self): > return "X" > def __getY(self): > return "Y" > def doAnything(self): > print self.__getY() > > > class B(A): > def __init__(self): > A.__init__(self) > print dir (self) > >>> b = B() > ['_A__getY', '_A__z', '__doc__', '__init__', '__module__', '_getX', '_z', > 'doAnything', 'z'] > > I was a bit surprised about '_A__getY' and '_A__z'. This is so that in class B, you can also have members called __getY and __z, and they won't interfere with class A (they'll be called _B__getY and _B__z respectively ). What would you say to a C++ Programmer about class interfaces in big Python > systems? What is the idea behind the _ and __ naming. As a rough analogy: __name -> private _name -> protected Use or don't use '_' > methods ? (As Designer of the software, as Programmer of the software) I don't know if you're making a distinction here between "designer" and "programmer". Are you meaning "implementer of library" and "user of library"? As a user of a library, never ever explicitly call members starting with an underscore. Regards Alexander > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jcd at sdf.lonestar.org Thu Sep 13 16:59:45 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Thu, 13 Sep 2007 16:59:45 -0400 Subject: Decimal formatting In-Reply-To: <1189716651.810481.260850@y42g2000hsy.googlegroups.com> References: <1189716651.810481.260850@y42g2000hsy.googlegroups.com> Message-ID: <20070913205945.GB5674@sdf.lonestar.org> On Thu, Sep 13, 2007 at 01:50:51PM -0700, Harlin Seritt wrote regarding Decimal formatting: > > Cant believe I have to post this and get help... and can't believe I > couldnt Google it reasonably well enough... I need to take a float > variable and have it display as a string to always have two decimal > places: > > 12.3333 -> 12.33 > 1.0 -> 1.00 > etc... > > Anyone willing to help with this one? > > thanks, > > Harlin > f = 12.333333 i = 10 f_output = "%0.2f" % f i_output = "%0.2f" % i Cheers, Cliff From sigmarCdS at hotmail.com Mon Sep 24 07:34:45 2007 From: sigmarCdS at hotmail.com (jonny) Date: Mon, 24 Sep 2007 04:34:45 -0700 Subject: rules from an xml file Message-ID: <1190633685.275142.264540@r29g2000hsg.googlegroups.com> I have a python code that manages some parameters using some variable rules that may change from day to day. I'd like that the code will self-modify according to rules parsed from a xml file: example: Something is wrong! ... ... Due to the fact that rules may change, I have to manage the python program, parsing the whole xml file, and self-modify the python code according to these variable rules. How can I do? From jelleferinga at gmail.com Thu Sep 6 12:12:11 2007 From: jelleferinga at gmail.com (jelle) Date: Thu, 06 Sep 2007 16:12:11 -0000 Subject: initializing cooperative method Message-ID: <1189095131.853954.233660@r34g2000hsd.googlegroups.com> Hi, I'm writing a bunch of abstract classes and I'd like to delegate the arguments of the concrete class the to abstract one. I was surprised to see that the print statement in the abstract class isn't executed. But moreover, I'd like to find out an idiom that allows one to delegate arguments in the inherited class. Any ideas? Thanks, -jelle class Abstract(object): def __init__(self, a='a', b='b'): self.a, self.b = a, b print a, b class Concrete(Abstract): def __init__(self, a='AAA', b='BBB'): super(Abstract, self).__init__( a=a, b=b ) print a, b c = Concrete(a=1) >>> c = Concrete(a=1) 1 BBB From paul.hankin at gmail.com Fri Sep 28 18:20:54 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 28 Sep 2007 15:20:54 -0700 Subject: Checking for the existence of Duplicates In-Reply-To: References: Message-ID: <1191018054.695826.73470@57g2000hsv.googlegroups.com> On Sep 28, 10:27 pm, AndyB wrote: > ... > This is in a program that generates random numbers to do a brute force > solve on a sudoku-like puzzle. Once a certain level of difficulty in > the puzzle is reached, performance goes off a cliff because the > duplicate checking code, although fast, is executed so many times. For a sudoku solver, you may be better dodging the problem, and maintaining a set per row, column and box saying which numbers have been placed already - and thus avoiding adding duplicates in the first place. It may be better to use a bitfield instead (ie use bits 1..9 of an int to represent these sets). You should also check out Donald Knuth's 'Dancing Links' algorithm as a clever implementation of a brute-force search that works perfectly for sudoku solving. (It uses linked lists, but the idea still works in python). But to answer your actual question: > I have found a lot of material on removing duplicates from a list, but I > am trying to find the most efficient way to just check for the existence > of duplicates in a list. Here is the best I have come up with so far: > > CheckList = [x[ValIndex] for x in self.__XRList[z]] > FilteredList = filter((lambda x:x != 0),CheckList) > if len(FilteredList) > len(sets.Set(FilteredList)): return In general, the natural way to test for duplicates is as you have it, except that set is now built-in, so you can write def has_no_duplicates(x): return len(x) == len(set(x)) But in your case, you're having to construct the list and filter, so it's better just to loop and do everything at once: found = set() for x in self.__XRList[z]: cell = x[ValIndex] if cell != 0 and cell in found: return False found.add(cell) Since your elements are probably numbers 1 to 9 (or 0), you might use bitfields. I'd expect this to be faster, but you should check: found = 0 for x in self.__XRList[z]: cellbit = 1 << x[ValIndex] if cellbit != 1 and (cellbit & found): return False found |= cellbit -- Paul Hankin From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 11 03:45:15 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 11 Sep 2007 09:45:15 +0200 Subject: newbie: stani's python editor if-else In-Reply-To: <1189484688.520933.25000@22g2000hsm.googlegroups.com> References: <1189484688.520933.25000@22g2000hsm.googlegroups.com> Message-ID: <46e6478c$0$28487$426a74cc@news.free.fr> madzientist a ?crit : > hi, > two quick questions: > > a) i am using SPE (latest version) and for some reason, when i type, > say > > if 1==2: > print "not equal" > else: > print "equal" > > the else is at the same indentation level as the preceding print > statement, and i get a syntax error Obviously. As you know, in Python, indentation is signifiant. > why doesn't spe automatically put the else at the level of the if > statement ? I don't know. Perhaps you should ask the author ? > what am i dong wrong ? Mmm, let's see.... Posting on the wrong place, perhaps ?-) > once i manually change the > indentation, the code snippet runs perfectly. Indeed. > b) if this is not the group for such elementary questions, please do > let me know. Ok, since you ask for it : this is not the group for problems related to SPE. You probably want the SPE mailing-list (if it exists), or whatever the project page offers as a mean of sending feedback to the author. Python-related questions, even elementary ones (provided you at least took time to read the official tutorial), are of course welcome !-) HTH From f.guerrieri at gmail.com Wed Sep 5 06:29:58 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Wed, 5 Sep 2007 12:29:58 +0200 Subject: concise code (beginner) In-Reply-To: <13dsvqrqivtf092@corp.supernews.com> References: <13dsvqrqivtf092@corp.supernews.com> Message-ID: <79b79e730709050329n393489c9jc956211da4065118@mail.gmail.com> On 9/5/07, bambam wrote: > > I have about 30 pages (10 * 3 pages each) of code like this > (following). Can anyone suggest a more compact way to > code the exception handling? If there is an exception, I need > to continue the loop, and continue the list. > > Steve. > > ----------------------------------- > for dev in devs > try: > dev.read1() > except > print exception > remove dev from devs > > for dev in devs > try: > dev.read2() > except > print exception > remove dev from devs > > for dev in devs > try: > dev.read3() > except > print exception > remove dev from devs > > etc. > well the first thought is: why don't you put all the calls in a single for loop? for dev in devs: try: call the methods on dev (instead of explicitly elencating all of them there could and should be other solutions more mantainable) except: flag dev as unusable Modifying the sequence you are iterating over can be tricky. francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Wed Sep 12 12:00:03 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 12 Sep 2007 11:00:03 -0500 Subject: Python 3K or Python 2.9? In-Reply-To: <1i4bjb8.63ihk49vs6c8N%aleax@mac.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <1i4bjb8.63ihk49vs6c8N%aleax@mac.com> Message-ID: <4866bea60709120900k35d30132yafd8fad0aeb0074d@mail.gmail.com> On 9/12/07, Alex Martelli wrote: > Duncan Booth wrote: > ... > > As for omitting 'self' from method definitions, at first site you might > > think the compiler could just decide that any 'def' directly inside a > > class could silently insert 'self' as an additional argument. This > > doesn't work though because not everything defined in a class has to be > > an instance method: static methods don't have a self parameter at all, > > class methods traditionally use 'cls' instead of 'self' as the name of > > the first parameter and it is also possible to define a function inside > > a class block and use it as a function. e.g. > > Actually you could do the "magic first-parameter insertion" just when > returning a bound or unbound method object in the function's __get__ > special method, and that would cover all of the technical issues you > raise. E.g.: > > > class Weird: > > def factory(arg): > > """Returns a function based on its argument""" > > > > foo = factory("foo") > > bar = factory("bar") > > del factory > > > > When factory is called, it is a simple function not a method. If it had > > Sure, that's because the function object itself is called, not a bound > or unbound method object -- indeed. factory.__get__ never gets called > here. > > > class C: > > def method(self): pass > > > > and > > > > def foo(self): pass > > class C: pass > > C.method = foo > > > > both of these result in effectively the same class (although the second > > one has a different name for the method in tracebacks). > > And exactly the same would occur if the self argument was omitted from > the signature and magically inserted when __get__ does its job. > This would mean that mixing functions and methods would have to be done like you do it in C++, with lots of careful knowledge and inspection of what you're working with. What would happen to stuff like inspect.getargspec? Besides, if self isn't in the argument spec, you know that the very next thing people will complain about is that it's not implicitly used for locals, and I'll punch a kitten before I accept having to read Python code guessing if something is a global, a local, or part of self like I do in C++. From andreas.tawn at ubisoft.com Fri Sep 7 05:08:02 2007 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Fri, 7 Sep 2007 11:08:02 +0200 Subject: interesting puzzle......try this you will be rewarded... Message-ID: <8AEDA5E3386EA742B8C24C95FF0C7580013D0FF6@PDC-MAIL3.ubisoft.org> >Basilisk96 wrote: >> I remember seeing a more elaborate puzzle that involved coding, >> cryptography knowledge, etc. to get through it. But what was the link, >> I forget now... > >There's this one http://www.inwardhellix.net/ > >I haven't played it yet so I can't vouch for its quality. (am playing >it now) Maybe http://www.pythonchallenge.com/ ? Cheers, Drea Andreas Tawn Lead Technical Artist Ubisoft Reflections From tjreedy at udel.edu Tue Sep 18 23:00:10 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Sep 2007 23:00:10 -0400 Subject: no more reload() in py3k References: <1190165028.837799.220300@q3g2000prf.googlegroups.com> Message-ID: I believe Guido said on the Py3 dev list that reload should have been moved to one of the modules (maybe inspect) rather than removed completely (and that he missed it also). So this appears to be an alpha1 glitch. tjr From pavlovevidence at gmail.com Fri Sep 28 19:13:01 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 28 Sep 2007 16:13:01 -0700 Subject: Numeric command-line options vs. negative-number arguments In-Reply-To: References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <0a6dnQmBPIzuqmHbnZ2dnUVZ_vihnZ2d@comcast.com> <87ejgj4lpy.fsf_-_@benfinney.id.au> <87wsub2s4w.fsf@benfinney.id.au> Message-ID: <1191021181.401767.41040@n39g2000hsh.googlegroups.com> On Sep 28, 9:51 am, Steven Bethard wrote: > Ben Finney wrote: > > Steven Bethard writes: > >> Argparse knows what your option flags look like, so if you specify > >> one, it knows it's an option. Argparse will only interpret it as a > >> negative number if you specify a negative number that doesn't match > >> a known option. > > > That's also irritating, and violates the expected behaviour. It leads > > to *some* undefined options being flagged as errors, and others > > interpreted as arguments. The user shouldn't need to know the complete > > set of options to know which leading-hyphen arguments will be treated > > as options and which ones won't. > > > The correct behaviour would be to *always* interpret an argument that > > has a leading hyphen as an option (unless it follows an explicit '--' > > option), and complain if the option is unknown. > > It was decided that practicality beats purity here. Arguments with > leading hyphens which look numeric but aren't in the parser are > interpreted as negative numbers. Arguments with leading hyphens which > don't look numeric and aren't in the parser raise errors. Sure, it's not > the pure answer, but it's the practical answer: "-123" is much more > likely to be a negative number than an option. What if (for example) you define a option "-3", and also accept numerical arguments on the command line. Then you could get sudden unexpected behavior if you input the wrong number: "./hello -1" works ok. "./hello -2" works ok. "./hello -3" ... whoops, now the negative number is suddenly an option. Granted, it would be stupid for a program to do that, but it suggests to me that it's probably a good idea to treat all negative numbers the same. I.e. if there are any numerical options, then all negative numbers are treated as options. If there are none, then negative numbers are treated as numbers. Carl Banks From steve at holdenweb.com Wed Sep 26 09:30:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 26 Sep 2007 09:30:52 -0400 Subject: setuptools without unexpected downloads In-Reply-To: References: <87ejgmklep.fsf@benfinney.id.au><874phhlupi.fsf@benfinney.id.au> <5lumarFae888U1@mid.uni-berlin.de> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> <5luv0iFaai82U1@mid.uni-berlin.de> <1190808836.056298.232640@57g2000hsv.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Paul Boddie wrote: > >> P.S. Of course, the package maintainer problem manifests itself most >> prominently on Windows where you often see people asking for pre-built >> packages or installers. > > for the record, I'd love to see a group of volunteers doing stuff like > this for Windows. there are plenty of volunteers that cover all major > Linux/*BSD distributions (tons of thanks to everyone involved in this!), > but as far as I can remember, nobody has ever volunteered to do the same > for Windows. > I'd like to see something like this happen, too, and if a group of volunteers emerges I'll do what I can through the PSF to provide resources. Activities that benefit the whole community (or a large part of it) are, IMHO, well worth supporting. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From jcd at sdf.lonestar.org Mon Sep 10 08:48:24 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 10 Sep 2007 08:48:24 -0400 Subject: encoding latin1 to utf-8 In-Reply-To: <1189427146.723304.270600@22g2000hsm.googlegroups.com> References: <1189427146.723304.270600@22g2000hsm.googlegroups.com> Message-ID: <20070910124824.GC5084@sdf.lonestar.org> On Mon, Sep 10, 2007 at 12:25:46PM -0000, Harshad Modi wrote regarding encoding latin1 to utf-8: > Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!newsgate.cistron.nl!xs4all!news.glorb.com!postnews.google.com!22g2000hsm.googlegroups.com!not-for-mail > > hello , > I make one function for encoding latin1 to utf-8. but i think it is > not work proper. > plz guide me. > > it is not get proper result . such that i got "Belgi???" using this > method, (Belgium) : > > import codecs > import sys > # Encoding / decoding functions > def encode(filename): > file = codecs.open(filename, encoding="latin-1") > data = file.read() > file = codecs.open(filename,"wb", encoding="utf-8") > file.write(data) > > file_name=sys.argv[1] > encode(file_name) Some tips to help you out. 1. Close your filehandles when you're done with them. 2. Don't shadow builtin names. Python uses the name file, and binding it to your own function can have ugly side effects that manifest down the road. So perhaps try the following: import codecs def encode(filename): read_handle = codecs.open(filename, encoding='latin-1') data = read_handle.read() read_handle.close() write_handle = codecs.open(filename, 'wb', encoding='utf-8') write_handle.write(data) write_handle.close() For what it's worth though, I couldn't reproduce your problem with either your code or mine. This is not too surprising as all the ascii characters are encoded identically in utf-8 and latin-1. So your program should output exactly the same file as it reads, if the contents of the file just read "Belgium" Cheers, Cliff From bronger at physik.rwth-aachen.de Wed Sep 5 06:45:26 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 05 Sep 2007 12:45:26 +0200 Subject: Wanted: safe codec for filenames Message-ID: <87sl5tcrw9.fsf@wilson.homeunix.com> Hall?chen! I'd like to map general unicode strings to safe filename. I tried punycode but it is case-sensitive, which Windows is not. Thus, "Hallo" and "hallo" are mapped to "Hallo-" and "hallo-", however, I need uppercase Latin letters being encoded, too, and the encoding must contain only lowercase Latin letters, numbers, underscores, and maybe a little bit more. The result should be more legible than base64, though. Has anybody created such a codec already? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From brown at esteem.com Thu Sep 6 18:39:13 2007 From: brown at esteem.com (Tom Brown) Date: Thu, 6 Sep 2007 15:39:13 -0700 Subject: why should I learn python In-Reply-To: <1189117798.506367.278560@y42g2000hsy.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <1189117798.506367.278560@y42g2000hsy.googlegroups.com> Message-ID: <200709061539.13537.brown@esteem.com> On Thursday 06 September 2007 15:29, windandwaves wrote: > On Sep 7, 9:50 am, James Stroud wrote: > > Seewww.python.org. Trust us all when we say that its the best. > > I get that feeling - yes. Question is: > > 1. what is it good for? > 2. why is it so good? > > I would love to hear some opinions. 1. It is good for just about everything except kernel modules. 2. Ease of use. From zentraders at gmail.com Tue Sep 25 13:07:37 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 25 Sep 2007 10:07:37 -0700 Subject: Nested For and While Statements In-Reply-To: <1190701545.148197.191090@o80g2000hse.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190664644.936871.57050@57g2000hsv.googlegroups.com> <1190701545.148197.191090@o80g2000hse.googlegroups.com> Message-ID: <1190740057.329424.57230@r29g2000hsg.googlegroups.com> Scope had to do with "visibility" and not with how memory was allocated. Scope means, can this line of code access that block of memory. Note that in list comprehension, [x for x in (1, 2, 3)], the for loop allocates memory the same way, but the scope changes so that "x" is visible outside the for loop, so I guess we will have to agree to disagree. From jstucklex at attglobal.net Sun Sep 30 13:55:28 2007 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Sun, 30 Sep 2007 13:55:28 -0400 Subject: which language allows you to change an argument's value? In-Reply-To: <1191170989.227928.252880@g4g2000hsf.googlegroups.com> References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> <1191170989.227928.252880@g4g2000hsf.googlegroups.com> Message-ID: Summercool wrote: > On Sep 30, 4:18 am, 7stud -- wrote: >> SpringFlowers AutumnMoon wrote: >>> we have no way >>> of knowing what we pass in could get changed. >> Sure you do. You look at the function's signature. In order to use >> someone else's library, you have to know the function's signature. And >> the signature explicitly tells you whether the value you pass in could >> be changed. > > do you mean in C++? I tried to find signature in two C++ books and it > is not there. Google has a few results but it looks something like > prototype. Is signature the same as the function prototype in the .h > file? If so, don't we usually just include <___.h> and forget about > the rest. Documentation is fine although in some situation, the > descriptions is 2 lines, and notes and warnings are 4, 5 times that, > and the users' discussing it, holding different opinion is again 2, 3 > times of that length. I think in Pascal and C, we can never have an > argument modified unless we explicitly allow it, by passing in the > pointer (address) of the argument. > You need to get more C++ books :-). You generally won't find them in basic books, but some of the more advanced ones talk about function signatures. A C++ function's signature is dependent on the function name, number of parameters being passed, and the type of each parameter. This is passed onto the linker. In any C++ program, every function signature must be unique. But in this case he's a little incorrect. You *could* look at the function's signature, but it's much easier just to look at the function's declaration. > also i think for string, it is a bit different because by default, > string is a pointer to char or the address of the first char in C and C > ++. So it is like passing in the address already. it is when the > argument n is something like 1 that makes me wonder. > > -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From http Sat Sep 8 00:15:50 2007 From: http (Paul Rubin) Date: 07 Sep 2007 21:15:50 -0700 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> <7x3axq7a8a.fsf@ruckus.brouhaha.com> <7xodgejx3l.fsf@ruckus.brouhaha.com> <13e43ups034ld13@corp.supernews.com> Message-ID: <7xwsv1n66h.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > Sorry, make that 32 or 40 instead of 10, if the number of id's is large, > > to make birthday collisions unlikely. > > I did a small empirical test, and with 16 million ids, I found no > collisions. 16 million 32-byte ids? With string and dictionary overhead that's probably on the order of 1 GB. Anyway, 16 bytes is enough, as mentioned elsewhere. > However, I did find that trying to dispose of a set of 16 million short > strings caused my Python session to lock up for twenty minutes until I > got fed up and killed the process. Should garbage-collecting 16 million > strings really take 20+ minutes? Maybe your system was thrashing, or maybe the GC was happening during allocation (there was some discussion of that a while back). > > If you don't want the id's to be that large, you can implement a Feistel > I'm not sure that I need it, but I would certainly be curious to see it. I posted some code elsewhere in the thread. From phil at riverbankcomputing.co.uk Sun Sep 16 13:28:45 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 16 Sep 2007 18:28:45 +0100 Subject: SVG to raster conversion. In-Reply-To: <46ED5283.3030004@sdf.lonestar.org> References: <46ED5283.3030004@sdf.lonestar.org> Message-ID: <200709161828.45145.phil@riverbankcomputing.co.uk> On Sunday 16 September 2007, J. Cliff Dyer wrote: > Does anybody know a good solution (preferably in python) for rasterizing > SVG or other vector graphics. > > I'm thinking something like > > vector_image = SVGFile(path_to_image) > raster_image = vector_image.rasterize(format, (width, height), dpi) > raster_image.write(out_file) > > Thanks for any pointers you might have. PyQt has QSVGRenderer (http://doc.trolltech.com/4.3/qsvgrenderer.html) which will render to a QPixmap (http://doc.trolltech.com/4.3/qpixmap.html) which you can save in a number of standard formats. Phil From bj_666 at gmx.net Sat Sep 22 08:34:21 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2007 12:34:21 GMT Subject: Writing Object Data to Disk References: Message-ID: <5lkgedF8gic1U7@mid.uni-berlin.de> On Sat, 22 Sep 2007 17:13:14 +0530, Amit Kumar Saha wrote: > BTW, do we have something like array of objects here? Like someone already said: lists. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu Sep 6 11:44:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Sep 2007 08:44:42 -0700 Subject: ImportError depending on the calling module In-Reply-To: <1189079269.279716.254560@50g2000hsm.googlegroups.com> References: <1189079269.279716.254560@50g2000hsm.googlegroups.com> Message-ID: <1189093482.137051.73770@r29g2000hsg.googlegroups.com> On 6 sep, 08:47, Samuel wrote: > Given the following directory structure: > > --------- > |-- Obj.py > |-- __init__.py > |-- foo > | |-- FooTest.py > | `-- __init__.py > `-- start1.py > --------- The container looks like a package (you didn't tell us the name). Should be placed somewhere accessible thru sys.path start1.py does NOT belong to the package, neither start2.py; place them somewhere else. They should import the package as any other client code, without doing any import tricks nor playing with sys.path. -- Gabriel Genellina From paddy3118 at googlemail.com Sat Sep 1 03:24:17 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 01 Sep 2007 07:24:17 -0000 Subject: list index() (OT) In-Reply-To: References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1cnfd31du01el95u70o8mjn9cb5r5aluiu@4ax.com> Message-ID: <1188631457.050512.103060@y42g2000hsy.googlegroups.com> On Sep 1, 7:57 am, "Hendrik van Rooyen" wrote: > "Richie Hindle" wrote: > > But - the word for someone who posts to the internet with the intention of > > stirring up trouble derives from the word for what fishermen do, not from > > the word for something that lives under a bridge. It derives from "trolling > > for suckers" or "trolling for newbies". > > So am I right in asserting that there is a difference in pronunciation > of the noun and the verb? > > He is a Troll - like the excellent frolic example > He likes to Troll - rhymes with roll? > > - Hendrik No difference. A troll is a troll is a troll. :-) - Paddy. From hniksic at xemacs.org Thu Sep 27 10:15:21 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 27 Sep 2007 16:15:21 +0200 Subject: PyObject_CallObject: difference between functions and class methods References: <1190900895.635795.262350@y42g2000hsy.googlegroups.com> Message-ID: <87ejgkurd2.fsf@mulj.homelinux.net> [ Note that there is now a mailing list dedicated to the C API: http://mail.python.org/mailman/listinfo/capi-sig ] mauro writes: > I am trying to call within a C extension a Python function provided as > an argument by the user with: PyObject_Call(). The C extension should > work also if the user supplies a class method, but in this case I am > getting an error. Do I need to explicitly pass 'self' as an argument > to PyObject_Call()? You don't. The reference to self will be added automatically when invoking the function you receive as object.method. > if ((tmp_args = PyTuple_New(1)) == NULL) > PyErr_SetString( PyExc_ReferenceError, "attempt to access a null- > pointer" ); > PyTuple_SetItem(tmp_args, 0, paramlist); Maybe you are mismanaging the reference count -- PyTuple_SetItem steals the refcount of its argument. Anyway, why not use PyObject_CallFunction or PyObject_CallFunctionObjArgs? For example: PyObject * mymodule_main(PyObject *ignored, PyObject *func) { PyObject *result, *my_param; /* ... do something, e.g. create my_param ... */ /* call func */ result = PyObject_CallFunction(received_func, "O", my_param); Py_DECREF(my_param); /* assuming you no longer need it */ if (!result) return NULL; /* ... do something with result ... */ Py_DECREF(result); Py_INCREF(Py_None); return Py_None; /* or whatever */ } From rikard.bosnjakovic at gmail.com Sat Sep 15 00:07:31 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Sat, 15 Sep 2007 06:07:31 +0200 Subject: [Tutor] Is there some sort of Python Error log. In-Reply-To: References: Message-ID: On 15/09/2007, Lamonte Harris wrote: > Command prompt is a pain and it would be pretty nice to have this feature. If you are using a Unixish system, do "python myscript.py 2> error.log". -- - Rikard - http://bos.hack.org/cv/ From darien.watkins at gmail.com Tue Sep 11 14:56:27 2007 From: darien.watkins at gmail.com (darien.watkins at gmail.com) Date: Tue, 11 Sep 2007 11:56:27 -0700 Subject: Python Database Apps In-Reply-To: References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> Message-ID: <1189536987.259907.68650@e34g2000pro.googlegroups.com> On Sep 11, 9:25 am, Ed Leafe wrote: > On Sep 10, 2007, at 10:52 PM, darien.watk... at gmail.com wrote: > > > Kindof a poll, kindof curiosity... > > > What is your favorite python - database combination? I'm looking to > > make an app that has a local DB and a server side DB. I'm looking at > > python and sqlite local side and sql server side. > > Are you asking for opinions on what sort of database engine to use? > Or are you trying to get a feel for what people use to develop their > apps? Are you looking for a web app, or a desktop app, or a non-UI app? > > -- Ed Leafe > --http://leafe.com > --http://dabodev.com It would help to get a feel of what is the most popular combination for people to develop their apps. It's gonna be a desktop app. The database engine is going to be the critical component. I like sqlite so that I don't need a database server on the client side. It would help though if there is a way to sync between multiple clients to a central server database. That's the tough part. To give you a better idea of what i'm trying to do, I am trying to write an app where multiple technicians have an issue tracker that is available both offline and online. I was looking to use sqlite as the local side that would sync new and updated issues to a central server when online. Any technician may work on any issue. Generally they will not be working on the same issue at the same time. The technicians are geographically diverse (anywhere in the southeast US, not in an office.) Thanks for the feedback so far... Darien From bronger at physik.rwth-aachen.de Thu Sep 6 02:38:45 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 06 Sep 2007 08:38:45 +0200 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? References: <46DEFD2E.5050205@sbcglobal.net> <87tzq898e2.fsf@wilson.homeunix.com> <87ejhc8z23.fsf@wilson.homeunix.com> <13dv7biiu70252d@corp.supernews.com> Message-ID: <87wsv4xpqi.fsf@wilson.homeunix.com> Hall?chen! Steven D'Aprano writes: > On Thu, 06 Sep 2007 03:31:43 +0000, Alan Isaac wrote: > >>> Their only flaw is that they are not "virtual" (in C++ speak). >>> In other words, you can't pass a "self" parameter to them. >> >> http://www.kylev.com/2004/10/13/fun-with-python-properties/ > > > I'm not 100% sure I get what problem that piece of code is > supposed to solve, but if I have understood it, the obvious > solution is to use inheritance, not nasty tricks with lambdas. Yes, it is the right solution for the wrong problem. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From horpner at yahoo.com Fri Sep 7 13:22:03 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 07 Sep 2007 17:22:03 GMT Subject: interesting puzzle......try this you will be rewarded... References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> <46e04138$0$16377$88260bb3@free.teranews.com> <1189130241.529344.52950@57g2000hsv.googlegroups.com> Message-ID: On 2007-09-07, Gabriel Genellina wrote: > En Thu, 06 Sep 2007 22:57:21 -0300, Basilisk96 > escribi?: > >> I got to 14 :) >> >> It's rather silly. >> >> I remember seeing a more elaborate puzzle that involved coding, >> cryptography knowledge, etc. to get through it. But what was the link, >> I forget now... > > Me too, and I can't find that link either. #15 is a bit > difficult for people outside US, and spelling on #21 is > questionable, but I liked this woody thing :) Y'all may be thinking of The Euler Project, which provides math puzzles for programmers. http://projecteuler.net/ -- Neil Cerutti I pulled away from the side of the road, glanced at my mother-in-law and headed over the embankment. --Insurance Claim Blooper From bignose+hates-spam at benfinney.id.au Thu Sep 27 21:34:01 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 28 Sep 2007 11:34:01 +1000 Subject: Numeric command-line options vs. negative-number arguments (was: getopt with negative numbers?) References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <0a6dnQmBPIzuqmHbnZ2dnUVZ_vihnZ2d@comcast.com> Message-ID: <87ejgj4lpy.fsf_-_@benfinney.id.au> Steven Bethard writes: > In most cases, argparse (http://argparse.python-hosting.com/) > supports negative numbers right out of the box, with no need to use > '--': > > >>> import argparse > >>> parser = argparse.ArgumentParser() > >>> parser.add_argument('-a', type=int) > >>> parser.add_argument('b', type=int) > >>> args = parser.parse_args('-a -42 -123'.split()) > >>> args.a > -42 > >>> args.b > -123 That would be irritating. I've used many programs which have numbers for their options because it makes the most sense, e.g. 'mpage' to indicate number of virtual pages on one page, or any number of networking commands that use '-4' and '-6' to specify IPv4 or IPv6. If argparse treats those as numeric arguments instead of options, that's violating the Principle of Least Astonishment for established command-line usage (hyphen introduces an option). -- \ "I went to a general store. They wouldn't let me buy anything | `\ specifically." -- Steven Wright | _o__) | Ben Finney From gnewsg at gmail.com Mon Sep 10 10:08:33 2007 From: gnewsg at gmail.com (billiejoex) Date: Mon, 10 Sep 2007 07:08:33 -0700 Subject: How can I test 'warnings' from testsuite? Message-ID: <1189433313.296787.166060@22g2000hsm.googlegroups.com> Hi there, into a module of mine I 'warn' a message if a certain situation occurs: def add_anonymous_user(permissions=('r'): if 'w' in p: import warnings warnings.warn("it's not rencommended assigning 'w' permission to anonymous user.", RuntimeWarning, stacklevel=2) I'd like to test such event from test suite ("fail test if warn is not raised") but don't know how. Any suggestion? From jcd at sdf.lonestar.org Tue Sep 11 16:49:01 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Tue, 11 Sep 2007 16:49:01 -0400 Subject: Car-ac-systems In-Reply-To: References: <5ko2rjF4om2bU1@mid.uni-berlin.de> Message-ID: <20070911204901.GA6188@sdf.lonestar.org> On Tue, Sep 11, 2007 at 07:50:33PM +0100, John Timney (MVP) wrote regarding Re: Car-ac-systems: > > "Marc 'BlackJack' Rintsch" wrote in message > news:5ko2rjF4om2bU1 at mid.uni-berlin.de... > > On Tue, 11 Sep 2007 17:42:53 +0000, Zentrader wrote: > > > >> > >> What is it about "please do not top-post" that you have difficulty > >> understanding? Or do "MVP"s feel that their time is so much more > >> valuable than anyone else's that they are free to ignore the norms? > >> > >> Who made this the norm? > > > > Common sense and (western) reading habits. > > > >> In my travels through web-land, it appears to be the opposite. > > > > You must travel strange territories. ;-) > > > >> Don't waste space repeating everything in every post, and it wastes > >> everyone's time by have to go over the same thing again and again. > > > > That's why you trim the quoted part to the minimum to understand what one > > is answering. Top posting and full quoting wastes time for people who > > want to see the context because context and answer are way apart and in > > the > > wrong order so one has to scroll back and forth to keep track of the > > discussion. > > > > Ciao, > > Marc 'BlackJack' Rintsch > > > I like top posted threads, its my preferred response method - and actually > also how I prefer to read a thread. Normally, I and the thread followers > are familiar with a threads context - and don't need to read down to get the > context of a response. Not much of a hardship really and just as I give my > time freely in answering a thread - everyone else can chose freely to read > it or ignore. > > I don't though have no issues with people who chose to bottom post, or > respond with the full thread if its relevent, or trim it. If the answer is > relevent, I'll gladly spend the time reading it from any direction. > > Regards > > John Timney (MVP) Thank you for your courtesy in bottom posting that comment, in spite of your personal preference. It makes the group easier to follow. Personally, I have nothing against top-posted comments. What really gets my panties in a bunch, however, are threads in which some replies are top-posted and some bottom posted. Then, in order to get the full story you end up bouncing back and forth through the message and trying to remember how deeply nested the last post was. Cheers, and welcome to c.l.py. Cliff From danfike at gmail.com Mon Sep 24 11:13:53 2007 From: danfike at gmail.com (danfike at gmail.com) Date: Mon, 24 Sep 2007 15:13:53 -0000 Subject: Building Python with VC8 on x64 Vista In-Reply-To: <46F52FFD.3040500@v.loewis.de> References: <1190299551.573204.322440@57g2000hsv.googlegroups.com> <46F52FFD.3040500@v.loewis.de> Message-ID: <1190646833.144905.40030@19g2000hsx.googlegroups.com> On Sep 22, 10:08 am, "Martin v. L?wis" wrote: > > 1>py_dyn_test.obj : error LNK2001: unresolved external symbol > > _Py_NoneStruct > > Could it be that py_dyn_test.obj is a x86 (not AMD64) object > file? Run dumpbin. Hmm - I've never used dumpbin, but I think I like it. It doesn't look like these are x86, though. See below: D:\....\py_dyn_test\x64\Debug>dumpbin /HEADERS py_dyn_test.obj Microsoft (R) COFF/PE Dumper Version 8.00.50727.762 Copyright (C) Microsoft Corporation. All rights reserved. Dump of file py_dyn_test.obj File Type: COFF OBJECT FILE HEADER VALUES 8664 machine (x64) .... D:\....\3rdParty\Python25\libs>dumpbin /HEADERS python25_d.lib Microsoft (R) COFF/PE Dumper Version 8.00.50727.762 Copyright (C) Microsoft Corporation. All rights reserved. Dump of file python25_d.lib File Type: LIBRARY FILE HEADER VALUES 8664 machine (x64) 3 number of sections 46F3CED2 time date stamp Fri Sep 21 09:01:54 2007 113 file pointer to symbol table 8 number of symbols 0 size of optional header 0 characteristics Version : 0 Machine : 8664 (x64) TimeDateStamp: 46F3CED2 Fri Sep 21 09:01:54 2007 SizeOfData : 0000001E DLL name : python25_d.dll Symbol name : _Py_NoneStruct Type : data Name type : name Hint : 900 Name : _Py_NoneStruct From http Sun Sep 9 13:09:14 2007 From: http (Paul Rubin) Date: 09 Sep 2007 10:09:14 -0700 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> <7xhcm4pl5m.fsf@ruckus.brouhaha.com> Message-ID: <7xwsuzdav9.fsf@ruckus.brouhaha.com> Bryan Olson writes: > I haven't kept up. Has anyone exhibited a SHA-1 collision? I don't think anyone has shown an actual collision, but apparently there is now a known way to find them in around 2**63 operations. I don't know if it parallellizes as well as a brute force attack does. If it does, then it's presumably within reach of the distributed attacks like the ones used against DES in the late 1990's, given the hardware speedups that have occurred since then. NIST is trying to phase out SHA-1 by 2010. http://en.wikipedia.org/wiki/SHA1#Cryptanalysis_of_SHA-1 http://csrc.nist.gov/hash_standards_comments.pdf From prikar20 at gmail.com Wed Sep 19 23:46:08 2007 From: prikar20 at gmail.com (prikar20 at gmail.com) Date: Thu, 20 Sep 2007 03:46:08 -0000 Subject: Sets in Python In-Reply-To: <1190247922.835055.31950@y42g2000hsy.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <1190239608.835359.51150@22g2000hsm.googlegroups.com> <1190244370.741482.6540@y27g2000pre.googlegroups.com> <1190247922.835055.31950@y42g2000hsy.googlegroups.com> Message-ID: <1190259968.214528.158370@v29g2000prd.googlegroups.com> On Sep 19, 5:25 pm, Mark Dickinson wrote: > On Sep 19, 7:26 pm, Karthik Gurusamy wrote: > > > If I did, a = [10, 20] and I did d[a]= 'foo', then a.append(30). > > If dict complains key error on d[a] now, I won't be surprised. If I do > > d[[10, 20, 30]], I will be surprised if it doesn't find the item. Of > > course, in today's behavior the above is syntax error. > > It sounds as though you're proposing something like the following: > > >>> k = mylist([1, 2]) > >>> d = {k : 'test'} > >>> d[k] > 'test' > >>> k.append(3) > >>> d[k] > > Traceback (most recent call last): > File "", line 1, in > KeyError: [1, 2, 3] > > So far, so good. But how do you explain the following to a confused > newcomer? > > >>> d.keys() > [[1, 2, 3]] > >>> k in d.keys() > True > >>> k in d > False > >>> d[k] > > Traceback (most recent call last): > File "", line 1, in > KeyError: [1, 2, 3] > > In other words, to repeat Sion Arrowsmith's question, what would you > expect d.keys() to return after a key of d has been modified? In the new model, it should be the value at the time of addition. That is [1,2] (not [1,2,3]). This does mean a copy of key in maintained internally in the dict. I think today that's not needed (just a reference to the key's object is sufficient). Again, this may not be the most elegant solution; neither seems to be the current requirement that keys must be immutable. Fundamentally dict is a mapping; underneath it could even use other elaborate algorithms (say for integer keys, an avl tree) -- there is no reason to expose the the quirks of hashing to the programmer. Karthik > > Mark From brice.fernandes at gmail.com Sun Sep 23 12:28:44 2007 From: brice.fernandes at gmail.com (brice.fernandes at gmail.com) Date: Sun, 23 Sep 2007 09:28:44 -0700 Subject: building a GUI In-Reply-To: References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> Message-ID: <1190564924.417792.287930@o80g2000hse.googlegroups.com> On Sep 23, 4:28 pm, stef mientki wrote: > yadin wrote: > > if i were up to make a GUI chich are the advantages of choosing python > > over matlab or java? > > As MatLab has a very lousy GUI, > any other language would be an advantage ;-) > > The best is Delphi, > second is VB, > then comes SciLab, Python, etc > I don't know where Java fits in. > > But as Wildemar said, your question is much to broad. > > cheers, > Stef Form a newbie's point of view, Java's Swing Libraries (gui stuff) are pretty easy to get to grips with, if a bit big. They are also incredibly well documented, and are distributed by sun with the core language. Compared to most python toolkits, they are approximately as complex, but far better documented. The other good thing compared to python is their integration at the language API level rather than as a supplementary module. A quick look at the 1.6 swing tutorial will tell you whether this is something you'd like to use: http://java.sun.com/docs/books/tutorial/uiswing/start/index.html hope this helps brice From greg at cosc.canterbury.ac.nz Mon Sep 24 22:15:17 2007 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 25 Sep 2007 14:15:17 +1200 Subject: ANN: 555-BOOM! version 0.6 Message-ID: I have released a post-competition version of my PyWeek 5 game competition entry, 555-BOOM!. http://www.cosc.canterbury.ac.nz/greg.ewing/python/PyWeek5/index.html This version has been tidied up in various ways, and a few more levels added. I have made a number of improvements to the level editor; it should be easier and less confusing to use now. Documentation for the level editor is included. What is it? This is a game involving telephones, relays, rotary switches, and other electrical things that make nice whirring and clicking noises. As well as challenging yourself to solve the puzzles, you can also use the comprehensive built-in level editor to create new puzzles for yourself and others, or just to play around and have fun with the parts. -- Gregory Ewing greg.ewing at canterbury.ac.nz From Shawn at Milochik.com Tue Sep 4 14:19:45 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 4 Sep 2007 14:19:45 -0400 Subject: [Tutor] Code reading for learning Python In-Reply-To: <46D61C0A.9090204@tds.net> References: <86105.56732.qm@web56412.mail.re3.yahoo.com> <46D61C0A.9090204@tds.net> Message-ID: <2dc0c81b0709041119j44dad31fn14b6cf6cdd83e160@mail.gmail.com> I second the Python Cookbook recommendation. From jcd at sdf.lonestar.org Mon Sep 10 22:49:31 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 10 Sep 2007 22:49:31 -0400 Subject: printing list containing unicode string In-Reply-To: <1189477580.214510.212420@22g2000hsm.googlegroups.com> References: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> <1189477580.214510.212420@22g2000hsm.googlegroups.com> Message-ID: <46E6023B.1090909@sdf.lonestar.org> Xah Lee wrote: > This post is about some notes and corrections to a online article > regarding unicod and python. > > -------------- > > by happenstance i was reading: > > Unicode HOWTO > http://www.amk.ca/python/howto/unicode > > Here's some problems i see: > > ? No conspicuous authorship. (however, oddly, it has a conspicuous > acknowledgement of names listing.) (This problem is a indirect > consequence of communism fanatism ushered by OpenSource movement) > (Originally i was just going to write to the author on some > corrections.) > > ? It's very wasteful of space. In most texts, the majority of the > code points are less than 127, or less than 255, so a lot of space is > occupied by zero bytes. > > Not true. In Asia, most chars has unicode number above 255. Considered > globally, *possibly* today there are more computer files in Chinese > than in all latin-alphabet based lang. > That's an interesting point. I'd be interested to see numbers on that, and how those numbers have changed over the past five years. Sadly, such data is most likely impossible to obtain. However, it should be pointed out that most *code*, whether written in the United States, New Zealand, India, China, or Botswana is written in English. In part because it has become a standard of sorts, much as italian was a standard for musical notation, due in part to the US's former (and perhaps current, but certainly fading) dominance in the field, and in part to the lack of solid support for unicode among many programming languages and compilers. Thus the author's bias, while inaccurate, is still understandable. > ? Many Internet standards are defined in terms of textual data, and > can't handle content with embedded zero bytes. > > Not sure what he mean by "can't handle content with embedded zero > bytes". Overall i think this sentence is silly, and he's probably > thinking in unix/linux. > > ? Encodings don't have to handle every possible Unicode > character, .... > > This is inane. A encoding, by definition, turns numbers into binary > numbers (in our context, it means a encoding handles all unicode chars > by definition). What he really meant to say is something like this: > "Practically speaking, most computer languages in western society > don't need to support unicode with respect to the language's source > file" > > ? > UTF-8 has several convenient properties: > 1. It can handle any Unicode code point. > ... > > > As mentioned before, by definition, any Unicode encoding encodes all > unicode char set. The mentioning of above as a "convenient property" > is inane. > No, it's not inane. UCS-2, for example, is a fixed width, 2-byte encoding that can handle any unicode code point up to 0xffff, but cannot handle the 3 and 4 byte extension sets. UCS-2 was developed for applications in which having fixed width characters is essential, but has the limitations of not being able to handle any Unicode code point. IIRC, when it was developed, it did handle every code point, and then Unicode grew. There is also a UCS-4 to handle this limitation. UTF-16 is based on a two-byte unit, but is variable width, like UTF-8, which makes it flexible enough to handle any code point, but harder to process, and a bear to seek through to a certain point. (I'm politely ignoring your ill-reasoned attacks on non-Microsoft OSes). Cheers, Cliff From eugene.vandenbulke at gmail.com Sat Sep 8 04:37:51 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Sat, 08 Sep 2007 10:37:51 +0200 Subject: python sqlite THREADSAFE? Message-ID: Hi, Is the sqlite distributed with Python 2.5 compiled with the -DTHREADSAFE=1 flag? My gutt feeling is Windows (yes) MacOS/Linux (no) but ... If it is not on MacOS/Linux, how do I go about replacing the sqlite so file with a threadsafe sqlite? Thanks, EuGeNe -- http://www.3kwa.com From stefan.behnel-n05pAM at web.de Fri Sep 21 08:50:22 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 21 Sep 2007 14:50:22 +0200 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> Message-ID: <46F3BE0E.8090001@web.de> W. Watson wrote: > Is vim just an editor or is it capable of running and debugging a > program, as well? Depends on how you define an editor. If you take Emacs as example for an editor, then, no, it's not an editor. BTW: >>> (It even gives useful advice on top-posting if you use it as a news >>> client :/) Stefan From linuxprog at gmail.com Mon Sep 24 05:42:23 2007 From: linuxprog at gmail.com (linuxprog) Date: Mon, 24 Sep 2007 09:42:23 +0000 Subject: SOAPpy Error Message-ID: <46F7867F.3090607@gmail.com> hi all i'm building a webservice client with soappy when i send some informations it's returns an error here is the informations that generates the error var = SOAPpy.structType() var._addItem("code", u"XysZjd") var._addItem("value", 1) when i send the var variable SOAPpy prints this File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 473, in __call__ return self.__r_call(*args, **kw) File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 495, in __r_call self.__hd, self.__ma) File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 366, in __call config = self.config) File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 228, in call data = r.getfile().read() AttributeError: 'NoneType' object has no attribute 'read' when i have activate debug , the debug mode shows : code : -1 msg : headers : None it should prints some thing like this if all goes well : code : 200 msg : OK headers : Date: Mon, 24 Sep 2007 09:08:45 GMT Server: Apache/2.2.3 (Debian) PHP/5.2.0-8+etch7 X-Powered-By: PHP/5.2.0-8+etch7 Content-Length: 2116 Connection: close Content-Type: text/xml; charset=utf-8 wha's wrong ? Thanks From rcdailey at gmail.com Mon Sep 24 20:37:20 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 24 Sep 2007 19:37:20 -0500 Subject: Regular Expressions: Can't quite figure this problem out Message-ID: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> Hi, I'm attempting to create a regular expression that removes redundancy in empty XML elements. For example: The regular expression would convert the XML above into: And another complex example: would be: So far I've been unsuccessful in creating a regular expression to do this. Below are outlined various guarantees: - The XML to be parsed shall have NO comments in it - The XML to be parsed shall have NO whitespace (spaces, tabs, carriage returns, etc) between elements. The examples above represent what this means. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Sep 2 04:46:37 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 02 Sep 2007 10:46:37 +0200 Subject: How best to dynamically define methods (and functions)? References: Message-ID: <5jvbjaF1ct31U1@mid.individual.net> Kenneth McDonald wrote: > I can see an obvious but hacky way to define a Python function at > runtime. What way is this? All Python function definitions in your code are executed at runtime. > In case it's of interest in the context of the question, I need to > define a largish set of functions (and similar methods) that > define a XML-type markup language. Most of these functions will > just be of the form > > def fun(...): > return Node('fun', ...) > > so it'd definitely be nice to just create most of them > automatically, and only do the special cases by hand. This looks cumbersome to me. If you reworked the interface (perhaps using dicts or a generic function) it might get clearer. Regards, Bj?rn -- BOFH excuse #241: _Rosin_ core solder? But... From timaranz at gmail.com Wed Sep 26 01:07:32 2007 From: timaranz at gmail.com (timaranz at gmail.com) Date: Tue, 25 Sep 2007 22:07:32 -0700 Subject: Missing documentation for ElementTree? In-Reply-To: References: <496954360709251539y2511a1cbnd25c6d3a0d368d2a@mail.gmail.com> Message-ID: <1190783252.777675.44180@r29g2000hsg.googlegroups.com> On Sep 26, 4:00 pm, "Gabriel Genellina" wrote: > En Tue, 25 Sep 2007 19:39:33 -0300, Robert Dailey > escribi?: > > > for the _ElementInterface class, there is no documentation for most of > > the > > members of this class such as .tail and .text. There's a brief > > description > > of these things on the front page of the ElementTree docs but nothing > > helpful. I have no idea what Tail is vs Text and I wanted to figure this > > out > > myself, however I don't think I can now. Anyone know if I'm just missing > > something in the documentation or if it really isn't in there? > > Start here:http://www.effbot.org/zone/element-index.htm > > -- > Gabriel Genellina Check out the development version of the documentation http://docs.python.org/dev/library/xml.etree.elementtree.html#module-xml.etree.ElementTree From gagsl-py2 at yahoo.com.ar Mon Sep 24 22:36:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Sep 2007 23:36:23 -0300 Subject: TRying to import files from my folder not pythons lib folder References: <1190395964.541835.114350@50g2000hsm.googlegroups.com> <1190396569.732154.234270@r29g2000hsg.googlegroups.com> <1190595699.093793.100960@w3g2000hsg.googlegroups.com> <1190684198.266529.85020@y42g2000hsy.googlegroups.com> Message-ID: En Mon, 24 Sep 2007 22:36:38 -0300, Luis M. Gonz?lez escribi?: > I solved the problem! > You were right. It seems there was a module that was causing problems, > although I don't know which one... > I just moved all the .py files on my desktop to a new folder, and > everything worked just fine. > The list of .py files in my desktop were: > > 'code.py', 'code2.py', 'code22.py', 'code3.py', 'draft.py', > 'flups.py', 'forma.py', 'fx.py', 'nuevo.py', 'nwind', 'ops', > 'pages.py', 'qqq.py', 'sample.py', 'ses.py', 'sess.py', 'sess2.py', > 'soup.py', 'style.py', 'test_session.py', 'up.py', 'up2.py', 'ww.py', > 'xx.pyw', 'xx.rsrc.py', 'xxxx.py' > > Any idea of which one was causing trouble? Possibly code.py, it's a standard module > Gracias, che! De nada loco! -- Gabriel Genellina From raychorn at hotmail.com Sat Sep 22 16:00:27 2007 From: raychorn at hotmail.com (Python Maniac) Date: Sat, 22 Sep 2007 13:00:27 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <5ljrklF8gic1U3@mid.uni-berlin.de> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> <1190394011.148384.106280@q3g2000prf.googlegroups.com> <1190417120.723579.267560@22g2000hsm.googlegroups.com> <5ljrklF8gic1U3@mid.uni-berlin.de> Message-ID: <1190491227.688310.247030@w3g2000hsg.googlegroups.com> On Sep 21, 11:39 pm, Marc 'BlackJack' Rintsch wrote: > On Fri, 21 Sep 2007 16:25:20 -0700, Python Maniac wrote: > > On Sep 21, 3:02 pm, "Matt McCredie" wrote: > > >> Isn't D compiled to machine code? I would expect it to win hands down. > >> That is, unless it is horribly unoptimized. > > > Well D code is compiled into machine code that runs via a VM. > > About which D are we talking here? Not digital mars' successor to C++, > right!? > > Ciao, > Marc 'BlackJack' Rintsch Yes, Digital Mars D is what I was referring to and yes I know D is not as efficient as C++. If I knew of a good C++ compiler that is not from Microsoft that works natively with Windows I would be happy to consider using it but alas the only one I have found so far is from Digital Mars. Digital Mars D has nice integration with Python via pyd and this is another plus, in my mind. From steve at holdenweb.com Fri Sep 28 18:16:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 18:16:51 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191013033.145194.193040@50g2000hsm.googlegroups.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <%q0Li.725$ih1.539@nlpi068.nbdc.sbc.com> <1i555ag.9ez4uvf4583jN%aleax@mac.com> <1191013033.145194.193040@50g2000hsm.googlegroups.com> Message-ID: <46FD7D53.1060403@holdenweb.com> Kay Schluehr wrote: > On 28 Sep., 17:53, John Nagle wrote: >> Alex Martelli wrote: >>> John Nagle wrote: >>>> TheFlyingDutchman wrote: >>>>> It seems that Python 3 is more significant for what it removes than >>>>> what it adds. >>>>> What are the additions that people find the most compelling? >>>> I'd rather see Python 2.5 finished, so it just works. >>> And I'd rather see peace on Earth and goodwill among men than _either_ >>> Python 3 or your cherished "finished" 2.5 -- the comparison and implied >>> tradeoff make about as much sense as yours. >> Insofar as Python has an organization, it's not adequately managing >> extension modules. Each extension module has its own infrastructure, >> with its own build procedures, its own bug list, and its own maintainers. >> There's not even an archive. Unlike CPAN, Cheese Shop is just a directory of >> URLs. > > John, can't you please piss off? > > Thanks, Kay > Oops! Let's get back to goodwill and peace to all men, can we - including {Flying Dutch,wo}men? crabbi-ly y'rs - steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From seanttierney at gmail.com Fri Sep 21 19:53:41 2007 From: seanttierney at gmail.com (Sean Tierney) Date: Fri, 21 Sep 2007 16:53:41 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <54e1e4bc0709211647v10140c13y90c9bd68007c8398@mail.gmail.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <54e1e4bc0709211647v10140c13y90c9bd68007c8398@mail.gmail.com> Message-ID: <54e1e4bc0709211653r2720b00cr67ab12223ce0fac2@mail.gmail.com> On 9/21/07, Sean Tierney wrote: > Just tell him that "functions are like all other variables and can > therefore be passed by other functions or returned by other functions. > " > > If your friend understands variables and functions and he can't make > the "leap" (and assuming you're right, of course) then your friend > doesn't [might not] understand variables and functions [and he might need patience b/c this stuff is hard and not everyone is as smart as everyone else]. > > Happy Friday. > > Sean [moderately overweight, self-admitted (very) slow learner.] > > On 9/21/07, Cristian wrote: > > On Sep 21, 3:44 pm, Ron Adam wrote: > > > > > I think key may be to discuss names and name binding with your friend. How > > > a name is not the object it self, like a variable is in other languages. > > > For example show him how an object can have more than one name. And discus > > > how names can be bound to nearly anything, including classes and functions. > > > > I could discuss name binding but it would be great if Python said this > > itself. After all, you can even bind a module with the foo = bar > > syntax by using __import__ function. If function definitions followed > > the same pattern, I think a beginner would subconsciously (maybe even > > consciously) realize that function names are just like everything > > else. Actually, this would be helpful for many people. If you come > > from a language like Java you're used to thinking of attributes and > > methods as living in different namespaces. I think a new syntax will > > encourage seasoned programmers think in a more Pythonic way. > > > > Python has done a very good job in easing people into programming. My > > friend doesn't come to me very often because the syntax is clear and > > simple and the builtin datatypes allow you to do so much. My goal is > > that I would never have to explain to him about name binding; that > > he'd pick it up by learning the language on his own. He's learned > > lists, dictionaries and even some OOP without me. I don't think name > > binding would be a stretch. > > > > > You could also discus factory functions with him. Once he gets that a > > > function can return another function, then it won't be so much of a leap > > > for a function to take a function as an argument. > > > > I think this isn't the most intuitive way of approaching first order > > functions. It's true that if a function can return another function > > then a function must be first order (i.e., it's just like any other > > variable), but that seems almost backwards to me. I think it would > > make more sense to have beginners _know_ that functions are like all > > > other variables and can therefore be passed by other functions or > > returned by other functions. That I think would be better accomplished > > if they define functions the same way you would define other variables > > that you know can be passed and returned. > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Sean Tierney > -- Sean Tierney From kyosohma at gmail.com Sat Sep 15 15:48:42 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 15 Sep 2007 19:48:42 -0000 Subject: (wxPython) wx.ProgressDialog - how to cancel out of? In-Reply-To: References: Message-ID: <1189885722.198714.266810@o80g2000hse.googlegroups.com> On Sep 15, 12:57 am, Terry Carroll wrote: > I'm trying to use wx.ProgressBar, and the cancel button is not > responding. > > Here is a simple program that exhibits the problem: > > ######################################################### > import wx > import time > > max = 10 > app = wx.PySimpleApp() > dlg = wx.ProgressDialog("Progress dialog example", > "variables to be shown here", > maximum = max, > style = wx.PD_CAN_ABORT > | wx.PD_CAN_SKIP > #| wx.PD_APP_MODAL > | wx.PD_ELAPSED_TIME > | wx.PD_ESTIMATED_TIME > | wx.PD_REMAINING_TIME > ) > > keepGoing = True > skip = False > count = 0 > > while keepGoing and count < max: > count += 1 > wx.MilliSleep(1000) > #time.sleep(1) > newtext = "(before) count: %s, keepGoing: %s, skip: %s " % \ > (count, keepGoing, skip) > print newtext > (keepGoing, skip) = dlg.Update(count, newtext) > newtext = "(after) count: %s, keepGoing: %s, skip: %s " % \ > (count, keepGoing, skip) > print newtext > dlg.Destroy() > ######################################################### > > The dialog looks right when this runs, but.... > > What's right: I get a progress bar; it includes "Skip" and "Cancel" > buttons; it shows 10 seconds of progress, and updates once per second > with the variables' values on each iteration. > > What's wrong is that I can't get clicking on the "Skip" or "Cancel" > buttons to have any effect. Instead, as soon as the dialog displays, > I get an hourglass, and it doesn't matter what I click on. Here's > what the print statements display, consistently, regardless of what I > try to click or whether I click nothing at all: > > I:\python>test1.py > (before) count: 1, keepGoing: True, skip: False > (after) count: 1, keepGoing: True, skip: False > (before) count: 2, keepGoing: True, skip: False > (after) count: 2, keepGoing: True, skip: True > (before) count: 3, keepGoing: True, skip: True > (after) count: 3, keepGoing: True, skip: True > (before) count: 4, keepGoing: True, skip: True > (after) count: 4, keepGoing: True, skip: True > (before) count: 5, keepGoing: True, skip: True > (after) count: 5, keepGoing: True, skip: True > (before) count: 6, keepGoing: True, skip: True > (after) count: 6, keepGoing: True, skip: True > (before) count: 7, keepGoing: True, skip: True > (after) count: 7, keepGoing: True, skip: True > (before) count: 8, keepGoing: True, skip: True > (after) count: 8, keepGoing: True, skip: True > (before) count: 9, keepGoing: True, skip: True > (after) count: 9, keepGoing: True, skip: True > (before) count: 10, keepGoing: True, skip: True > (after) count: 10, keepGoing: True, skip: True > > Two oddities here: > > 1) As I read the docs, the keepGoing variable should be set to True, > unless I click on "Cancel," in which case it should be set to False > (which would end the loop). That doesn't happen. This is really what > I'm most concerned here with. > > 2) The variable "skip: set to False on the first iteration, and then > set to True on subsequent iterations? Note that this happens even if > no buttons are selected. This is just a weirdness to me, and not my > main concern, but I thought I'd mention it in case it's relevant. > > You can see some variations in the commented-out code that I tried; > they did not help. > > Relevant software and releases: > > OS: Windows XP Home Edition, Version 2002, SP2 > Python: ActivePython 2.5.0.0 > wxPython: 2.8.1.1 (msw-unicode) > > Any help appreciated. I'm not seeing the error either. The code looks very similar to the example in the demo. Maybe you can look at it and see the difference? The only thing I see is that the demo embeds the ProgressDialog into a Panel object. You should probably post this to the wxPython mailing group: http://wxpython.org/maillist.php Mike From lasses_weil at klapptsowieso.net Sun Sep 2 15:00:45 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 02 Sep 2007 21:00:45 +0200 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <46DB04DD.80801@v.loewis.de> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> Message-ID: <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> Martin v. L?wis wrote: >>> (2) it is a interpretation language >> Not quite. It's compiled to byte-code - just like Java (would you call >> Java an 'interpreted language' ?) > > Python is not implemented like Java. In Java (at least in HotSpot), > the byte code is further compiled to machine code before execution; > in Python, the byte code is interpreted. > OK, good. Naive question now comming to mind: Why doesn't Python do the latter as well? /W From harry.g.george at boeing.com Thu Sep 6 01:47:31 2007 From: harry.g.george at boeing.com (Harry George) Date: Thu, 6 Sep 2007 05:47:31 GMT Subject: SSL Issue References: Message-ID: Jurian Botha writes: > Sorry if this is a real dumb question, but I'm totally stumped. > > I'm trying to connect to a https url in order to do some xml-rpc method > calls, but I'm getting the following error: > > Error Type: sslerror > Error Value: (6, 'TLS/SSL connection has been closed') > > What could be causing this error, any clues would be greatly appreciated. > > Thanks > -- > View this message in context: http://www.nabble.com/SSL-Issue-tf4388062.html#a12510772 > Sent from the Python - python-list mailing list archive at Nabble.com. > I don't have a complete story, but here are some hints: 1. The message is from: http://www.openssl.org/docs/ssl/SSL_get_error.html (see "ZERO RETURN") probably as filtered by PyOpenSSL, which has its own issues: http://mail.python.org/pipermail/python-dev/2007-August/074322.html 2. Chances are that your certificates are out of whack, or you are misusing the SSL context parameters, or are not telling the HTTP Connection object about the SSL Connection properly. 3. Debugging at the python layer is easier (put print statements in M2Crypto's SSL/Context and SSL/Connection) but if necessary, dive into openssl: http://www.mail-archive.com/openssl-users at openssl.org/msg49287.html 4. You can check for the "hello" handshake using WireShark. 5. I haven't found a tutorial for full Python client/server over HTTPS with verification of both client and server certificates. If that is where you are going, let me know what works. -- Harry George PLM Engineering Architecture From mail at microcorp.co.za Tue Sep 25 02:34:21 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 25 Sep 2007 08:34:21 +0200 Subject: Google and Python References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com><1190231094.276099.136250@22g2000hsm.googlegroups.com><1190235678.019823.315850@o80g2000hse.googlegroups.com><7xejgr68pm.fsf@ruckus.brouhaha.com> Message-ID: <000b01c7ff46$5e33dfc0$03000080@hendrik> "Nick Craig-Wood" wrote: > Passing file descriptors between processes is one of those things I've > always meant to have a go with, but the amount of code (in Advanced > Programming in the Unix Environment) needed to implement it is rather > disconcerting! A python module to do it would be great! I must be missing something here. What is the advantage of passing the open file rather than just the fully qualified file name and having the other process open the file itself? I would tend to not go this route, but would opt for one "file owner" process and use a message based protocol if heavy sharing is envisaged. It feels "more right" to me than to have different processes read and write to the same thing. I can imagine big Dragons with sharp teeth... - Hendrik From fakeaddress at nowhere.org Wed Sep 26 23:24:30 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 27 Sep 2007 03:24:30 GMT Subject: database persistence with mysql, sqlite In-Reply-To: References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> <1190650748.590245.221490@n39g2000hsh.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In Bryan Olson wrote: > >> coldpizza wrote: >>> It turned out that the method above ('SELECT * FROM TABLE LIMIT L1, >>> L2') works ok both with mysql and sqlite3, therefore I have decided to >>> stick with it until I find something better. With Sqlite3 you are >>> supposed to use LIMIT 10 OFFSET NN, but it also apparently supports >>> the mysql syntax (LIMIT NN, 10) for compatibility reasons. >> A more reliable form is along the lines: >> >> SELECT keyfield, stuff >> FROM table >> WHERE keyfield > ? >> ORDER BY keyfield >> LIMIT 10 >> >> With the right index, it's efficient. > > But that involves keeping track of the right starting keyfield value for the > next batch of records, which is complicated and nontrivial. I think you missed the idea here. Recall that we return a web page showing 10 records and a 'Next' link. We write the link so that the browser will send back the parameter we need. If the largest keyfield value on the page is "Two-Sheds" the link might read: Next The solution is stateless. There's no "keeping track" on the server side. When we respond to a request, we neither look up a previous request nor store anything for a future response. > Simpler to let > the DBMS do the work for you. Keeping a cursor with pending data across HTTP requests is a world of hurt. -- --Bryan From grante at visi.com Sat Sep 22 01:19:42 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 22 Sep 2007 05:19:42 -0000 Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> Message-ID: <13f99fediasg3ae@corp.supernews.com> On 2007-09-22, Carl Banks wrote: > Anyone with me here? (I know the deadline for P3 PEPs has passed; this > is just talk.) Not me. > Not many people are bit-fiddling these days. I do. > One of the main uses of bit fields is flags, but that's not > often done in Python because of keyword arguments and dicts, > which are lot more versatile. Another major use, talking to > hardware, is not something oft done in Python either. I do it all the time. Bit fiddling is also required for implementing communications prototocols. > It seems like this occasional usage wouldn't justify having built-in > operators on its own. And with the int/long unification, it makes a bit > less sense to think of integers as a bit field. Python has these > operators because of its heritage, but Python continues to move away from > the bad habits of its ancestors (integer division and so on), and I > wonder if this isn't another one. > > Of course I'm not suggesting to get rid of bitwise operations altogether; > just make them builtin functions: "x & 1" becomes "bitwise_and(x,1)" and > so on. > > Is it worth it to make such a change? It would remove a lot of operators > (11 by my count), vastly simplifying syntax, Which, IMHO, is no small > thing. If you don't want to use the bitwise operations, then ignore them. Presto! Simpler syntax. > Obviously, how widespread their usage is would matter. But keep in mind > it would also be easy to convert the code automatically, because the > Python parser could reliably find all bitwise operations reliably. The resulting code wold be fugly. -- Grant From jura.grozni at gmail.com Wed Sep 19 15:33:08 2007 From: jura.grozni at gmail.com (azrael) Date: Wed, 19 Sep 2007 12:33:08 -0700 Subject: Help for Otsu implementation from C In-Reply-To: References: <1190201086.468348.274850@g4g2000hsf.googlegroups.com> Message-ID: <1190230388.764546.114690@57g2000hsv.googlegroups.com> I know. The translation is not so important to me, because this is going to just a little function that is working in the last step of the whole proces. The whole implementation wont be published and has just the meaning to implement a first alpha version of a face recognition system. It is nearly finished, and this is the only function I am missing. For this purpose I need it to work "EXACTLY". I know that it doesnt look pythonic. After I know that it works correctly, I am going to write a total Rewrite for the Beta Version. On Sep 19, 1:55 pm, Peter Otten <__pete... at web.de> wrote: > azrael wrote: > > Can somone look at this > > def otsu(hi): > > fmax=-1.0 > > border=len(hi) > > for i in range(border): > > if hi[i]!=0:break > > for j in range(border-1,0-1,-1): > > if hi[j] != 0:break > > s = sum([k*hi[k] for k in range(border)]) n = sum(hi) # > > product(im.size) > > n1=n2=csum=0.0 > > for k in range(i,j): > > n1 += hi[k] > > n2 = n - n1 > > csum+= k * hi[k] > > m1 = csum/ n1 > > m2 = (s - csum)/n2 > > As I said in my previous post, try replacing this line > > > sb = n1 * n2 * (m2 - m1) > > with the original > > sb = n1 * n2 * (m1 - m2) * (m1 - m2) > > that has been commented out. > > > if sb > fmax: > > fmax = sb > > V=k+1 > > print V > > I try to implement it from C from this location. > > Personally, I would start with a literal translation and not try to > improve it until it works. > > Peter From list-ener at strank.info Thu Sep 6 07:37:50 2007 From: list-ener at strank.info (Stefan Rank) Date: Thu, 06 Sep 2007 13:37:50 +0200 Subject: Nudge needed for rst to html In-Reply-To: <46DFE179.40003@timgolden.me.uk> References: <46DFE179.40003@timgolden.me.uk> Message-ID: <46DFE68E.2080906@strank.info> on 06.09.2007 13:16 Tim Golden said the following: > I'm a bit embarrassed about this, but I've scoured > the docutils docs and I can't seem to work out how > to take a block of ReStructuredText and output a > raw HTML fragment, ideally without a surrounding > document or embedded/linked css etc. (I'm trying > to allow rst in our helpdesk system which can render > nicely on the web version and be readable in text). > > I thought that: > > > import docutils.core > > html = docutils.core.publish_string ("Hello, world!", writer_name="html") > > > > would do the trick, but that produces an entire document with > an embedded style block. try this:: import docutils.core parts = docutils.core.publish_parts("Hello!", writer_name="html") html = parts['body'] tfm: http://docutils.sourceforge.net/docs/api/publisher.html cheers, stefan From paul at boddie.org.uk Wed Sep 26 08:13:56 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 26 Sep 2007 05:13:56 -0700 Subject: setuptools without unexpected downloads In-Reply-To: <5luv0iFaai82U1@mid.uni-berlin.de> References: <87ejgmklep.fsf@benfinney.id.au><874phhlupi.fsf@benfinney.id.au> <5lumarFae888U1@mid.uni-berlin.de> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> <5luv0iFaai82U1@mid.uni-berlin.de> Message-ID: <1190808836.056298.232640@57g2000hsv.googlegroups.com> On 26 Sep, 13:44, "Diez B. Roggisch" wrote: > > Do I understand that correctly that essentially you're saying: if you want > your software released for a certain distro, package it up for it the way > it's supposed to be? I can understand that and said so myself - but then, > the whole setuptools-debate has come to an end. Yes, my preference is to install software as native packages, although I'm generally spoilt by the selection of packages available and the availability of packaging for current and previous versions of a lot of Python packages for my system. One problem with promoting system/ native packages is that it can be difficult for people not using the target platform to actually build the packages themselves, thus requiring some kind of package maintainer role to be filled by another person, but generally any demand on a given system for a package leads to that role being filled by a community member fairly quickly. And there are some existing semi-automated solutions, too, such as stdeb and the distutils bdist_rpm option. Paul P.S. Of course, the package maintainer problem manifests itself most prominently on Windows where you often see people asking for pre-built packages or installers. From bj_666 at gmx.net Sun Sep 16 02:24:09 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Sep 2007 06:24:09 GMT Subject: Needless copying in iterations? References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> Message-ID: <5l40g9F655kfU1@mid.uni-berlin.de> On Sun, 16 Sep 2007 00:40:13 +0000, Steven D'Aprano wrote: > On Sun, 16 Sep 2007 00:05:58 +0000, Marc 'BlackJack' Rintsch wrote: > > In *general* the compiler can't tell, but in specific cases it could. A > (hypothetical) optimizing compiler would tell the difference between: > > > for item in alist[1:5]: > print item # no possible side-effects To expand on what Ben said: After conversion to `str` the result is then given to `sys.stdout.write()` and of course `sys.stdout` could be another object that changes `alist`. > for item in alist[1:5]: > alist.append(item) # side-effects DON'T matter Side effect do matter here, even in not so pathological cases. There are cases where you get a different result whether you copy or not even with plain vanilla `list`\s: In [153]: alist = [1, 2, 3] In [154]: for item in alist[1:5]: .....: alist.append(item) .....: In [155]: alist Out[155]: [1, 2, 3, 2, 3] In [156]: alist = [1, 2, 3] In [157]: for item in islice(alist, 1, 5): .....: alist.append(item) .....: In [158]: alist Out[158]: [1, 2, 3, 2, 3, 2, 3] Ciao, Marc 'BlackJack' Rintsch From dohertywa at gmail.com Mon Sep 17 16:12:18 2007 From: dohertywa at gmail.com (dohertywa) Date: Mon, 17 Sep 2007 13:12:18 -0700 Subject: pattern combinations In-Reply-To: References: Message-ID: <1190059938.527265.292000@57g2000hsv.googlegroups.com> On Sep 17, 3:11 pm, "Shawn Milochik" wrote: > On 9/17/07, dorje tarap wrote: > > > > > Hi all, > > > Given some patterns such as "...t...s." I need to make all possible > > combinations given a separate list for each position. The length of the > > pattern is fixed to 9, so thankfully that reduces a bit of the complexity. > > > For example I have the following: > > > pos1 = ['a',' t'] > > pos2 = ['r', 's'] > > pos3 = ['n', 'f'] > > > So if the pattern contains a '.' character at position 1 it could be 'a' or > > 't'. For the pattern '.s.' (length of 3 as example) all combinations would > > be: > > > asn > > asf > > tsn > > tsf > > > Thanks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Sounds like homework to me. Checkout http://probstat.sf.net/ it will sort you out quick. From ricaraoz at gmail.com Fri Sep 7 13:59:12 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 07 Sep 2007 14:59:12 -0300 Subject: Finding specific date ranges In-Reply-To: <46E02369.6020504@timgolden.me.uk> References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> <46E02369.6020504@timgolden.me.uk> Message-ID: <46E19170.4020409@bigfoot.com> Tim Golden wrote: > kyosohma at gmail.com wrote: >> Hi, >> >> I am working on a timesheet application in which I need to to find the >> first pay period in a month that is entirely contained in that month >> to calculate vacation time. Below are some example date ranges: >> >> >> December 31, 2006 January 13, 2007 # doesn't earn >> January 14, 2007 January 27, 2007 # does earn >> January 28, 2007 February 10, 2007 # doesn't >> February 11, 2007 February 24, 2007 # does >> What about (untested) : import datetime def itEarns(fromDate, toDate) : return (fromDate.year == toDate.year and fromDate.month == toDate.month) periods = [ (datetime.date(2006, 12, 31), datetime.date(2007, 1, 13)), (datetime.date(2007, 1, 14), datetime.date(2007, 1, 27)), (datetime.date(2007, 1, 28), datetime.date(2007, 2, 10)), (datetime.date(2007, 2, 11), datetime.date(2007, 2, 24)) ] candidatePeriods = [(frm, to) for frm, to in periods if itEarns(frm, to)] ?? >> >> So far, the best approach I've come up with is to create a list of >> tuples that contain the pay period date ranges for the year and >> iterate through the tuples looking for the first occurrence of the >> month names matching. Then I'd add that date range to a separate list >> and somehow ignore any other matches in that month. This seems like a >> hack. Does anyone have a better idea? > > > Well, I can come up with a solution which basically reflects the > way I'd do it in SQL (since this kind of thing is my bread-and-butter > there) but I'm not convinced it's really any better than your proposal. > However, for the purposes of illustration: > > > import calendar > import datetime > > YEAR = 2007 > > months = [ > (datetime.date (YEAR, n, 1), datetime.date (YEAR, n, calendar.monthrange (YEAR, n)[1])) > for n in range (1, 13) > ] > > periods = [ > (datetime.date(2006, 12, 31), datetime.date(2007, 1, 13)), > (datetime.date(2007, 1, 14), datetime.date(2007, 1, 27)), > (datetime.date(2007, 1, 28), datetime.date(2007, 2, 10)), > (datetime.date(2007, 2, 11), datetime.date(2007, 2, 24)) > ] > > for m in months: > candidate_periods = [p for p in periods if m[0] <= p[0] and p[1] <= m[1]] > if candidate_periods: > print m[0], "=>", min (candidate_periods) > else: > print m[0], "=>", "no period matches" > > > > TJG From babycode at gmail.com Thu Sep 20 10:29:00 2007 From: babycode at gmail.com (babycode at gmail.com) Date: Thu, 20 Sep 2007 07:29:00 -0700 Subject: unittest tutorial In-Reply-To: References: Message-ID: <1190298540.618701.221870@k79g2000hse.googlegroups.com> On Sep 20, 6:48 am, Gigs_ wrote: > does anyone know some good tutorial for unittest? (with examples how unit work)? > > thank you http://www.onlamp.com/pub/a/python/2005/02/03/tdd_pyunit2.html From byte8bits at gmail.com Tue Sep 25 13:41:56 2007 From: byte8bits at gmail.com (brad) Date: Tue, 25 Sep 2007 13:41:56 -0400 Subject: Script to extract text from PDF files Message-ID: I have a very crude Python script that extracts text from some (and I emphasize some) PDF documents. On many PDF docs, I cannot extract text, but this is because I'm doing something wrong. The PDF spec is large and complex and there are various ways in which to store and encode text. I wanted to post here and ask if anyone is interested in helping make the script better which means it should accurately extract text from most any pdf file... not just some. I know the topic of reading/extracting the text from a PDF document natively in Python comes up every now and then on comp.lang.python... I've posted about it in the past myself. After searching for other solutions, I've resorted to attempting this on my own in my spare time. Using apps external to Python (pdftotext, etc.) is not really an option for me. If someone knows of a free native Python app that does this now, let me know and I'll use that instead! So, if other more experienced programmer are interested in helping make the script better, please let me know. I can host a website and the latest revision and do all of the grunt work. Thanks, Brad From rave247 at seznam.cz Thu Sep 6 15:25:28 2007 From: rave247 at seznam.cz (=?us-ascii?Q?rave247=20rave247?=) Date: Thu, 06 Sep 2007 21:25:28 +0200 (CEST) Subject: =?us-ascii?Q?Re=3A=20Getting=20original=20working=20directory?= In-Reply-To: Message-ID: <1505.1821-20120-1168490301-1189106727@seznam.cz> Yes, I think you are right, without hacking into the parent process it will not work, and this is bad way. I hope I find the better way. Thanks for your comments > ------------ P?vodn? zpr?va ------------ > Od: Steve Holden > P?edm?t: Re: Getting original working directory > Datum: 06.9.2007 21:15:10 > ---------------------------------------- > rave247 rave247 wrote: > > If I could use os.getcwd() or save the value to some variable before calling > os.chdir() > > I would do it, believe me. However I can't because it is the part of > code where I > > can't do any changes. > > > > Also I do not agree that such thing is not possible because after python > script > > finishes its work, it naturally gets back into the original location > from where > > you started the script (in shell you are in the original location > after script > > finishes). So this information has to be stored somewhere (probably > in shell which > > runs the interpreter) and there *must* be a way how to get it. > Simply after > > calling os.chdir() the original value doen't disappear, I think it > just needs > > some nice hack if python doesn't provide a way how to get it. > > > Python runs as a sub-process. The parent process (the one that started > Python) contains the working directory that the Python interpreter > inherited from it. But you can't expect to just go poking around inside > the environment of your parent process, which will typically be waiting > for you to finish before it continues. Why *must* there be a way to get > at its current directory? Once it continues, of course, it does so in > the same directory. If you want to hack into your parent process to find > that information that's up to you, but Python certainly has no special > mechanism for doing it. > > If you treat the answers to all your questions with so little respect > it's a wonder you bother asking the questions in the first place. > > You didn't even explain what the relationship was between the "myscript" > that you want to run and the Python code that you want to switch back to > the original working directory. Sorry, we aren't mind readers (though > some of the guys on this list get close on occasion). > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- > > -- > http://mail.python.org/mailman/listinfo/python-list > > > From kw at codebykevin.com Thu Sep 27 10:23:17 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 27 Sep 2007 10:23:17 -0400 Subject: Tkinter / Tk 8.5 In-Reply-To: References: <13fm60kbhr28fa8@corp.supernews.com> Message-ID: <46FBBCD5.3070106@codebykevin.com> Eric Brunel wrote: > On Thu, 27 Sep 2007 04:41:48 +0200, Scott David Daniels > wrote: > >> Michal Bozon wrote: >>> Today has been released a first beta of Tk 8.5, including a Ttk >>> (tile) style engine, which makes possible the native look >>> of widgets on MS platform, without having to install any extension. >>> Is there a chance it will be included in 2.5.x, 2.6 or 3.0 ? >> >> This is just a guess, but: >> The beta: no way for anything. >> 2.5.x: also very unlikely >> 2.6: unlikely unless release is _soon_ (first alpha of 2.6 is out) > > It won't be: tcl/tk development is quite slow. There have been several > months between each 5 or 6 alpha release and between the last alpha and > the beta. So don't expect the official release to come soon... > >> 3.0: much more likely, 3.0 won't be out for some time. > > This would be my guess too... I'd say that Tk 8.5 will be out before Python 3.0: the beta phase should be fairly efficient on Tk. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From ricaraoz at gmail.com Wed Sep 26 16:43:42 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 26 Sep 2007 17:43:42 -0300 Subject: Delete values from a string using the index In-Reply-To: <1190838311.630506.64670@y42g2000hsy.googlegroups.com> References: <1190838311.630506.64670@y42g2000hsy.googlegroups.com> Message-ID: <46FAC47E.40606@bigfoot.com> koutoo at hotmail.com wrote: > How do I delete or remove values from a list or string using the > index. > > If a = [1,2,3,4,5,6,7,8] and I want to get rid of 1 -5, how would I do > that? > > Thanks. > del a[1] del a[-5] From cjt22 at bath.ac.uk Tue Sep 4 09:43:14 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Tue, 04 Sep 2007 06:43:14 -0700 Subject: Printing lists in columns (was: TypeError: 'module object is not callable') In-Reply-To: References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> Message-ID: <1188913394.763871.218660@d55g2000hsg.googlegroups.com> On Sep 4, 2:06 pm, Duncan Booth wrote: > cj... at bath.ac.uk wrote: > >> But watch out if the lists aren't all the same length: zip won't pad out > >> any sequences, so it maynotbe exactly what is wanted here: > > >> >>> x = ['1', '2', '3'] > >> >>> y = ['4', '5'] > >> >>> for row in zip(x,y): > > >> print ', '.join(row) > > >> 1, 4 > >> 2, 5 > > > Unfortunately the lists will be of different sizes > > In that case use: > > from itertools import repeat, chain, izip > def izip_longest(*args, **kwds): > fillvalue = kwds.get('fillvalue') > def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): > yield counter() # yields the fillvalue, or raises IndexError > fillers = repeat(fillvalue) > iters = [chain(it, sentinel(), fillers) for it in args] > try: > for tup in izip(*iters): > yield tup > except IndexError: > pass > > x = ['1', '2', '3'] > y = ['4', '5'] > for row in izip_longest(x,y, fillvalue='*'): > print ', '.join(row) > > which gives: > > 1, 4 > 2, 5 > 3, * > > (izip_longest is in a future version of itertools, but for > now you have to define it yourself). Thanks guys I have a list of lists such as a = ["1" , "2"] b = ["4", "5", "6"] c = ["7",8", "9"] Stored in another list: d = [a,b,c] I know this makes me sound very stupid but how would I specify in the parameter the inner lists without having to write them all out such as: for row in izip_longest(d[0], d[1], d[2], fillvalue='*'): print ', '.join(row) i.e. How could I do the following if I didn't know how many list of lists I had. Sorry this sounds stupid and easy. Thankyou very much in advance as well, you are all very helpful indeed. From chris.olekas at gmail.com Mon Sep 10 11:57:41 2007 From: chris.olekas at gmail.com (Chris) Date: Mon, 10 Sep 2007 08:57:41 -0700 Subject: Silent SaveAs when using the Excel win32com module Message-ID: <1189439861.200686.245420@k79g2000hse.googlegroups.com> I'm trying to create an excel file which will act as a log, however I want to overwrite the file if it exists. Looking at the SaveAs method I can't find anything that would allow it. I don't want the prompt to appear to ask whether to replace the file or not. I just want to replace it without thinking. Thanks in advance. From rrr at ronadam.com Fri Sep 21 10:41:30 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 21 Sep 2007 09:41:30 -0500 Subject: Python 3K or Python 2.9? In-Reply-To: <46f38907$0$27686$426a74cc@news.free.fr> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1190013827.107324.111820@w3g2000hsg.googlegroups.com> <1190053757.091035.221570@22g2000hsm.googlegroups.com> <46f38907$0$27686$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Ron Adam a ?crit : >> >> TheFlyingDutchman wrote: >> >>> I am not talking about the way it does it, but rather, the way it >>> could do it or... could have done it. That requires no knowledge of >>> how the interpreter currently does it unless I am proposing something >>> that no interpreter in the world could ever do. > (snip) >> So if you can find a way to do things like removing self in python in >> such a way that it doesn't require adding more to the Core interpreter, >> then it might be considered. > > By who ? As far as I'm concerned, I don't want 'self' to be removed, and > I'm probably not the only one here. The term "might be considered" in this case is a very very small possibility. It would need to be a very good solution which has some very nice benifits over the current way. As you say below, it's probably not possible. This was more of a challenge to get anyone who thinks it's worth doing to learn more about how python works rather than just propose arbitrary ideas. >> What I've found is as my skills improve, I take more advantage of being >> able to modify and/or introspect how things work. This allows more >> choices on how I might solve a particular problem. > > The changes required by removing self would make most of this either > painfull or near impossible AFAICT. Right, It would have a cascade effect in many places. >> I also think there a lots of improvements that could be made to other >> parts of python such as the libraries that would be of much more >> practical benefit. > > indeed. Cheers, Ron From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 17 05:07:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 17 Sep 2007 11:07:04 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <1190016312.637754.109770@n39g2000hsh.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> <46e97917$0$9014$426a74cc@news.free.fr> <1190013177.473529.167770@o80g2000hse.googlegroups.com> <46ee2d9d$0$26213$426a74cc@news.free.fr> <1190016312.637754.109770@n39g2000hsh.googlegroups.com> Message-ID: <46ee43b8$0$30545$426a74cc@news.free.fr> TheFlyingDutchman a ?crit : > > If you wanna know why the Renault Dauphine requires the driver to pull > down on the rearview mirror in order to shift into reverse you simply > need to open the hood and remove the engine and disassemble the > transmission and you will see that it has no way of distinguishing a > shift into third from a shift into reverse without a rearview mirror > pull. But these days most people just open the glove compartment when > shifting into reverse which works just as well! > Very interesting engineering problem. But a bit out of date and totally unrelated to Python. Anything else ? From george.sakkis at gmail.com Fri Sep 7 14:49:56 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 07 Sep 2007 18:49:56 -0000 Subject: Speed of Python In-Reply-To: References: Message-ID: <1189190996.887575.27240@57g2000hsv.googlegroups.com> On Sep 7, 12:42 pm, "wang frank" wrote: > Is my conclusion correct that Python is slower than matlab? Are there any > way to speed it up? Yes, use Numpy for any non trivial number-crunching task: http://numpy.scipy.org/. Even if you don't, you can speed up the original function by ~25% if you replace range() with xrange() and bind the log function to a local variable: def bench2(n): from math import log for i in xrange(n): for j in xrange(1000): m=j+1 z=log(m) z1=log(m+1) z2=log(m+2) z3=log(m+3) z4=log(m+4) z5=log(m+5) z6=log(m+6) z7=log(m+7) z8=log(m+8) z9=log(m+9) return z9 HTH, George From jd at nospam.com Fri Sep 21 13:28:22 2007 From: jd at nospam.com (Jd) Date: Fri, 21 Sep 2007 10:28:22 -0700 Subject: xml-rpc timeout Message-ID: <2_WdnTQ86eZNY27bnZ2dnUVZ_jCdnZ2d@comcast.com> Hi I have a multi-threaded application. For certain operations to the server, I would like to explicitly set timeout so that I get correct status from the call and not timed out exception. Does anyone know how to go about doing it ? /Jd From raychorn at hotmail.com Sat Sep 22 16:02:51 2007 From: raychorn at hotmail.com (Python Maniac) Date: Sat, 22 Sep 2007 13:02:51 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> Message-ID: <1190491371.189556.177790@d55g2000hsg.googlegroups.com> On Sep 21, 12:56 am, Duncan Booth wrote: > George Sakkis wrote: > > It has to do with the input string length; try multiplying it by 10 or > > 100. Below is a more complete benchmark; for largish strings, the imap > > version is the fastest among those using the original algorithm. Of > > course using a lookup table as Diez showed is even faster. FWIW, here > > are some timings (Python 2.5, WinXP): > > > scramble: 1.818 > > scramble_listcomp: 1.492 > > scramble_gencomp: 1.535 > > scramble_map: 1.377 > > scramble_imap: 1.332 > > scramble_dict: 0.817 > > scramble_dict_map: 0.419 > > scramble_dict_imap: 0.410 > > I added another one: > > import string > scramble_translation = string.maketrans(''.join(chr(i) for i in xrange > (256)), ''.join(chr(i|0x80) for i in xrange(256))) > def scramble_translate(line): > return string.translate(line, scramble_translation) > > ... > funcs = [scramble, scramble_listcomp, scramble_gencomp, > scramble_map, scramble_imap, > scramble_dict, scramble_dict_map, scramble_dict_imap, > scramble_translate > ] > > and I think I win: > > scramble: 1.949 > scramble_listcomp: 1.439 > scramble_gencomp: 1.455 > scramble_map: 1.470 > scramble_imap: 1.546 > scramble_dict: 0.914 > scramble_dict_map: 0.415 > scramble_dict_imap: 0.416 > scramble_translate: 0.007 Some benchmarks showing the effectiveness of using Psyco: scramble: 4.210 scramble_listcomp: 2.343 scramble_gencomp: 2.599 scramble_map: 1.960 scramble_imap: 2.231 scramble_dict: 2.387 scramble_dict_map: 0.535 scramble_dict_imap: 0.726 scramble_translate: 0.010 Now with Psyco... psyco.bind(scramble)... scramble: 0.121 4.088 34.670x faster scramble_listcomp: 0.215 2.128 10.919x faster scramble_gencomp: 2.563 0.036 1.014x faster scramble_map: 2.002 -0.043 0.979x slower scramble_imap: 2.175 0.056 1.026x faster scramble_dict: 0.199 2.188 11.983x faster scramble_dict_map: 0.505 0.029 1.058x faster scramble_dict_imap: 0.728 -0.001 0.998x slower scramble_translate: 0.009 0.001 1.111x faster Overall, Psyco helped my little process of converting 20 MB worth of ASCII into what may not look like the original at 6x faster than without Psyco. From steve at REMOVE-THIS-cybersource.com.au Sun Sep 16 18:48:19 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 22:48:19 -0000 Subject: Needless copying in iterations? References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> <13epv3fnb6bak15@corp.supernews.com> Message-ID: <13ercljcg60mq99@corp.supernews.com> On Sun, 16 Sep 2007 11:49:15 -0400, Steve Holden wrote: >> It seems to me that the "consenting adults" philosophy of Python >> doesn't extend to the compiler, and perhaps it should. Maybe Python >> could optimize common cases, and if developers wanted to do wacky >> things, let them turn optimization off on a module-by-module basis. >> >> Or even function-by-function. Wouldn't it be nice to have decorators >> that could optimize the functions they decorated? >> > No, it would be disastrous, Disastrous, as in thousands dead, panic in the street, martial law declared? I'm sure your program in important, but is it really *that* important? :-) > unless you could manage to implement a > mechanism that *told* you when the optimizations were playing havoc with > your program's execution. How about "the test suite passes when I turn optimization off, but fails when I turn optimization on"? How is that any different from "the test suite passes when I use StringIO, but not if I use cStringIO"? > The problem is that debugging only works if you can assume a > deterministic environment. If you are going to put funky optimizations > in that break determinism in "little-used" corner cases, then debugging > the situations when the optimizations *do* affect program execution will > be a complete pain. Right, so we're back to the "any pixel is as likely as any other pixel" example from Joel On Software I mentioned earlier. To prevent some hypothetical developer doing some wacky thing from having to work harder to debug some weird corner case, *everybody else* has to miss out on optimizations that could lead to significantly better performance. You might think that's a good trade-off. I don't. >>>> for item in alist[1:5]: >>>> alist.append(item) # side-effects DON'T matter >>> The compiler doesn't know that, at the time of invocation, >>> 'alist.append' doesn't have side effects that matter. >> >> It might if it knows what type alist is, and how long it is (as Marc >> Rintsch points out). That's why I used "alist" in my example rather >> than "an_arbitrary_sequence". >> > But alist doesn't *have* a type, and static program analysis would have > to be extensive to determine that it could only ever be of a specific > type. Of course alist has a type. Python is a strongly-typed language, not untyped. And I don't believe I specifically mentioned that static program analysis was the only optimization possible. But even if it was... I can *hand optimize* a function that I write, yes? I might *choose* to say to myself, "Screw duck typing, in *my* program function foo will only ever be called with an honest-to-god built-in list argument, I'm going to optimize it for that case". We're all consenting adults here, right? Well, what's the difference between me hand optimizing the function, and calling a built-in decorator that does it for me? Why is it okay for me to shoot myself in the foot, but not for me to tell the compiler to shoot me in the foot? >> Because of its very nature, optimizing Python is hard. Even something >> as simple as tail-call recursion optimization is verboten, because >> Guido considers good stack traces more important than preventing stack >> overflows in the first place: >> >> http://www.tratt.net/laurie/tech_articles/articles/ tail_call_optimization >> > And who's to say he's wrong, especially since Python is intended to be > an environment that's friendly to beginners. I'm not saying he's *wrong*, I'm saying he's making trade-offs I would like to see relaxed. But in the specific case of recursion... have you seen the exception you get when the recursion limit is hit? By default, you get 1000 lines of ' File "foo", line 2, in function_name' followed by "RuntimeError: maximum recursion depth exceeded". Maybe I'm missing something there, but I don't see how that's much of a help in debugging. >> Anyway, I'm not really complaining. I like Python, I'm grateful for the >> work the Python-dev people have already done, and I'm in no position to >> volunteer to write an optimizing compiler. And it may be that, >> regardless of how smart you make the compiler, Python simply can't be >> optimized because of design decisions made back in 1990-whatever when >> Guido first started his grand plan. >> > There is some of that. The environment is so dynamic that even something > as innocuous as attribute lookup can actually involve properties (for > example) reading a relational database! I'm not saying that optimization > under these circumstances is possible, but that it's much more difficult > than is easily anticipated, and that the benefits to be gained might be > less than you would think. I'm mostly objecting to people who say that Python's compiler "can't" be optimized, which is not true. As I mentioned, there's already a peephole optimizer. There are runtime optimizations possible. Psycho could become a built-in, if the right people wanted it to become a built-in. Etc. With a few million in funding, Python could become as heavily optimized as Common Lisp. Of course, whether that would still be the Python we know *now* is another question. But then, with decorators and generator expressions and iterators, Python 2.6 is not precisely the same as the Python we knew back in 1997, is it? -- Steven. From antroy at gmail.com Sat Sep 29 06:46:18 2007 From: antroy at gmail.com (Ant) Date: Sat, 29 Sep 2007 03:46:18 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: Message-ID: <1191062778.951573.166480@d55g2000hsg.googlegroups.com> I've posted my vote. However, I guess it won't be that simple in practice. I suspect that the following is more likely: 1) Migrate to 3000 fairly soon after release for scripts and new projects for which required third party modules are available for 3k 2) Migrate existing projects to 3k a) when frameworks/modules that they use are available and b) if and when doing so would be advantageous. I suspect that many of the projects I have that are solid and are in no imminent need of development will remain <3k for several years. Cheers, -- Ant From jonas.maurus at gmail.com Wed Sep 19 16:48:33 2007 From: jonas.maurus at gmail.com (Jonas Maurus) Date: Wed, 19 Sep 2007 20:48:33 -0000 Subject: limiting memory consumption of Python itself or a dict in a Python program Message-ID: <1190234913.608070.5410@19g2000hsx.googlegroups.com> Hello everybody, I'm pondering the following problem: I want to write a Python program that receives messages via SMTP and stores them in a dict or an array. For my purposes it would be important that all received mail would be kept in RAM and not cached out to disk. If a new message comes in that can't fit in the allocated memory, a number of old messages would be discarded. As the server needs to have room for other tasks, I'd like to limit the overall memory consumption to a certain amount. Is this possible? How would I go about implementing it? By imposing "ulimit"s and catching MemoryError? Thanks for your help, Jonas From jstroud at mbi.ucla.edu Thu Sep 20 20:38:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 20 Sep 2007 17:38:00 -0700 Subject: executing list of methods (and collecting results) In-Reply-To: References: Message-ID: Gerardo Herzig wrote: > Hi all. Im in this situation: I want to perform several kind of > (validating) methods to a given value. > Lets say i have a class named Number, and the following methods: > is_really_a_number(), > is_even(), > is_greater_than_zero(), > and so on. All of them returning booleans. > > I want the collect_validators() method is to execute any of the above > methods, and collect their names as items of a list (wich will be the > collect_validators() return value). > > My first approach is: > > [code] > def collect_validators(self): > v_dict = { 'is_really_a_number': is_really_a_number, > 'is_even': is_even, > 'is_greater_than_zero', is_greater_than_zero > } > > for name, meth in v_dict.items(): > result = meth() > if result: yield name > [/code] > > I wondering if is this a good pattern to apply, i like the way it looks > like, at least to me it looks `natural', but...im calling every method > twice here? One in v_dict and again on the dict iteration? > > Any suggestion will be great! > > Thanks! > Gerardo You are not calling every method twice. You are painstakingly typing out their names twice. But fortunately, functions and methods have a __name__ attribute which makes a this typing redundant. I would give your class instances a _validators attribute which is a list of validating methods, then make the generator like this: def collect_validators(self): for v in self._validators: if v(): yield v.__name__ James From jura.grozni at gmail.com Sat Sep 22 13:24:29 2007 From: jura.grozni at gmail.com (azrael) Date: Sat, 22 Sep 2007 10:24:29 -0700 Subject: Help for Otsu implementation from C In-Reply-To: <1190230388.764546.114690@57g2000hsv.googlegroups.com> References: <1190201086.468348.274850@g4g2000hsf.googlegroups.com> <1190230388.764546.114690@57g2000hsv.googlegroups.com> Message-ID: <1190481869.029440.240720@22g2000hsm.googlegroups.com> Thanks Man, I did it. It works fantastic. On Sep 19, 9:33 pm, azrael wrote: > I know. The translation is not so important to me, because this is > going to just a little function that is working in the last step of > the whole proces. The whole implementation wont be published and has > just the meaning to implement a first alpha version of a face > recognition system. It is nearly finished, and this is the only > function I am missing. For this purpose I need it to work "EXACTLY". > > I know that it doesnt look pythonic. After I know that it works > correctly, I am going to write a total Rewrite for the Beta Version. > > On Sep 19, 1:55 pm, Peter Otten <__pete... at web.de> wrote: > > > azrael wrote: > > > Can somone look at this > > > def otsu(hi): > > > fmax=-1.0 > > > border=len(hi) > > > for i in range(border): > > > if hi[i]!=0:break > > > for j in range(border-1,0-1,-1): > > > if hi[j] != 0:break > > > s = sum([k*hi[k] for k in range(border)]) n = sum(hi) # > > > product(im.size) > > > n1=n2=csum=0.0 > > > for k in range(i,j): > > > n1 += hi[k] > > > n2 = n - n1 > > > csum+= k * hi[k] > > > m1 = csum/ n1 > > > m2 = (s - csum)/n2 > > > As I said in my previous post, try replacing this line > > > > sb = n1 * n2 * (m2 - m1) > > > with the original > > > sb = n1 * n2 * (m1 - m2) * (m1 - m2) > > > that has been commented out. > > > > if sb > fmax: > > > fmax = sb > > > V=k+1 > > > print V > > > I try to implement it from C from this location. > > > Personally, I would start with a literal translation and not try to > > improve it until it works. > > > Peter From steve at REMOVE-THIS-cybersource.com.au Wed Sep 12 08:38:13 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 12 Sep 2007 12:38:13 -0000 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> Message-ID: <13efndlln9n9659@corp.supernews.com> On Wed, 12 Sep 2007 03:21:58 -0700, Charles Fox wrote: > I've just started playing around with Python, as a possible replacement > for a mix of C++, Matlab and Lisp. The language looks lovely and clean > with one huge exception: I do a lot of numerical modeling, so I deal > with objects (like neurons) described mathematically in papers, by > equations like > a_dot = -k(a-u) > In other languages, this translates nicely into code, but as far as I > can tell, Python needs the ugly: > self.a_dot = -self.k(self.a-self.u) I think you've been seriously mislead. You don't NEED self. That's only for writing classes. Although Python is completely object oriented, and everything is an object, you don't have to put your code in classes. Instead of doing something like this: class Adder(object): """Pointless class to add things.""" def __init__(self, value): self.value = other def add(self, other): x = self.value + other return float(x) you don't need a class. Just write a function: def add(x, other): """Function that adds other to x.""" return float(x + other) Here's how I would write your function above: def function(a, u, k): """Calculate a_dot from a, u and k.""" return -k(a-u) And here is how I would use it: a = 57 # or whatever... u = 54 k = 3 a_dot = function(a, u, k) See? Not a single "self" in sight. You might also like to read about a strange, bizarre programming that forces you to put everything inside classes: http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html -- Steven. From steven.bethard at gmail.com Fri Sep 28 13:44:07 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Sep 2007 11:44:07 -0600 Subject: getopt with negative numbers? In-Reply-To: <1190999036.588941.165610@g4g2000hsf.googlegroups.com> References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <1190915197.390247.313590@57g2000hsv.googlegroups.com> <1190930134.780005.68510@22g2000hsm.googlegroups.com> <1190944143.521085.66910@g4g2000hsf.googlegroups.com> <871wcj4ib9.fsf@benfinney.id.au> <1190999036.588941.165610@g4g2000hsf.googlegroups.com> Message-ID: Casey wrote: > Ben Finney wrote: >> I believe they shouldn't because the established interface is that a >> hyphen always introduced an option unless (for those programs that >> support it) a '--' option is used, as discussed. > > Not "THE" established interface; "AN" established interface. There > are other established interfaces that have different behaviors. I'm a > pragmatist; I write software for users, not techies. I suspect most > users would expect a command like "abc -a -921 351 175" to treat the > "-921" as a negative integer and not abort the program with some > obscure error about option 921 not being known. Glad I'm not alone in this. ;-) A user shouldn't have to go out of their way to specify regular numbers on the command line, regardless of whether they're positive or negative. STeVe From gagsl-py2 at yahoo.com.ar Sat Sep 22 01:31:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 22 Sep 2007 02:31:01 -0300 Subject: threading.local _threading_local problems References: Message-ID: En Fri, 21 Sep 2007 14:36:34 -0300, Jd escribi?: > Hi > I have the following situation.. Have a worker thread, that does the > "work" given to it. While doing work, some of the objects use thread > local storage for storing that requires explicit close. e.g. connection > handles. These objects are long living. The worker, does not have any > direct access to the objects. > > I would like to clean up thread local area explicitly so that I do not > run out of connection handles. Any ideas on how to access local storage > from the thread ? (threading.local() gives new object everytime.. I am > looking for something like singleton / global access from within the > thread) Create a local() object *once*; it may be a global variable. Then assign to its attributes from any thread. Each thread will see a different set of attributes. > Or is there anyway to notify the object when the thread for which it > set the local storage is going away ? Do that at the end of the thread's run method. -- Gabriel Genellina From heikki at osafoundation.org Fri Sep 21 04:07:44 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 21 Sep 2007 01:07:44 -0700 Subject: M2Crypto 0.18 - new version, same old build bugs. In-Reply-To: References: Message-ID: John Nagle wrote: > Back in March, I posted this: > >> Hit that with OpenSSL. Red Hat took elliptical curve cryptography >> out of Fedora 6 for patent reasons. With that missing, M2Crypto won't >> build. It ought to; the implementor of M2Crypto thought of that, because >> it's an optional feature. But M2Crypto uses SWIG. SWIG doesn't normally >> process nested include files. OpenSSL had changed their configuration >> approach to use nested include files. So SWIG didn't see the #define >> that >> said to turn off elliptical curve crypto support. This resulted in >> compile errors in the 24,000 lines of code that come out of SWIG. > > That was for M2Crypto 0.17. > > It's still broken in M2Crypto 0.18. This was reported as https://bugzilla.osafoundation.org/show_bug.cgi?id=9404 and fixed, at least according to the person who reported the bug. I'd be curious to know why the fix does not work for you... As an alternative, does it work if you add line 130 to setup.py: '-DOPENSSL_NO_EC', # Uncomment if you have trouble compiling without EC support -- Heikki Toivonen From ptmcg at austin.rr.com Thu Sep 13 14:22:31 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 13 Sep 2007 11:22:31 -0700 Subject: plotting pixels in python In-Reply-To: <1189706620.564963.29690@d55g2000hsg.googlegroups.com> References: <1189706620.564963.29690@d55g2000hsg.googlegroups.com> Message-ID: <1189707751.846412.51420@r29g2000hsg.googlegroups.com> On Sep 13, 1:03 pm, jo5867... at gmail.com wrote: > hi to all > I am just a beginner of python. I want to know how pixels are plotted > in python. I am not intending to use PIL because I don't need to > manipulate images. So is there a simple module for 2D graphics and > plot pixels Here is a *very* simple-minded module for creating BMP files, that supports drawing points, lines, and simple shapes. http://www.geocities.com/ptmcg/python/index.html#bmp -- Paul From grante at visi.com Sat Sep 29 11:35:36 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 29 Sep 2007 15:35:36 -0000 Subject: Program inefficiency? References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> Message-ID: <13fss68juscn33@corp.supernews.com> > [...] > the program works great except for one thing. It's significantly > slower through the later files in the search then through the early > ones... Before anyone criticizes, I recognize that that middle section > could be simplified with a for loop... I just haven't cleaned it > up... > > The problem is that the first 300 files take about 10-15 seconds and > the last 300 take about 2 minutes... If we do more than about 1500 > files in one run, it just hangs up and never finishes... > > Is there a solution here that I'm missing? What am I doing that is so > inefficient? The only thing I see is that you compile all of the RE's every time you call replacecycle(). They really only need to be compiled once, but I don't know why that would cause the progressive slowing. FWIW, it seems to me like a shell+sed script would be the obvious solution to the problem. > # File: masseditor.py > > import re > import os > import time > > def massreplace(): > editfile = open("pathname\editfile.txt") > filestring = editfile.read() > filelist = filestring.splitlines() > ## errorcheck = re.compile('(a name=)+(.*)(-)+(.*)(>)+') > for i in range(len(filelist)): > source = open(filelist[i]) > starttext = source.read() > interimtext = replacecycle(starttext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > interimtext = replacecycle(interimtext) > finaltext = replacecycle(interimtext) > source.close() > source = open(filelist[i],"w") > source.write(finaltext) > source.close() > ## if errorcheck.findall(finaltext)!=[]: > ## print errorcheck.findall(finaltext) > ## print filelist[i] > if i == 100: > print "done 100" > print time.clock() > elif i == 300: > print "done 300" > print time.clock() > elif i == 600: > print "done 600" > print time.clock() > elif i == 1000: > print "done 1000" > print time.clock() > print "done" > print i > print time.clock() > > def replacecycle(starttext): > p1= re.compile('(href=|HREF=)+(.*)(#)+(.*)( )+(.*)(">)+') > p2= re.compile('(name=")+(.*)( )+(.*)(">)+') > p3= re.compile('(href=|HREF=)+(.*)(#)+(.*)(\')+(.*)(">)+') > p4= re.compile('(name=")+(.*)(\')+(.*)(">)+') > p5= re.compile('(href=|HREF=)+(.*)(#)+(.*)(-)+(.*)(">)+') > p6= re.compile('(name=")+(.*)(-)+(.*)(">)+') > p7= re.compile('(href=|HREF=)+(.*)(#)+(.*)(<)+(.*)(">)+') > p8= re.compile('(name=")+(.*)(<)+(.*)(">)+') > p7= re.compile('(href=|HREF=")+(.*)(#)+(.*)(:)+(.*)(">)+') > p8= re.compile('(name=")+(.*)(:)+(.*)(">)+') > p9= re.compile('(href=|HREF=")+(.*)(#)+(.*)(\?)+(.*)(">)+') > p10= re.compile('(name=")+(.*)(\?)+(.*)(">)+') > p100= re.compile('(a name=)+(.*)(-)+(.*)(>)+') > q1= r"\1\2\3\4_\6\7" > q2= r"\1\2_\4\5" > interimtext = p1.sub(q1, starttext) > interimtext = p2.sub(q2, interimtext) > interimtext = p3.sub(q1, interimtext) > interimtext = p4.sub(q2, interimtext) > interimtext = p5.sub(q1, interimtext) > interimtext = p6.sub(q2, interimtext) > interimtext = p7.sub(q1, interimtext) > interimtext = p8.sub(q2, interimtext) > interimtext = p9.sub(q1, interimtext) > interimtext = p10.sub(q2, interimtext) > interimtext = p100.sub(q2, interimtext) > > return interimtext > > massreplace() > -- Grant Edwards grante Yow! Are you still at SEXUALLY ACTIVE? Did you visi.com BRING th' REINFORCEMENTS? From newsuser at stacom-software.de Fri Sep 7 04:35:27 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Fri, 07 Sep 2007 10:35:27 +0200 Subject: Class design (information hiding) Message-ID: Hi all, I'm wodering how the information hiding in python is ment. As I understand there doesn't exist public / protected / private mechanism, but a '_' and '__' naming convention. As I figured out there is only public and private possible as speakin in "C++ manner". Are you all happy with it. What does "the zen of python" say to that design? (protected is useless?) class A: def __init__(self): self.__z = 1 self._z = 2 self.z = 3 def _getX(self): return "X" def __getY(self): return "Y" def doAnything(self): print self.__getY() class B(A): def __init__(self): A.__init__(self) print dir (self) >>> b = B() ['_A__getY', '_A__z', '__doc__', '__init__', '__module__', '_getX', '_z', 'doAnything', 'z'] I was a bit surprised about '_A__getY' and '_A__z'. What would you say to a C++ Programmer about class interfaces in big Python systems? What is the idea behind the _ and __ naming. Use or don't use '_' methods ? (As Designer of the software, as Programmer of the software) Regards Alexander From m.n.summerfield at googlemail.com Tue Sep 25 16:55:22 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Tue, 25 Sep 2007 13:55:22 -0700 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190748509.786571.124150@n39g2000hsh.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> Message-ID: <1190753722.026806.254530@d55g2000hsg.googlegroups.com> On 25 Sep, 20:28, Paul Hankin wrote: > On Sep 25, 7:58 pm, Steven Bethard wrote: > > > > > > Paul Hankin wrote: > > > ... > > > class sorteddict(dict): > > > "A sorted dictionary" > > > def __init__(self, arg=None, cmp=None, key=None, reverse=False): > > > if arg: > > > ... > > > With this is the implementation, I'm definitely -1. Not because it's a > > bad implementation, but because if the iteration is always doing a sort, > > then there's no reason for a separate data structure. Just use sorted() > > directly on a regular dict. That has the advantage of being much more > > obvious about where the expensive operations are:: > > > for key in sorted(d, ...): > > ... whatever you want to do ... > > > IMHO, the only reason to introduce a sorteddict() is if it minimizes the > > cost of sorting the keys. > > I disagree with your reason for introducing a sorteddict - the main > reason should be if it makes code that uses it simpler and more > readable, with efficiency (within reasonable limits) being of > secondary importance. Unfortunately for sorteddict, your code is > simpler and more explicit for most obvious use cases. > > But, with Bill's cached sorted key list it'll be reasonably efficient, > and it's likely possible to update the sorted cache more efficiently > than resorting if there's only been a small number of insertions since > the last sort, but I haven't the time to do a thorough job. > > -- > Paul Hankin I think that keeping a sorted list of keys is worthwhile, but because the key or cmp functions could access keys or values or both you have to invalidate whenever a key or value is added or changed. Here's my version (v. similar to yours of course, but sorting when necessary): class sorteddict(dict): def __init__(self, iterable=None, cmp=None, key=None, reverse=False): if iterable is None: iterable = [] dict.__init__(self, iterable) self.__cmp = cmp self.__key = key self.__reverse = reverse self.__keys = None def update(self, *args, **kwargs): dict.update(self, *args, **kwargs) self.__keys = None @classmethod def fromkeys(cls, iterable, value=None): dictionary = cls() for key in iterable: dictionary[key] = value return dictionary def copy(self): dictionary = sorteddict(dict.copy(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) dictionary.__keys = None if self.__keys is None else self.__keys[:] return dictionary def clear(self): self.__keys = None dict.clear(self) def setdefault(self, key, value): self.__keys = None return dict.setdefault(self, key, value) def pop(self, key, value=None): if key not in self: return value self.__keys = None return dict.pop(self, key, value) def popitem(self): self.__keys = None return dict.popitem(self) def keys(self): if self.__keys is None: self.__keys = sorted(dict.keys(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) return self.__keys[:] def values(self): if self.__keys is None: self.__keys = sorted(dict.keys(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) return [self[key] for key in self.__keys] def items(self): if self.__keys is None: self.__keys = sorted(dict.keys(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) return [(key, self[key]) for key in self.__keys] def __iter__(self): if self.__keys is None: self.__keys = sorted(dict.keys(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) return iter(self.__keys) def iterkeys(self): if self.__keys is None: self.__keys = sorted(dict.keys(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) return iter(self.__keys) def itervalues(self): if self.__keys is None: self.__keys = sorted(dict.keys(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) for key in self.__keys: yield self[key] def iteritems(self): if self.__keys is None: self.__keys = sorted(dict.keys(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) for key in self.__keys: yield key, self[key] def __delitem__(self, key): self.__keys = None dict.__delitem__(self, key) def __setitem__(self, key, value): self.__keys = None dict.__setitem__(self, key, value) def __repr__(self): return str(self) def __str__(self): if self.__keys is None: self.__keys = sorted(dict.keys(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) return "{%s}" % ", ".join( ["%r: %r" % (key, self[key]) for key in self.__keys]) From tec at knology.net Mon Sep 10 10:57:45 2007 From: tec at knology.net (Tim) Date: Mon, 10 Sep 2007 07:57:45 -0700 Subject: shared memory pointer Message-ID: <1189436265.841415.234050@w3g2000hsg.googlegroups.com> Hello Everyone, I am getting shared memory in python using the following. szName = c_char_p(name) hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE, None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName) if (hMapObject == 0): print "OpenKey: Could not open name file mapping object" raise WinError() self.pData = windll.kernel32.MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE) This seems to work OK. How do I get to the data in self.pData? It is suppose to be an array of floats. I think MapViewOfFile returns a point to the data. Here is what I tried. current_time = 45.55 memcpy( current_time, self.pData, 4 ) but I get an error: ArgumentError: argument 1: : Don't know how to convert parameter 1 I need to get my floating point array casted from the self.pData. Any help would be appreciated! Thanks Tim From steve at REMOVE-THIS-cybersource.com.au Sat Sep 22 20:02:52 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 23 Sep 2007 00:02:52 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <7xy7eysfc0.fsf@ruckus.brouhaha.com> <7xbqbu1k7a.fsf@ruckus.brouhaha.com> Message-ID: <13fbb9c51ksaj19@corp.supernews.com> On Sat, 22 Sep 2007 14:09:13 -0700, Paul Rubin wrote: >> Nevertheless, def is never a real anonymous function constructor. > > Well, def constructs a function with a name, but the function can stay > around after the name goes away, after which I'd say the function is > nameless. One could otherwise say that (lambda x: x+x) is not anonymous > either, since id(lambda ...) is a unique label stuck to it like a > __name__. If you want to be tediously pedantic, lambda doesn't construct anonymous functions either: you can bind them to a name, and whether you do or not, they have a name. >>> f = lambda: 3 >>> f.__name__ '' It's just that all functions created by lambda share the same name. If you really want an anonymous function... >>> def foo(): ... return 3 ... >>> foo.__name__ = '' >>> foo I know, I know, I'm being tediously pedantic... and that's not what the anonymity of lambda refers to. What it actually means is that the lambda doesn't create a name in a namespace. In that regard, calling a factory function is also anonymous, because the function isn't added to the calling code's namespace. Or, to put it another way... def factory(): def foo(): return 3 return foo Within factory(), foo() is not an anonymous function, because 'foo' is in the local namespace. But the result of factory() is anonymous in the same sense that lambda is: although the function object has a attribute __name__ set to 'foo', calling factory() doesn't modify the caller's namespace (unless you assign the result to a name). -- Steven. From gslindstrom at gmail.com Fri Sep 7 15:09:06 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Fri, 7 Sep 2007 14:09:06 -0500 Subject: Python and Cron In-Reply-To: <46E19CAE.10205@ulmcnett.com> References: <46E19CAE.10205@ulmcnett.com> Message-ID: > Can you post the Python script? Not the whole thing; it's quite long. But here's the relevant parts. We're using the ado database interface into postgres (that's what the results.EOFis all about) output_file = file(output_path, 'w') # output_path = /my_path/data/work/my_file.txt while not results.EOF: row = results.GetRowAssoc(upper=0) output_file.write(row['data']) results.MoveNext() output_file.close() debug('Total Bytes Written: %d' % total_bytes) new_path = None if total_bytes > 0: new_path = output_path.replace('/work/', '/') else: new_path = output_path.replace('/work/', '/empty/') debug('Original Path [%s]'%output_path) # new_path = /my_path/data/my_file.txt debug(' New Path [%s]'%new_path) # new_path = /my_path/data/empty/my_file.txt The original code looked like this (worked from command line, failed with cron) os.rename(output_path, new_path) But since that didn't work and I could create a new file, I tried this as a work around output_file = file(new_path, 'w') for line in file(output_path): output_file.write(line) output_file.close() The interesting/infuriating thing is that the second method also fails; that is, the file is not moved to the data directory or the "empty" directory...it remains in the "work" directory after the cron job completes. If I run the same routine from the command like (after su'ing to the edith user) it runs and moves the file to the appropriate directory. I am going to see if we can get the email routing set up (we run over 100 cron jobs daily so I'm not sure I want it on too long) to see if it will tell me anything. Thanks for your time and effort --greg What's the name of the original file, and what are you trying to rename > it to? I'm wondering if you are deriving the new name from something, > and that thing is failing from within the cronjob for some reason. > Perhaps the new name contains a complete path in one of the cases but > not in the other... > > Edith should be getting email (if email routing is set up correctly) if > the job is failing or producing output. Specifically, perhaps she's > getting Python tracebacks and not telling you... :) > > > > -- > pkm ~ http://paulmcnett.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Sep 10 22:12:05 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 11 Sep 2007 12:12:05 +1000 Subject: Enum class with ToString functionality References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <87bqca9hrw.fsf@benfinney.id.au> <1189472591.797327.189180@w3g2000hsg.googlegroups.com> Message-ID: <87sl5m7xxm.fsf@benfinney.id.au> TheFlyingDutchman writes: > > (Please preserve attribution lines so it's clear who wrote what.) > Looking at the documentation it looks excellent. But I don't > understand the 0.4.2 version number, Note the tag that says the "Development Status" is "Beta". > particularly when you refer to it as robust. I assume you're referring to the short description, "Robust enumerated type support in Python". That refers to the implemented type as robust, not the state of the code. That is, the short description should be read as "Support, in Python, for robust enumerated types". It's a description of the package functionality. If, of course, the state of the code is not robust, that's a bug that needs to be fixed; but that's true for any package. -- \ "Try to become not a man of success, but try rather to become a | `\ man of value." ?Albert Einstein | _o__) | Ben Finney From mail at microcorp.co.za Thu Sep 20 02:51:38 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 20 Sep 2007 08:51:38 +0200 Subject: Tutorial or Example (or Tutorial) of Using Canvas to Producea Plot References: <13evohih7rkd030@corp.supernews.com><13f0b2qlvj5ige6@corp.supernews.com><9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com><1190185249.235840.263260@50g2000hsm.googlegroups.com> Message-ID: <00f601c7fb59$31ba42e0$03000080@hendrik> "W. Watson" wrote: > I'm just trying to get some feel for how canvas works. I'm about to modify a > program I use for meteor work. It uses canvas to display images, and I plan > to draw on the image. For example, I plan to draw compass headings on a > circle every 30 degrees. Just warming up to the task. Don't be surprised if you can't draw a full circle - I have never managed it, but 359.99 degrees works fine - Hendrik From paul.nospam at rudin.co.uk Fri Sep 21 11:03:45 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 21 Sep 2007 16:03:45 +0100 Subject: acronym program References: Message-ID: <87lkb0hxgu.fsf@rudin.co.uk> Shawn Minisall writes: > I'm trying to write a program that gets the first letter of every word > of a phrase and prints it on screen. I'm having problems with it. > I'm thinking a for loop would be good since I don't know the exact > number of words the user is going to enter, but after that I get > confused. How do I tell python to just goto the beg of each word in > the phrase and include it in the acronym? Am I on the right track? > > for a in string.split(phrase) > acronym = phrase [0] > acronym = acronym + 1 How about: for a in phrase.split(): print a[0] From bbxx789_05ss at yahoo.com Thu Sep 20 15:17:00 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 20 Sep 2007 12:17:00 -0700 Subject: subprocess: returncode v. poll() Message-ID: <1190315820.532320.26570@22g2000hsm.googlegroups.com> Hi, What is the difference between: 1) getting the returncode directly from the subprocess object 2) calling poll() on the subprocess object? Here is an example: import subprocess p = subprocess.Popen("ls", stdout=subprocess.PIPE) print p.returncode print p.poll() print print p.stdout.read()[:5] print print p.returncode print p.poll() print p.returncode --output:-- None None 10tes None 0 0 From ricaraoz at gmail.com Sat Sep 8 17:32:45 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 08 Sep 2007 18:32:45 -0300 Subject: Spell-checking Python source code In-Reply-To: <1189285495.185657.88010@o80g2000hse.googlegroups.com> References: <1189285495.185657.88010@o80g2000hse.googlegroups.com> Message-ID: <46E314FD.7030200@bigfoot.com> John Zenger wrote: > To my horror, someone pointed out to me yesterday that a web app I > wrote has been prominently displaying a misspelled word. The word was > buried in my code. > > Is there a utility out there that will help spell-check literal > strings entered into Python source code? I don't mean spell-check > strings entered by the user; I mean, go through the .py file, isolate > strings, and tell me when the strings contain misspelled words. In an > ideal world, my IDE would do this with a red wavy line. > > I guess a second-best thing would be an easy technique to open a .py > file and isolate all strings in it. > > (I know that the better practice is to isolate user-displayed strings > from the code, but in this case that just didn't happen.) > Use the re module, identify the strings and write them to another file, then open the file with your spell checker. Program shouldn't be more than 10 lines. From robin at alldunn.com Fri Sep 28 01:08:27 2007 From: robin at alldunn.com (Robin Dunn) Date: Thu, 27 Sep 2007 22:08:27 -0700 Subject: ANNOUNCE: wxPython 2.8.6.0 Message-ID: <46FC8C4B.8000808@alldunn.com> Announcing ---------- The 2.8.6.0 release of wxPython is now available for download at http://wxpython.org/download.php. This release is mostly about fixing a number of bugs and inconsistencies in wxWidgets and wxPython. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some pacakges for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.3+, in most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.6.0 ------------------ This release is mostly about fixing a number of bugs and inconsistencies in wxWidgets and wxPython. In other words, there have been a whole lot more changes than what is listed here, but they are not new features or API visible changes, which is what are usually listed in this file. Some Menu APIs added to make things more consistent. Added wx.MenuBar.SetMenuLabel, wx.MenuBar.GetMenuLabel, wx.MenuBar.GetMenuLabelText, wx.Menu.GetLabelText, wx.MenuItem.SetItemLabel, wx.MenuItem.GetItemLabel, wx.MenuItem.GetItemLabelText, wx.MenuItem.GetLabelText. The Get...Label functions get the raw label with mnemonics and accelerators, and the Get...LabelText functions get the text only, without mnemonics/accelerators. Added wx.BORDER_THEME style. This style will attempt to use a theme specific style, if the current platform and environment is themeable and has a specific theme style. For example, you could use this on Windows XP on a custom control to give it a themed border style that looks like what is used by default on the native wx.TextCtrl or wx.ListBox. Since there were not any more available bits for border styles, this style replaces wx.BORDER_DOUBLE. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From arkanes at gmail.com Fri Sep 7 10:55:28 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 7 Sep 2007 09:55:28 -0500 Subject: Best practice prompting for password In-Reply-To: <46E14CF1.8090706@gentlemail.com> References: <46E14CF1.8090706@gentlemail.com> Message-ID: <4866bea60709070755i3602eac4se2a47d9211526b6a@mail.gmail.com> On 9/7/07, GiBo wrote: > Hi, > > what's the best practice to securely prompt user for password on console > in Python? IIRC some programs like SSH do a lot to ensure that the input > comes from TTY and is not redirected from somewhere and several other > checks. In the case of OpenSSH even the password prompt is always > displayed regardless if the output is redirected to a file or not. > > Any pointers to best practice or code snippet of python password prompt? > The getpass module. From gagsl-py2 at yahoo.com.ar Mon Sep 17 21:58:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Sep 2007 22:58:59 -0300 Subject: Entering strings as user input but interpreting as Python input (sort of) References: Message-ID: En Mon, 17 Sep 2007 21:01:38 -0300, Chris Carlen escribi?: > I'm writing a Python program, a hex line editor, which takes in a line > of input from the user such as: > > >>> cmd = raw_input('-').split() > -e 01 02 "abc def" 03 04 > >>> cmd > ['e', '01', '02', '"abc', 'def"', '03', '04'] > > Trouble is, I don't want to split the quoted part where the space occurs. For this, try using the shlex module The cmd module may be useful too, so you can concentrate on your own functions, not the framework: -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Sep 6 10:23:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Sep 2007 16:23:59 +0200 Subject: startswith( prefix[, start[, end]]) Query In-Reply-To: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> References: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> Message-ID: <46e00d7e$0$16413$426a74cc@news.free.fr> cjt22 at bath.ac.uk a ?crit : > Hi > > startswith( prefix[, start[, end]]) States: > > Return True if string starts with the prefix, otherwise return False. > prefix can also be a tuple of suffixes to look for. However when I try > and add a tuple of suffixes I get the following error: > > Type Error: expected a character buffer object > > For example: > > file = f.readlines() > for line in file: slightly OT, but: 1/ you should not use 'file' as an identifier, it shadowas the builtin file type 2/ FWIW, it's also a pretty bad naming choice for a list of lines - why not just name this list 'lines' ?-) 3/ anyway, unless you need to store this whole list in memory, you'd be better using the iterator idiom (Python files are iterables): f = open('some_file.ext') for line in f: print line > if line.startswith(("abc","df")) > CODE > > It would generate the above error May I suggest that you read the appropriate version of the doc ? That is, the one corresponding to your installed Python version ?-) Passing a tuple to str.startswith is new in 2.5. I bet you're trying it on a 2.4 or older version. > To overcome this problem, I am currently just joining individual > startswith methods > i.e. if line.startswith("if") or line.startswith("df") > but know there must be a way to define all my suffixes in one tuple. You may want to try with a regexp, but I'm not sure it's worth it (hint: the timeit module is great for quick small benchmarks). Else, you could as well write your own testing function: def str_starts_with(astring, *prefixes): startswith = astring.startswith for prefix in prefixes: if startswith(prefix): return true return false for line in f: if str_starts_with(line, 'abc, 'de', 'xxx'): # CODE HERE HTH From tim.couper at scivisum.co.uk Tue Sep 4 09:53:46 2007 From: tim.couper at scivisum.co.uk (Tim Couper) Date: Tue, 04 Sep 2007 14:53:46 +0100 Subject: Setting Current Dir in Python In-Reply-To: References: <000001c7eeec$d9341470$8b9c3d50$@net> <46DD5135.7060501@scivisum.co.uk> Message-ID: <46DD636A.7090209@scivisum.co.uk> Steve Of course it is. I'd like to think I left a test for the observant, but in reality it just shows I can't copy-type ... :-) Tim Dr Tim Couper CTO, SciVisum Ltd www.scivisum.com Steve Holden wrote: > Tim Couper wrote: > >> "Non-ASCII character '\xef' in file" >> >> SandhirFileMonitor.py on line 356, >> >> This is reason for the failure .. you have a (probably accidentally placed) non-ascii (ie whose value is > 128) character on line 356, whose hex value is ef (decimal 259) . Solution: find that line and remove the character - or line. >> >> > Tim: > > You should know that any two-digit hexadecimal number is less than 255! > > >>> int("ef", 16) > 239 > > regards > Steve > From richardjones at optushome.com.au Fri Sep 21 22:42:17 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 22 Sep 2007 12:42:17 +1000 Subject: Registration for OSDC 2007 is open Message-ID: <200709221242.17442.richardjones@optushome.com.au> OSDC 2007 is in Brisbane this year on 27-29 November (with a tutorial day on the 26th). $275 early bid registration closes October 14th. Just follow the instructions at the top of http://osdc.com.au/registration/ to 1. register and 2. pay. (If you are going to pay by credit card/PayPal you should note the OS7xxxxx invoice number that the registration process allocates you and re-enter that when you pay.) Richard From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 5 10:43:02 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 05 Sep 2007 16:43:02 +0200 Subject: handling modules in packages In-Reply-To: References: <619B716A-C1EB-42DF-9702-E288AD04F613@mac.com> Message-ID: <46dec070$0$25029$426a74cc@news.free.fr> Tommy Grav a ?crit : (snip) > > So am I understanding it right that a second import numpy statement > in a different module (and thus a different namespace) just results in > a binding to the already existing numpy "object"? Yes. And FWIW, you can drop the quotes around the word 'object', because Python's modules *are* objects: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.__class__ >>> HTH From a.schmolck at gmail.com Wed Sep 5 08:48:02 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Wed, 05 Sep 2007 13:48:02 +0100 Subject: Calling a matlab script from python References: <1188978068.544030.158010@19g2000hsx.googlegroups.com> Message-ID: n o s p a m p l e a s e writes: > Suppose I have a matlab script mymatlab.m. How can I call this script > from a python script? You could use . 'as From sajmikins at gmail.com Mon Sep 17 02:12:40 2007 From: sajmikins at gmail.com (Simon Forman) Date: Mon, 17 Sep 2007 06:12:40 -0000 Subject: Tkinter pack difficulty In-Reply-To: References: <1189617737.700363.187450@g4g2000hsf.googlegroups.com> Message-ID: <1190009560.393700.170690@w3g2000hsg.googlegroups.com> Thanks everyone for the incredibly helpful replies! I got the effect I wanted, no problem. I don't know why I didn't think to remove the expand option. I thought the sticky option would constrain the expansion. Thanks again, ~Simon From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 17 10:15:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 17 Sep 2007 16:15:04 +0200 Subject: Saving parameters between Python applications? In-Reply-To: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> Message-ID: <46ee8be6$0$14822$426a74cc@news.free.fr> Stodge a ?crit : > I'm trying to do the following. I have a Python application that is > run: > > python app1.py --location=c:\test1 > > What I want to do is save the location parameter, so I can then do (in > the same window): > > python app2.py > > And have app2.py automatically have access to the value of "location". > > Now, the difficult part is, that in another window I want to do: > > python app1.py --location=c:\test2 > python app2.py > > And have app2.py automatically get c:\test2 as the location. So the > two windows (consoles) are isolated from each other. > > I thought I could use os.environ, but that doesn't save the variable > for applications that are run afterwards in the same window. > > Any suggestions? Yes : pass the same arg to both app1.py and app2.py !-) Braindead, I know, but still the simplest solution. From aleax at mac.com Thu Sep 13 11:23:07 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 13 Sep 2007 08:23:07 -0700 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> Message-ID: <1i4dddf.piaojwz9lz40N%aleax@mac.com> TheFlyingDutchman wrote: > > >>> Foo.bar(foo, "spam") > > >>> foo.bar("spam") > > That looks like a case of "There's more than one way to do it". ;) > The first form is definitely consistent with the > method declaration, so there's a lot to be said for using that style > when teaching people to make classes -> send self, receive self. On the other hand, the second form is not polymorphic: it doesn't allow for foo to be an instance of some OTHER class (possibly subclassing Foo and overriding bar) -- it will call the Foo version of bar anyway. type(foo).bar(foo, "spam") *IS* almost semantically equivalent to the obviousy simpler foo.bar("spam") -- but doesn't cover the possibility for foo to do a *per-instance* override of 'bar'. getattr(foo, 'bar', functools.partial(type(foo).bar, foo))("spam") is getting closer to full semantic equivalence. And if you think that's "another OBVIOUS way of doing it" wrt foo.bar("spam"), I think your definition of "obvious" may need a reset (not to mention the fact that the "equivalent" version is way slower;-). Foo.bar(foo, "spam")'s different semantics are important when any implementation of type(foo).bar (or other method yet) wants to BYPASS polymorphism to redirect part of the functionality to a specific type's implementation of bar ('super' may help in some cases, but it keeps some polymorphic aspects and pretty often you just want to cut all polymorphism off and just redirect to ONE specific implementation). Alex From svenn.bjerkem at googlemail.com Wed Sep 26 16:49:10 2007 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Wed, 26 Sep 2007 20:49:10 -0000 Subject: Script to extract text from PDF files In-Reply-To: <1190747931.415834.75670@n39g2000hsh.googlegroups.com> References: <1190746968.162359.39890@r29g2000hsg.googlegroups.com> <1190747931.415834.75670@n39g2000hsh.googlegroups.com> Message-ID: <1190839750.537205.193110@d55g2000hsg.googlegroups.com> On Sep 25, 9:18 pm, byte8b... at gmail.com wrote: > On Sep 25, 3:02 pm, Paul Hankin wrote: > > > Googling for 'pdf to text python' and following the first link giveshttp://pybrary.net/pyPdf/ > > Doesn't work that well, I've tried it, you should too... the author > even admits this: > > extractText() [#] > > Locate all text drawing commands, in the order they are provided > in the content stream, and extract the text. This works well for some > PDF files, but poorly for others, depending on the generator used. > This will be refined in the future. Do not rely on the order of text > coming out of this function, as it will change if this function is > made more sophisticated. - sourcehttp://pybrary.net/pyPdf/pythondoc-pyPdf.pdf.html I have downloaded this package and installed it and found that the text-extraction is more or less useless. Looking into the code and comparing with the PDF spec show a very early implementation of text extraction. Luckily it is possible to overwrite the textextraction method in the base class without having to fiddle with the original code. I tried to contact the developer to offer some help on implementing text extraction, but he didn't answer my emails. -- Svenn From jjl at pobox.com Thu Sep 20 15:27:51 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 20 Sep 2007 19:27:51 GMT Subject: UTF-8 characters in doctest References: <1190202459.229197.297350@n39g2000hsh.googlegroups.com> Message-ID: <878x71jfwo.fsf@pobox.com> Peter Otten <__peter__ at web.de> writes: [...] > # -*- coding: utf8 -*- > r""" >>>> f("???".decode("utf8")) > (u'\xe4\xf6\xfc',) > """ > def f(s): > return (s,) Forgive me if this is a stupid question, but: What purpose does function f serve? John From mail at microcorp.co.za Sat Sep 1 04:46:54 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 1 Sep 2007 10:46:54 +0200 Subject: list index() (OT) References: <1188456273.102334.48660@50g2000hsm.googlegroups.com><46d674c2$0$417$426a34cc@news.free.fr><1188496588.750629.208100@g4g2000hsf.googlegroups.com><1188497498.3468.60.camel@dot.uniqsys.com><021801c7eba2$ad429640$03000080@hendrik> <1cnfd31du01el95u70o8mjn9cb5r5aluiu@4ax.com><007f01c7ec65$605e6700$03000080@hendrik> Message-ID: <026301c7ec75$087eb980$03000080@hendrik> "Steve Holden" wrote: > Where's Godwin's Law when yo need it? Hitler would not have spellt "you" like that... - Hendrik From bj_666 at gmx.net Thu Sep 13 02:55:56 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Sep 2007 06:55:56 GMT Subject: python & osgi References: <1189645993.968565.313760@57g2000hsv.googlegroups.com> Message-ID: <5ks57sF57ml9U1@mid.uni-berlin.de> On Wed, 12 Sep 2007 18:13:13 -0700, Andreas Wapf wrote: > Is there something like a osgi implementation in python? I am really > impressed by the bundle system and the possibility to load and unload > bundles without wasting memory. I'm really impressed by the about 1000 pages OSGi specification. 8-) > Is it even possible to do something like that in python? Would be nice to > have a very small python interpreter and just load the modules as needed. Modules are only loaded as you import them, so you can make it as "lazy" as you want. I don't know if it's possible to unload them again. But is code really a memory problem? I've never thought "OMG memory is getting low, I wish I could unload a module to get some space." In my experience it's always data that eats my RAM. Ciao, Marc 'BlackJack' Rintsch From grante at visi.com Sat Sep 15 12:07:07 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Sep 2007 16:07:07 -0000 Subject: how to join array of integers? References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> Message-ID: <13eo0pbiab4spdf@corp.supernews.com> On 2007-09-15, Arnau Sanchez wrote: >>> in Python... is the method to use ",".join() ? but then it >>> must take a list of strings... not integers... >>> >>> any fast method? > > > print ''.join([str(i) for i in [1,2,3]]) > > It's better to use generator comprehension instead of LC: > > ",".join(str(i) for i in [1, 2, 3]) > > Or, if you happen to like the itertools modules: > > from itertools import imap > ",".join(imap(str, [1, 2, 3])) It's nice people have invented so many ways to spell the builting "map" ;) >>> ",".join(map(str,[1,2,3])) '1,2,3' -- Grant Edwards grante Yow! Thousands of days of at civilians... have produced visi.com a... feeling for the aesthetic modules -- From george.sakkis at gmail.com Sun Sep 30 22:36:23 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 01 Oct 2007 02:36:23 -0000 Subject: Using fractions instead of floats In-Reply-To: <1191202509.853059.222530@k79g2000hse.googlegroups.com> References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> Message-ID: <1191206183.441075.167450@57g2000hsv.googlegroups.com> On Sep 30, 9:35 pm, andresj wrote: > I was doing some programming in Python, and the idea came to my mind: using fractions instead of floats when doing 2/5. > (...) > I would like to get some feedback on this idea. Has this been posted > before? If so, was it rejected? and for what? Is internet down today ? http://pypi.python.org/pypi/clnum/1.2 http://www.python.org/dev/peps/pep-0239/ George From bbxx789_05ss at yahoo.com Sat Sep 15 17:27:13 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 15 Sep 2007 14:27:13 -0700 Subject: curses: x, y positioning Message-ID: <1189891633.622313.81850@r29g2000hsg.googlegroups.com> I can't see to get any y, x coordinates to work with curses. Here is an example: import curses def my_program(screen): while True: ch = screen.getch() if ch == ord("q"): break if ch <= 255: screen.addstr(30, 10, "*%s*" % chr(ch)) screen.refresh() curses.wrapper(my_program) Here is the result: Traceback (most recent call last): File "2pythontest.py", line 12, in ? curses.wrapper(my_program) File "/Library/Frameworks/Python.framework/Versions/2.4//lib/ python2.4/curses/wrapper.py", line 44, in wrapper return func(stdscr, *args, **kwds) File "2pythontest.py", line 9, in my_program screen.addstr(30, 10, "*%s*" % chr(ch)) _curses.error: addstr() returned ERR From rschroev_nospam_ml at fastmail.fm Tue Sep 25 08:36:54 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 25 Sep 2007 12:36:54 GMT Subject: Newbie completely confused In-Reply-To: References: Message-ID: Roel Schroeven schreef: > import time > > input_files = ["./test_file0.txt", "./test_file1.txt"] > > total_start = time.time() > data = {} > for input_fn in input_files: > file_start = time.time() > f = file(input_fn, 'r') > data[input_fn] = f.read() > f.close() > file_done = time.time() > print '%s: %f to read %d bytes' % (input_fn, file_done - > file_start, len(data)) ... that should of course be len(data[input_fn]) ... > total_done = time.time() > print 'all done in %f' % (total_done - total_start) > > > When I run that with test_file0.txt and test_file1.txt as you described > (each 30 MB), I get this output: > > ./test_file0.txt: 0.260000 to read 1 bytes > ./test_file1.txt: 0.251000 to read 2 bytes > all done in 0.521000 ... and then that becomes: ./test_file0.txt: 0.290000 to read 33170000 bytes ./test_file1.txt: 0.231000 to read 33170000 bytes all done in 0.521000 -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From gagsl-py2 at yahoo.com.ar Wed Sep 26 02:57:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Sep 2007 03:57:18 -0300 Subject: the address of list.append and list.append.__doc__ References: <1190775258.351819.24930@22g2000hsm.googlegroups.com> <1190780557.879816.13800@d55g2000hsg.googlegroups.com> <1190788149.477809.80130@g4g2000hsf.googlegroups.com> Message-ID: En Wed, 26 Sep 2007 03:29:09 -0300, HYRY escribi?: > I want to add a docstring translator into the Python interpreter. If > the user input: >>>> a = [1,2,3] >>>> a.append( > this translator will show the docstring of append in my native > language. Because __doc__ is read only, I added a dict to the > interpreter as follows: > > DOC[list.append.__doc__] = """ translated version of the __doc__ """ > > When it is the time to show docstring, the program get the translated > version from DOC. > This works, but I think the key of DOC is too long, so I want to use > the id of list.append.__doc__ as the key; or use the id of > list.append: Don't worry about that. There is no "wasted memory" apart from some overhead due to the string object itself (a few bytes per string, fixed and not depending on the string length). Just use the __doc__ as the dictionary key. Perhaps using an external database, to avoid keeping all the translated texts in memory. -- Gabriel Genellina From iclark at mail.ewu.edu Fri Sep 14 16:46:35 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Fri, 14 Sep 2007 13:46:35 -0700 Subject: subclass of integers In-Reply-To: <1189780201.692192.291010@k79g2000hse.googlegroups.com> References: <1189780201.692192.291010@k79g2000hse.googlegroups.com> Message-ID: Mark Morss wrote: > I would like to construct a class that includes both the integers and > None. I desire that if x and y are elements of this class, and both > are integers, then arithmetic operations between them, such as x+y, > return the same result as integer addition. However if either x or y > is None, these operations return None. > > It's simple enough to construct a subclass of integers that behave in > this way: > > class Nint(int): > def __add__(self,other): > if (other != None): > return self+other > else: > return None > def __radd__(self,other): > if (other != None): > return other+self > else: > return None > #...and so forth > > However I have not been able to figure out how to make it so that > None, as well as an integer, could be an element of my class. My > preliminary impression is that I have to override int.__new__; but I > am uncertain how to do that and have been unable to find anything on > the web explaining that. Indeed I haven't been able to find much > about __new__ at all. Overriding this method of built-in classes > seems to be quite unusual. > > I would very much appreciate anyone's help. My thought would be rather than trying to cram None into a subclass of int, to use delegation instead... -----8<-------------------------------------------------- class NoneInt(object): def __init__(self, value): self.value = value def __add__(self, other): if isinstance(other, NoneInt): if None in (self.value, other.value): return NoneInt(None) return NoneInt(self.value + other.value) elif isinstance(other, int): if self.value is None: return NoneInt(None) return NoneInt(self.value + other) else: raise TypeError( "unsupported operand type(s) for +: 'NoneInt'" "and '%s'" % str(other.__class__.__name__) ) __radd__ = __add__ def __str__(self): return 'NoneInt(%s)' % str(self.value) def main(): print '42? ', NoneInt(40) + NoneInt(2) print '41? ', NoneInt(40) + 1 print '40? ', 25 + NoneInt(15) print 'None? ', NoneInt(None) print 'None? ', NoneInt(None) + 1 print 'None? ', 1 + NoneInt(None) print 'Error? ', NoneInt(0) + 'spam' if __name__ == '__main__': main() -----8<-------------------------------------------------- Ian From cjt22 at bath.ac.uk Tue Sep 4 10:52:30 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Tue, 04 Sep 2007 07:52:30 -0700 Subject: Printing lists in columns In-Reply-To: <46dd69b1$0$24998$426a74cc@news.free.fr> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> <1188913394.763871.218660@d55g2000hsg.googlegroups.com> <46dd69b1$0$24998$426a74cc@news.free.fr> Message-ID: <1188917550.261894.84010@k79g2000hse.googlegroups.com> On Sep 4, 3:20 pm, Bruno Desthuilliers wrote: > cj... at bath.ac.uk a ?crit : > (snip) > > > Thanks guys > > > I have a list of lists such as > > a = ["1" , "2"] b = ["4", "5", "6"] c = ["7",8", "9"] > > Stored in another list: d = [a,b,c] > > > I know this makes me sound very stupid but how would I specify > > in the parameter the inner lists without having to write them all out > > such as: > > > for row in izip_longest(d[0], d[1], d[2], fillvalue='*'): > > print ', '.join(row) > > > i.e. How could I do the following if I didn't know how many list of > > lists I had. > > for row in izip_longest(*d, fillvalue='*'): > print ', '.join(row) > > HTH I thought that but when I tried it I recieved a "Syntax Error: Invalid Syntax" with a ^ pointing to fillvalue :S From joel.schaerer at gmail.com Thu Sep 27 09:31:22 2007 From: joel.schaerer at gmail.com (Joel) Date: Thu, 27 Sep 2007 06:31:22 -0700 Subject: Cross-platform time out decorator In-Reply-To: <1190802115.585306.250400@o80g2000hse.googlegroups.com> References: <1190802115.585306.250400@o80g2000hse.googlegroups.com> Message-ID: <1190899882.702911.44670@w3g2000hsg.googlegroups.com> On Sep 26, 12:21 pm, Joel wrote: > I've been using this nice timing out decorator :http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871. The > problem is that since it relies on sigalarm, it doesn't work under > windows. Would anyone know how to do a cross-platform version? > > Thanks a lot! > > joel I found the solution : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440569 describes a solution based on threads. I tested it and it works perfectly. From manuel.graune at koeln.de Mon Sep 24 12:55:45 2007 From: manuel.graune at koeln.de (Manuel Graune) Date: Mon, 24 Sep 2007 18:55:45 +0200 Subject: An Editor that Skips to the End of a Def References: <87odfxjgjy.fsf@pobox.com> <3Md*NJqVr@news.chiark.greenend.org.uk> Message-ID: Lawrence D'Oliveiro writes: > In message , Manuel Graune wrote: > >> Matthew Woodcraft writes: >> >>> Lawrence D'Oliveiro wrote:> >>> >>>> >>> >> And "cursor keys"? Please, every self respecting editor has ways for >> moving around quite a bit more efficiently. >> >> And on top of that a use case, which no one in his right mind would >> do this way. Accomplishing this task with search-and-replace would >> have taken about 10 seconds. With Mouse or Keyboard. > > Just to reinforce the point that the above was in no way an artificial or > isolated case: > > > Without knowing more about the design of those studies, further discussion is kind of pointless. I would really like to see a comparison of "mouse-centered IDEs" (e. g. Eclipse) vs. "keyboard-centered IDEs" (e. g. Emacs). used for some small progamming task (and not isolated editing problems). For one thing, most programmers more or less are not normal people. We tend to have superior memories, we actually grasp boolean logic, we have formed priesthoods around the most egregious interfaces, and we have a firm belief that the average citizen is in search of an editor for his daily C and Pascal coding tasks. We are not firmly rooted in the real world. So I'm not really concerned about the first-time user, for which without a doubt a mouse-based user-interface is easier (and probably faster). I need an editor/IDE I feel comfortable with after using it for a month or longer. And for the record: Being subjectively faster is good enough for me. I don't really care if I could have saved 15 minutes at the end of the day with the objectively faster interface, if I don't feel slowed down. But since this is not a usability-NG and I originally just wanted to point out that the specific example is far from ideal, I won't continue this discussion in this NG. If you want to, you can contact me by mail. Regards, Manuel -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 From mastro.francesco at gmail.com Thu Sep 27 09:12:40 2007 From: mastro.francesco at gmail.com (mastro.francesco at gmail.com) Date: Thu, 27 Sep 2007 06:12:40 -0700 Subject: Mysqldb & stderr Message-ID: <1190898760.854246.51690@n39g2000hsh.googlegroups.com> developing a daemon (using python 2.4 and mysqldb 1.2.1_p2) we notes that mysqldb class write on stderr some warnings and error asyncronously (uhmmm.... it's good written? ;P ). If stderr is closed these function raise up an I/O error (obviously). We spent a lot of time to understand for now we redirected stderr on /dev/null, but.. it's a workaround. Someone knows how stop write on stderr (and stdout) on mysqldb? Thanks. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 11 10:46:10 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 11 Sep 2007 16:46:10 +0200 Subject: newbie: stani's python editor if-else In-Reply-To: References: <1189484688.520933.25000@22g2000hsm.googlegroups.com> Message-ID: <46e6aa30$0$22433$426a74cc@news.free.fr> Steve Holden a ?crit : > madzientist wrote: >> hi, >> >> two quick questions: >> >> a) i am using SPE (latest version) and for some reason, when i type, >> say >> >> if 1==2: >> print "not equal" >> else: >> print "equal" >> >> the else is at the same indentation level as the preceding print >> statement, and i get a syntax error >> >> why doesn't spe automatically put the else at the level of the if >> statement ? (snip) > > The point here is that SPE isn't analyzing your source in sufficient > detail to recognize the need to "outdent" the else statement. Clearly > there could be any number of statements at the same indent level as the > first print statement. > > For the record this is not a behavior restricted to SPE, but also occurs > in Wing IDE, PythonWin and Scite, for starters. > > Technically you are correct in the example you give: an IDE could decide > to remove one level of indentation, but of course there's always the > "dangling else" problem: if one "if" statement is nested inside another > one, which indentation level would be appropriate for an "else"? > > Generally speaking, only the programmer can know, and so generally you > are left to enforce these issues for yourself. Emacs does a good job here - FWIW, it solves the "dangling else" problem by deindenting one level, then it's up to you to deindent more if appropriate. In practice, it turns out to be right most of the times, and not a problem in the few special cases. From wizzardx at gmail.com Wed Sep 12 06:20:47 2007 From: wizzardx at gmail.com (David) Date: Wed, 12 Sep 2007 12:20:47 +0200 Subject: MemoryError on reading mbox file In-Reply-To: <1189589259.662667.149730@w3g2000hsg.googlegroups.com> References: <1189589259.662667.149730@w3g2000hsg.googlegroups.com> Message-ID: <18c1e6480709120320k1f83a040r2e4138f4c95f880f@mail.gmail.com> > > My system has 512M RAM and 768M swap, which seems to run out at an > early stage of this. Is there a way to clean up memory for messages > already processed? It may be that Python's garbage collection isn't keeping up with your app. You could try periodically forcing it to run. eg: import gc gc.collect() You can also finetune the GC settings and check what is using up your memory. More info here: http://docs.python.org/lib/module-gc.html From zzbbaadd at aol.com Wed Sep 12 21:18:01 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 12 Sep 2007 18:18:01 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: <87sl5j5r34.fsf@benfinney.id.au> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> Message-ID: <1189646281.569796.267940@d55g2000hsg.googlegroups.com> On Sep 12, 5:47 pm, Ben Finney wrote: > TheFlyingDutchman writes: > > I am talking about how an author describes in English the "this" > > pointer/reference in their book on programming C++ or Java. > > > I don't think you will find them saying that under the covers "this" > > was passed to the method (if in fact it is). They just say that it > > refers to the current object inside that object's method. > > In other words, it's magic, and the behaviour has to be explained so > the reader knows where the undeclared 'this' comes from. I would disagree that it _has_ to be explained where it came from. I think knowing that the compiler is providing it is sufficient. Any further knowledge of what the compiler is doing under the covers to provide it is unnecessary. Sun made no mention of where "this" comes from in that link I provided. > > How is that preferable to the magic of "instance is passed as the > first argument to a method"? I would mention that an instance is passed as the first parameter argument of a method if the methods were declared with the extra argument and called with the extra argument: a = MyClass() my_method(a,someParameter) Then it makes sense to me to talk about it. From gagsl-py2 at yahoo.com.ar Sat Sep 29 21:56:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Sep 2007 22:56:56 -0300 Subject: Balloon Taskbar Popup for Windows XP References: <1191062421.610473.13070@19g2000hsx.googlegroups.com> Message-ID: En Sat, 29 Sep 2007 07:40:21 -0300, makko escribi?: > I need to create a function that will produce a balloon popup in the > taskbar when called. Whats the shortest and easiest way to do this? Mark Hammond's pywin32 extensions support notification icons but not balloon popups. The Windows NOTIFYICONDATA structure in newer shell versions contains more fields, required to show a balloon tooltip, but it is incompatible with earlier versions (there are dumb people in MS too...) Below there is a demo based on win32gui_taskbar.py, using pywin32, ctypes and struct. The bulk of code is just to create the window, setup the menu, and such. The balloon is shown on this fragment: def show_balloon(self): # For this message I can't use the win32gui structure because # it doesn't declare the new, required fields nid = PyNOTIFYICONDATA() nid.hWnd = self.hwnd nid.uFlags = NIF_INFO # type of balloon and text are random from random import choice nid.dwInfoFlags = choice([NIIF_INFO, NIIF_WARNING, NIIF_ERROR]) nid.szInfo = choice(["Balloon text.", "This text is nicer.", "Perl rulez! :)"]) nid.szInfoTitle = "A Title" # Call the Windows function, not the wrapped one from ctypes import windll Shell_NotifyIcon = windll.shell32.Shell_NotifyIconA Shell_NotifyIcon(NIM_MODIFY, nid.pack()) For more info see the Shell_NotifyIcon docs at # Based on win32gui_taskbar demo from win32api import * # Try and use XP features, so we get alpha-blending etc. try: from winxpgui import * except ImportError: from win32gui import * import win32con import sys, os import struct import timer class PyNOTIFYICONDATA: _struct_format = ( "I" # DWORD cbSize; "I" # HWND hWnd; "I" # UINT uID; "I" # UINT uFlags; "I" # UINT uCallbackMessage; "I" # HICON hIcon; "128s" # TCHAR szTip[128]; "I" # DWORD dwState; "I" # DWORD dwStateMask; "256s" # TCHAR szInfo[256]; "I" # union { # UINT uTimeout; # UINT uVersion; #} DUMMYUNIONNAME; "64s" # TCHAR szInfoTitle[64]; "I" # DWORD dwInfoFlags; # GUID guidItem; ) _struct = struct.Struct(_struct_format) hWnd = 0 uID = 0 uFlags = 0 uCallbackMessage = 0 hIcon = 0 szTip = '' dwState = 0 dwStateMask = 0 szInfo = '' uTimeoutOrVersion = 0 szInfoTitle = '' dwInfoFlags = 0 def pack(self): return self._struct.pack( self._struct.size, self.hWnd, self.uID, self.uFlags, self.uCallbackMessage, self.hIcon, self.szTip, self.dwState, self.dwStateMask, self.szInfo, self.uTimeoutOrVersion, self.szInfoTitle, self.dwInfoFlags) def __setattr__(self, name, value): # avoid wrong field names if not hasattr(self, name): raise NameError, name self.__dict__[name] = value class MainWindow: def __init__(self): message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_USER+20: self.OnTaskbarNotify, } # Register the Window class. wc = WNDCLASS() hinst = wc.hInstance = GetModuleHandle(None) wc.lpszClassName = "PythonTaskbarDemo" wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = CreateWindow( classAtom, "Taskbar Demo", style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, hinst, None) UpdateWindow(self.hwnd) iconPathName = os.path.abspath(os.path.join( sys.prefix, "pyc.ico" )) icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE try: hicon = LoadImage(hinst, iconPathName, win32con.IMAGE_ICON, 0, 0, icon_flags) except: hicon = LoadIcon(0, win32con.IDI_APPLICATION) flags = NIF_ICON | NIF_MESSAGE | NIF_TIP nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "Balloon tooltip demo") Shell_NotifyIcon(NIM_ADD, nid) print "Ready. Click on the Python icon." def OnTaskbarNotify(self, hwnd, msg, wparam, lparam): if lparam==win32con.WM_LBUTTONUP or lparam==win32con.WM_RBUTTONUP: print "Click." menu = CreatePopupMenu() AppendMenu( menu, win32con.MF_STRING, 1024, "Generate balloon") AppendMenu( menu, win32con.MF_STRING, 1025, "Exit") pos = GetCursorPos() SetForegroundWindow(self.hwnd) TrackPopupMenu(menu, win32con.TPM_LEFTALIGN, pos[0], pos[1], 0, self.hwnd, None) PostMessage(self.hwnd, win32con.WM_NULL, 0, 0) return 1 def enqueue_balloon(self): timer.set_timer(3000, self.show_balloon) print "A balloon will appear in 3 sec" def show_balloon(self, id, time): timer.kill_timer(id) # one-shot timer! # For this message I can't use the win32gui structure because # it doesn't declare the new, required fields nid = PyNOTIFYICONDATA() nid.hWnd = self.hwnd nid.uFlags = NIF_INFO # type of balloon and text are random from random import choice nid.dwInfoFlags = choice([NIIF_INFO, NIIF_WARNING, NIIF_ERROR]) nid.szInfo = choice(["Balloon text.", "This text is nicer.", "Perl rulez! :)"]) nid.szInfoTitle = "A Title" # Call the Windows function, not the wrapped one from ctypes import windll Shell_NotifyIcon = windll.shell32.Shell_NotifyIconA Shell_NotifyIcon(NIM_MODIFY, nid.pack()) def OnCommand(self, hwnd, msg, wparam, lparam): id = LOWORD(wparam) if id == 1024: self.enqueue_balloon() elif id == 1025: print "Goodbye" DestroyWindow(self.hwnd) else: print "OnCommand for ID", id def OnDestroy(self, hwnd, msg, wparam, lparam): nid = (self.hwnd, 0) Shell_NotifyIcon(NIM_DELETE, nid) PostQuitMessage(0) # Terminate the app. def main(): w=MainWindow() PumpMessages() if __name__=='__main__': main() -- Gabriel Genellina From iainking at gmail.com Wed Sep 12 04:59:49 2007 From: iainking at gmail.com (Iain King) Date: Wed, 12 Sep 2007 08:59:49 -0000 Subject: Difference between two times (working ugly code, needs polish) In-Reply-To: References: <13ee01cfc7f4be2@corp.supernews.com> <2dc0c81b0709111420r453ac15av6c7aa19473785080@mail.gmail.com> Message-ID: <1189587589.085002.34000@19g2000hsx.googlegroups.com> On Sep 12, 1:31 am, "Shawn Milochik" wrote: > > I suppose really oneDay should be a global (i.e. outside the function > > definition). Apart from that it would be hard to improve on: obvious, > > easy to read, in short - pythonic. > > > Are you concerned about daylight savings? That could certainly introduce > > a whole new level of complexity into the problem. Let's hope not ... > > I'm not concerned with DST; this is a script which checks my Ebay > auctions (I have some things for sale), and sends me e-mail whenever > someone bids. It's run by cron every half hour -- it keeps me from > compulsively checking my auctions. ^_^ > > In any case, DST isn't an issue because the same machine generates > both timestamps, and all I use it for is to stop displaying auctions > after they are 10 days old, so I don't get all my old crap filling up > the alert e-mail or skewing the total dollar amount for all active > auctions. > > Thanks. > Shawn Just to be picky - your function returns the number of days between two dates, but it's called isOld, which looks like it should return a boolean. i.e. it looks like it would be used as: if not isOld(auctionDate, currentTime): checkForBid() rather than how I assume it is used: if isOld(auctionDate, currentTime) <= 10: checkForBid() I'd call it daysDiff or something similar, or make it more specific so that it works like the first block of code above: ONEDAY = 60*60*24 OLDNESS_THRESHOLD = 10 def isOld(lastUpdate, runTimeStamp): lastUpdate = time.mktime(time.strptime(lastUpdate, "%Y-%m-%d_%H: %M")) runTimeStamp = time.mktime(time.strptime(runTimeStamp, "%Y-%m-%d_ %H:%M")) return (runTimeStamp - lastUpdate) / ONEDAY >= OLDNESS_THRESHOLD if not isOld(auctionDate, currentTime): checkForBid() Iain From afriere at yahoo.co.uk Mon Sep 3 22:32:13 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 03 Sep 2007 19:32:13 -0700 Subject: Python is overtaking Perl In-Reply-To: References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> <20070904024908.b8aca60c.sulsa@gazeta.pl> <1188869347.102325.119830@w3g2000hsg.googlegroups.com> Message-ID: <1188873133.137684.147260@r29g2000hsg.googlegroups.com> On Sep 4, 11:49 am, Erik Max Francis wrote: > Who knows? The graph has no labeling or calibration for the y-axis, so > it's meaningless. > Well yes, some calibration would make it more meaningful, but it is at least labeled 'Search Volume.' What's worse the calibration changes with any search you do (try 'java programming, python programming'). In any case this is how Google describe what they are doing. |Google Trends analyzes a portion of Google web searches to compute how many |searches have been done for the terms you enter, relative to the total number |of searches done on Google over time. We then show you a graph with the |results -- our search-volume graph -- plotted on a linear scale. So I think we can at least say from the chart that searches combining the terms 'python' and 'programming' have been falling, by some unquantifiable amount (it don't _look_ like much!?), relative to the number of total searches. I think we can also say that nothing in the chart implies that the "amount of python programers is smaller every year." From bdesth.quelquechose at free.quelquepart.fr Wed Sep 19 15:23:03 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 21:23:03 +0200 Subject: cannot create my own dict In-Reply-To: References: Message-ID: <46f17743$0$12915$426a34cc@news.free.fr> A.T.Hofkamp a ?crit : > Hello all, > > This morning I tried to create my own read-only dictionary, and failed > miserably. > I don't understand why, can somebody enlighten me? > > Below is a brute-force experiment that cannot deal with "x in obj", plz read > the explanation below the code: > -------------------------------- > class myowndict(object): > def __init__(self, mydict): > self.mydict = mydict Why don't you just subclass dict and override the needed method(s) ? class ReadOnlyDict(dict): @classmethod def _raise(cls): raise AttributeError("%s is read-only" % cls.__name__) def __setitem__(self, name, val): self._raise() def setdefault(self, name, value=None): self._raise() # TODO : check if I missed some other setter ? def test(d): print d try: d['c'] = 3 except AttributeError, e: print "__setitem__ ok, got : %s" % e else: assert('failed on __setitem__') try: d.setdefault('c', 3) except AttributeError, e: print "setdefault ok, got : %s" % e else: assert('failed on setdefault') if __name__ == '__main__': d1 = ReadOnlyDict(a=1, b=2) test(d1) d2 = ReadOnlyDict({'a':1, 'b':2}) test(d2) d3 = ReadOnlyDict((c, i+1) for i, c in enumerate('ab')) test(d3) d4 = ReadOnlyDict(**d1) test(d4) NB : works fine so far, but choke on fromkeys, which obviously uses __setitem__ > # Below is produced with > # print '\n'.join([' self.%s = self.mydict.%s' % (v,v) > # for v in dir(dict)]) > # commented-out functions done by hand > # > #self.__class__ = self.mydict.__class__ > self.__cmp__ = self.mydict.__cmp__ > self.__contains__ = self.mydict.__contains__ (snip lots of useless code) May I suggest that you learn to use __getattr__ and __setattr__ ?-) HTH From nagle at animats.com Tue Sep 25 13:40:50 2007 From: nagle at animats.com (John Nagle) Date: Tue, 25 Sep 2007 10:40:50 -0700 Subject: M2Crypto 0.18 - new version, same old build bugs - more details In-Reply-To: References: <46F82296.5010701@animats.com> Message-ID: <7ybKi.1138$hI7.1043@newssvr17.news.prodigy.net> Heikki Toivonen wrote: > John Nagle wrote: > >>But notice that the -D entry didn't appear on the SWIG command line. >>Neither did the "-includeall". The "swig_opts" values around line >>129 aren't actually being used. I think that's left over from the code >>intended >>to allow builds with Python 2.3 and earlier. The "self.swig_opts" up at >>line 53 of "setup.py" seems to be controlling. The patch was to >>the obsolete code. > > > Aha! Good find. I reopened > https://bugzilla.osafoundation.org/show_bug.cgi?id=9404 and attached a > patch that should address this for real this time. At least -includeall > appears in my Ubuntu Dapper Drake environment. Could you give it a go > and let me know how it works? That's progress, but the build still doesn't work: $ python setup.py build running build running build_py running build_ext building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/local/include/python2.5 -I/usr/include -includeall -D__i386__ -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:13: Error: Unable to find 'opensslconf-i386.h' error: command 'swig' failed with exit status 1 Now that SWIG is being invoked with "-includeall", it has to have all the include paths defined. (Without "includeall", includes are deferred until the C compile stage.) Note that the SWIG command line specifies "/usr/include", but not "/usr/include/openssl". Within M2Crypto's SWIG files, there's _ec.i:%include which brings in "opensslconf.h" from /usr/include/openssl. But that file has #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) ... Since "opensslconf-i386.h" lives in /usr/include/openssl, and that directory isn't mentioned on the SWIG command line, the #include of "opensslconf-i386.h" fails. And, no, adding self.swig_opts.append('-DOPENSSL_NO_EC') # Uncomment if you can't build with EC disabled does not help. As a test, I tried adding "-I/usr/include/openssl" to the SWIG command line. Building then gets further, but during a C compile, we get SWIG/_m2crypto_wrap.c:2529:18: error: _lib.h: No such file or directory and the build goes downhill from there, with many compile errors in the GCC phase. The gcc call gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python2.5 -c SWIG/_m2crypto_wrap.c -o build/temp.linux-i686-2.5/SWIG/_m2crypto_wrap.o -DTHREADING is in the directory below SWIG, and doesn't include SWIG, so it's clear why gcc couldn't find the file. So those fixes were not enough. Include file management in the M2Crypto build clearly needs some work. John Nagle From iclark at mail.ewu.edu Fri Sep 21 17:14:48 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Fri, 21 Sep 2007 14:14:48 -0700 Subject: newb: Simple regex problem headache In-Reply-To: <1190408680.273525.209270@w3g2000hsg.googlegroups.com> References: <1190408680.273525.209270@w3g2000hsg.googlegroups.com> Message-ID: crybaby wrote: > import re > > s1 =' 25000 ' > s2 = ' 5.5910 ' > > mypat = re.compile('[0-9]*(\.[0-9]*|$)') > rate= mypat.search(s1) > print rate.group() > > rate=mypat.search(s2) > print rate.group() > rate = mypat.search(s1) > price = float(rate.group()) > print price > > I get an error when it hits the whole number, that is in this format: > s1 =' 25000 ' > For whole number s2, mypat catching empty string. I want it to give > me 25000. > I am getting this error: > > price = float(rate.group()) > ValueError: empty string for float() > > Anyone knows, how I can get 25000 out of s2 = ' 5.5910 ' > using regex pattern, mypat = re.compile('[0-9]*(\.[0-9]*|$)'). mypat > works fine for real numbers, but doesn't work for whole numbers. > > thanks > Try this: >>> import re >>> s1 =' 25000 ' >>> s2 = ' 5.5910 ' >>> num_pat = re.compile(r'([0-9]+(\.[0-9]+)?)') >>> num_pat.search(s1).group(1) '25000' >>> num_pat.search(s2).group(1) '5.5910' Ian From bj_666 at gmx.net Sat Sep 22 17:28:21 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2007 21:28:21 GMT Subject: I could use some help making this Python code run faster using only Python code. References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> <1190394011.148384.106280@q3g2000prf.googlegroups.com> <1190417120.723579.267560@22g2000hsm.googlegroups.com> <5ljrklF8gic1U3@mid.uni-berlin.de> <1190491227.688310.247030@w3g2000hsg.googlegroups.com> Message-ID: <5llfnlF8gic1U11@mid.uni-berlin.de> On Sat, 22 Sep 2007 13:00:27 -0700, Python Maniac wrote: > On Sep 21, 11:39 pm, Marc 'BlackJack' Rintsch wrote: >> On Fri, 21 Sep 2007 16:25:20 -0700, Python Maniac wrote: >> >> > Well D code is compiled into machine code that runs via a VM. >> >> About which D are we talking here? Not digital mars' successor to C++, >> right!? > > Yes, Digital Mars D is what I was referring to and yes I know D is not > as efficient as C++. But D code doesn't run in a VM unless you see hardware processors as VMs. Ciao, Marc 'BlackJack' Rintsch From lutz at rmi.net Mon Sep 3 17:19:54 2007 From: lutz at rmi.net (Mark Lutz) Date: Mon, 03 Sep 2007 14:19:54 -0700 Subject: Colorado Python training in October Message-ID: <1188854394.021585.121570@o80g2000hse.googlegroups.com> Python author and trainer Mark Lutz will be teaching another 3-day Python class at a conference center in Longmont, Colorado, on October 23-25, 2007. This is a public training session open to individual enrollments, and covers the same topics as the 3-day onsite sessions that Mark teaches, with hands-on lab work. For more information on this class, please visit these web pages: http://home.earthlink.net/~python-training/longmont-public-classes.htm Thanks for your interest. --Python Training Services From zentraders at gmail.com Thu Sep 6 19:41:26 2007 From: zentraders at gmail.com (Zentrader) Date: Thu, 06 Sep 2007 16:41:26 -0700 Subject: Finding specific date ranges In-Reply-To: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> Message-ID: <1189122086.388859.146670@r34g2000hsd.googlegroups.com> On Sep 6, 7:56 am, kyoso... at gmail.com wrote: > December 31, 2006 January 13, 2007 # doesn't earn > January 14, 2007 January 27, 2007 # does earn > January 28, 2007 February 10, 2007 # doesn't > February 11, 2007 February 24, 2007 # does Am I over simplifying if I say that since it appears to be a two week pay period, the date has to be greater than the 11th unless the first, or first and second, are on a weekend, in which case it would be > 12 or > 13? Or a reasonable facsimile thereof, depending on whether or not the two week period is Saturday through Friday. From sjmachin at lexicon.net Sun Sep 16 18:28:01 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 16 Sep 2007 15:28:01 -0700 Subject: Try this In-Reply-To: <1189979679.969074.216490@y42g2000hsy.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> Message-ID: <1189981681.745195.18130@y42g2000hsy.googlegroups.com> On Sep 17, 7:54 am, "mensana... at aol.com" wrote: > On Sep 16, 2:22?pm, Steve Holden wrote: > > > > > mensana... at aol.com wrote: > > > On Sep 16, 1:10?pm, Dennis Lee Bieber wrote: > > >> On Sun, 16 Sep 2007 01:46:34 -0700, GeorgeRXZ > > >> declaimed the following in comp.lang.python: > > > >>> Then Open the Notepad and type the following sentence, and save the > > >>> file and close the notepad. Now reopen the file and you will find out > > >>> that, Notepad is not able to save the following text line. > > >>> Well you are speed > > >>> This occurs not only with above sentence but any sentence that has > > >>> 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) > > >> I tried. I also opened the saved file in SciTE... > > >> And the text WAS there... > > > >> It is Notepad that can not properly render what it, > > >> itself, saved. > > > > C:\Documents and Settings\mensanator\My Documents>type huh.txt > > > Well you are speed > > > > Yes, file was saved correctly. > > > But reopening it shows 9 unprintable characters. > > > If I copy those to a new file (huh1.txt): > > > > C:\Documents and Settings\mensanator\My Documents>type huh1.txt > > > ????????? > > > > But wait...the new file is 20 characters, not 9. > > > > 09/16/2007 01:44 PM 18 huh.txt > > > 09/16/2007 01:54 PM 20 huh1.txt > > > > C:\Documents and Settings\mensanator\My Documents>dump huh.txt > > > huh.txt: > > > 00000000 5765 6c6c 2079 6f75 2061 7265 2073 7065 Well you are spe > > > 00000010 6564 ed > > > > Here's what it's actually doing: > > > > C:\Documents and Settings\mensanator\My Documents>dump huh1.txt > > > huh1.txt: > > > 00000000 fffe 5765 6c6c 2079 6f75 2061 7265 2073 .~Well you are s > > > 00000010 7065 6564 peed > > > One word: Unicode. > > > The "open" and "save" dialogs allow you to specify an encoding. > > And the encoding specified was ANSI. > > > If you > > specify Unicode the you will get what you see above. > > And if you specify ANSI _before_ you click the file name, > the specification switches to Unicode and has to then > be manually switched back to ANSI. > > > If you specify ANSI > > you will get the text you entered. > > It's still a bug in the "open" dialog. It's more like a bug/feature in its encoding detector. I can get it to switch to Unicode only if there's an even number of characters AND the line is NOT terminated by CRLF -- add/remove one alpha character, or hit the enter key at the end of the line, and it won't detect it as Unicode when you open it again. You only get the BOM (0xfffe) if you are silly enough to save it while it's open in Unicode mode. > > > > > By the way, this has precisely what to do with Python? > > I've been known to use Notepad to create Python > source code. Your source code would have to be trivially short to trigger the strange behaviour. From pdula at cisco.com Mon Sep 24 05:37:49 2007 From: pdula at cisco.com (Piotr Dula (pdula)) Date: Mon, 24 Sep 2007 11:37:49 +0200 Subject: IPv6 in python Message-ID: Hello, How to make python support IPv6? I tried to do: ./configure --enable-ipv6 make make install and I didn't get any error. However, IPv6 doesn't seem to be working yet. then I tried ./configure --enable-ipv6=yes and I got a lot of parse errors (many pages similar to this below) In file included from /root/Piotr/Python-2.5.1/Modules/_tkinter.c:67: /usr/include/tk.h:581: parse error before "Bool" /usr/include/tk.h:583: parse error before "event" /usr/include/tk.h:584: parse error before "root" /usr/include/tk.h:585: parse error before "subwindow" /usr/include/tk.h:586: parse error before "time" /usr/include/tk.h:586: `time' redeclared as different kind of symbol /usr/include/time.h:184: previous declaration of `time' /usr/include/tk.h:591: parse error before "same_screen" /usr/include/tk.h:597: parse error before "Bool" /usr/include/tk.h:599: parse error before "window" /usr/include/tk.h:601: parse error before "XActivateEven How to make it work? Thank you in advance, Piotr -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Tue Sep 25 00:15:49 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Sep 2007 21:15:49 -0700 Subject: vim - what's a smarttab? In-Reply-To: References: <1190624225.926815.149720@50g2000hsm.googlegroups.com> Message-ID: <1190693749.202770.227890@57g2000hsv.googlegroups.com> On Sep 24, 4:49 am, Marco wrote: > > > Alternatively, what is a smarttab? > > in VIM type :help smarttab and you'll see the following: > Thanks! I spent an hour hunting around on google with no success. :( Another question if you don't mind. I'm using vim 6.2, and I am trying to setup vim to use different tab sizes based on different file types. I've searched around, and as far as I can tell, this should work: filetype indent on Somehow that is supposed to let vim decide what type of file is being edited. But, it doesn't work for me. Is there a list of file types vim can recognize? This is what my ~/.vimrc file looks like: "python settings: set tabstop=4 "4 space tab set shiftwidth=4 "The amount to block indent when using < and > set smarttab "Uses shiftwidth instead of tabstop at start of lines set expandtab "Replaces a with spaces--more portable set softtabstop=4 "Causes backspace to delete 4 spaces = converted "general settings: filetype indent on "new in vim 6.0+; file type specific indenting set nu "line numbers on (set nonu) syntax on "turns on syntax highlighting From bdesth.quelquechose at free.quelquepart.fr Mon Sep 3 11:10:54 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 03 Sep 2007 17:10:54 +0200 Subject: function call In-Reply-To: <46ddc12c$0$24997$426a74cc@news.free.fr> References: <1188937059.459609.61850@57g2000hsv.googlegroups.com> <46ddc12c$0$24997$426a74cc@news.free.fr> Message-ID: <46ddc536$0$30590$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > ianar? a ?crit : > >> Hey all, >> >> Is there a way of printing out how a function was called? In other >> words if I do the following: >> >> def someFunction(self): >> self.someOtherFunction(var1, var2) >> >> >> I would get something like "someOtherFunction: called by: >> someFunction, args are: var1, var2" >> >> Thanks in advance >> > You may be able to solve this using a decorator (to avoid polluting your > code with this) and the infamous sys._getframe() hack. Not even with sys._getframe in fact - or at least not directly !-) import inspect def trace(func): def traced(*args, **kw): f = inspect.currentframe(1) caller = inspect.getframeinfo(f)[2] print "%s : called by %s with %s %s" \ % (caller, func.__name__, str(args), kw) return func(*args, **kw) return traced @trace def test(toto, tata=None): return 42 def call(toto): return test(toto, 24) call("foo") HTH From DustanGroups at gmail.com Sun Sep 16 13:08:06 2007 From: DustanGroups at gmail.com (Dustan) Date: Sun, 16 Sep 2007 17:08:06 -0000 Subject: Try this In-Reply-To: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> Message-ID: <1189962486.806757.257700@w3g2000hsg.googlegroups.com> On Sep 16, 3:46 am, GeorgeRXZ wrote: > If you have Microsoft windows 98/2000/ME/XP/2003 Operating System on > your PC. > Then Open the Notepad and type the following sentence, and save the > file and close the notepad. Now reopen the file and you will find out > that, Notepad is not able to save the following text line. > > Well you are speed > > This occurs not only with above sentence but any sentence that has > > 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) > > When type following sentence and save file then same thing occurs. > > This is not Maria > > GEOrgE > << Develop a website that will help people, > Avoid spamming, provide quality contents on your website >> > > http://zsoftwares.googlepages.com/index.htm Didntworkiwantmymoneyback. From stef.mientki at gmail.com Sun Sep 23 18:08:09 2007 From: stef.mientki at gmail.com (stef mientki) Date: Mon, 24 Sep 2007 00:08:09 +0200 Subject: building a GUI In-Reply-To: <200709232234.54500.phil@riverbankcomputing.co.uk> References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> <5lnp2rF90pqqU1@mid.uni-berlin.de> <46F6CB6C.3050609@gmail.com> <200709232234.54500.phil@riverbankcomputing.co.uk> Message-ID: <46F6E3C9.7040702@gmail.com> Phil Thompson wrote: > On Sunday 23 September 2007, stef mientki wrote: > >> Diez B. Roggisch wrote: >> >>> stef mientki schrieb: >>> >>>> Thomas Dybdahl Ahle wrote: >>>> >>>>> Den Sun, 23 Sep 2007 17:28:38 +0200 skrev stef mientki: >>>>> >>>>>> yadin wrote: >>>>>> >>>>>>> if i were up to make a GUI chich are the advantages of choosing >>>>>>> python over matlab or java? >>>>>>> >>>>>> The best is Delphi, >>>>>> second is VB, >>>>>> >>>>> That sounds mostly like a personal preference :) >>>>> >>>> Well I prefer Python ( because of it's OS-independancy and it's open >>>> source), >>>> but Python is really (still) much worse for GUI designs. >>>> Just compare some parameters like: >>>> - ease of use >>>> - speed of development >>>> - support of features >>>> - availability of libraries >>>> - documentation >>>> >>> Sounds like PyQt for me. Best GUI-designer I know, tremendous speed in >>> development, giant sized lib that does all kinds of stuff & is >>> brilliantly designed + professional grade docus. >>> >> Could well be, >> but I never looked at PyQt seriously, >> because of their weird license. >> > > It's not weird. It's either GPL or proprietary. Your choice. That's as > complicated as it gets. > This is what I find "weird": == quote == Trolltech's commercial license terms do not allow you to start developing proprietary software using the Open Source edition. == end quote == Stef From jcd at sdf.lonestar.org Sun Sep 9 15:15:56 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Sun, 09 Sep 2007 15:15:56 -0400 Subject: Modul (%) in python not like in C? In-Reply-To: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> Message-ID: <46E4466C.2030303@sdf.lonestar.org> Dotan Cohen wrote: > FIrst of all, how is the % symbol (as in 70%6=4) called in English? > > Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or > the other in error? Is this a known gotcha? I tried to google the > subject however one cannot google the symbol %. Thanks in advance. > > Dotan Cohen > The % operator is called "modulo" in English. I don't think the difference in implementation is an error. It's just a difference of calculation method. Python will always yield a number x = m%n such that 0 <= x < n, but Turbo C will always yield a number such that if x = m%n -x = -m%n. That is, since 111 % 10 = 1, -111 % 10 = -1. The two values will always differ by n (as used above). I'm sure there are mathematicians on the list who can give you a more technical, precise explanation of the reasons for the different results. Cheers, Cliff From grante at visi.com Thu Sep 6 22:34:10 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Sep 2007 02:34:10 -0000 Subject: why should I learn python References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> Message-ID: <13e1e52cfb1u505@corp.supernews.com> On 2007-09-06, Torsten Bronger wrote: > Hall?chen! > > Tom Brown writes: > >> [...] Python has been by far the easiest to develop in. Some >> people might say it is not "real programming" because it is so >> easy. > > I can't believe this. Have you really heard such a statement? Maybe it's a allusion to that fake Stroustrup interview where he supposedly explains that C++ was meant to be a difficult language to use as a means to keep more programmers employed at higher salaries? -- Grant Edwards grante Yow! Yow! I threw up on at my window! visi.com From jcd at sdf.lonestar.org Tue Sep 11 06:53:50 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 11 Sep 2007 06:53:50 -0400 Subject: Enum class with ToString functionality In-Reply-To: <1r6ae3tuv8rj19ka3b2tpqsni29v48b7p5@4ax.com> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <1r6ae3tuv8rj19ka3b2tpqsni29v48b7p5@4ax.com> Message-ID: <46E673BE.6070208@sdf.lonestar.org> Zara wrote: > On Mon, 10 Sep 2007 02:28:57 -0700, bg_ie at yahoo.com wrote: > > >> Hi, >> >> I have the following class - >> >> class TestOutcomes: >> PASSED = 0 >> FAILED = 1 >> ABORTED = 2 >> >> plus the following code - >> >> testResult = TestOutcomes.PASSED >> >> testResultAsString >> if testResult == TestOutcomes.PASSED: >> testResultAsString = "Passed" >> elif testResult == TestOutcomes.FAILED : >> testResultAsString = "Failed" >> else: >> testResultAsString = "Aborted" >> >> But it would be much nicer if I had a function to covert to string as >> part of the TestOutcomes class. How would I implement this? >> >> > You should implement __str__ (or __repr__) method in your class, > > class TestOutcomes: > PASSED = 0 > FAILED = 1 > ABORTED = 2 > > def __str__(self): > textResultAsString="Unknown" > if testResult == TestOutcomes.PASSED: > testResultAsString = "Passed" > elif testResult == TestOutcomes.FAILED : > testResultAsString = "Failed" > else: > testResultAsString = "Aborted" > return testResultAsString > > Regards, > > Zara > > This code cannot output "Unknown," because you use an else: at the end of your if-chain to represent a specific (non-catch-all) case. s/else:/elif testResult == TestOutcomes.ABORTED:/ Cheers, Cliff From elmakko at gmail.com Sat Sep 29 06:40:21 2007 From: elmakko at gmail.com (makko) Date: Sat, 29 Sep 2007 10:40:21 -0000 Subject: Balloon Taskbar Popup for Windows XP Message-ID: <1191062421.610473.13070@19g2000hsx.googlegroups.com> Greetings, I need to create a function that will produce a balloon popup in the taskbar when called. Whats the shortest and easiest way to do this? Thanks. regards, Makko From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Sep 26 16:42:00 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 26 Sep 2007 22:42:00 +0200 Subject: Delete values from a string using the index References: <1190838311.630506.64670@y42g2000hsy.googlegroups.com> Message-ID: <5lvugoFap2kaU1@mid.individual.net> koutoo at hotmail.com wrote: > How do I delete or remove values from a list or string using the > index. > > If a = [1,2,3,4,5,6,7,8] and I want to get rid of 1 -5, how would > I do that? del a[0:5] Be sure to check out the relevant section of the Python tutorial. http://docs.python.org/tut/node7.html Regards, Bj?rn -- BOFH excuse #31: cellular telephone interference From llothar at web.de Sat Sep 1 06:44:10 2007 From: llothar at web.de (llothar) Date: Sat, 01 Sep 2007 03:44:10 -0700 Subject: How to find out if the interpreter is a debug build? In-Reply-To: <46d905d5$0$26151$9b622d9e@news.freenet.de> References: <1188609417.273513.74450@i13g2000prf.googlegroups.com> <46d905d5$0$26151$9b622d9e@news.freenet.de> Message-ID: <1188643450.431001.219220@o80g2000hse.googlegroups.com> On 1 Sep., 13:25, "Martin v. L?wis" wrote: > If you want it cross-platform, you can check whether sys.getobjects > is available. That, of course, is also unsafe because there isn't > a single "debug build" on Unix, but instead, several debugging > features can be enabled and disabled separately, so you would have > to specify first what precisely a debug build is. I thought that the answer is as complicated as this. At the moment it would be nice and enough if i only can find out if my binary extension can be loaded into an interpreter or if this requires a new extension build. It is a huge problem and weakness of python if this is impossible with debug builds. And if you answer that this is up to the user, i have to say, no it isn't: At least if you are like me and are working on an IDE with a debugger component. From bronger at physik.rwth-aachen.de Wed Sep 5 18:20:45 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 06 Sep 2007 00:20:45 +0200 Subject: Wanted: safe codec for filenames References: <87sl5tcrw9.fsf@wilson.homeunix.com> Message-ID: <87ps0w92ki.fsf@wilson.homeunix.com> Hall?chen! Torsten Bronger writes: > I'd like to map general unicode strings to safe filename. I tried > punycode but it is case-sensitive, which Windows is not. Thus, > "Hallo" and "hallo" are mapped to "Hallo-" and "hallo-", however, > I need uppercase Latin letters being encoded, too, and the > encoding must contain only lowercase Latin letters, numbers, > underscores, and maybe a little bit more. The result should be > more legible than base64, though. > > Has anybody created such a codec already? Okay, the following works fine for me: --8<---------------cut here---------------start------------->8--- import codecs class Codec(codecs.Codec): """Codec class for safe filenames. Safe filenames work on all important filesystems, i.e., they don't contain special or dangerous characters, and they don't assume that filenames are treated case-sensitively. >>> u"hallo".encode("safefilename") 'hallo' >>> u"Hallo".encode("safefilename") '(h)allo' >>> u"MIT Thesis".encode("safefilename") '(mit)_(t)hesis' >>> u"Gesch\\u00e4ftsbrief".encode("safefilename") '(g)esch{e4}ftsbrief' Of course, the mapping works in both directions as expected: >>> "(g)esch{e4}ftsbrief".decode("safefilename") u'Gesch\\xe4ftsbrief' >>> "(mit)_(t)hesis".decode("safefilename") u'MIT Thesis' """ lowercase_letters = "abcdefghijklmnopqrstuvwxyz" safe_characters = lowercase_letters + "0123456789-+!$%&`'@~#.,^" uppercase_letters = lowercase_letters.upper() def encode(self, input, errors='strict'): """Convert Unicode strings to safe filenames.""" output = "" i = 0 input_length = len(input) while i < input_length: c = input[i] if c in self.safe_characters: output += str(c) elif c == " ": output += "_" elif c in self.uppercase_letters: output += "(" while i < input_length and input[i] in self.uppercase_letters: output += str(input[i]).lower() i += 1 output += ")" continue else: output += "{" + hex(ord(c))[2:] + "}" i += 1 return output, input_length def handle_problematic_characters(self, errors, input, start, end, message): if errors == 'ignore': return u"" elif errors == 'replace': return u"?" else: raise UnicodeDecodeError("safefilename", input, start, end, message) def decode(self, input, errors='strict'): """Convert safe filenames to Unicode strings.""" input = str(input) input_length = len(input) output = u"" i = 0 while i < input_length: c = input[i] if c in self.safe_characters: output += c elif c == "_": output += " " elif c == "(": i += 1 while i < input_length and input[i] in self.lowercase_letters: output += input[i].upper() i += 1 if i == input_length: self.handle_problematic_characters(errors, input, i-1, i, "open parenthesis was never closed") continue if input[i] != ')': self.handle_problematic_characters( errors, input, i, i+1, "invalid character '%s' in parentheses sequence" % input[i]) continue elif c == "{": end_position = input.find("}", i) if end_position == -1: end_position = i+1 while end_position < input_length and input[end_position] in "0123456789abcdef" and \ end_position - i <= 8: end_position += 1 output += self.handle_problematic_characters(errors, input, i, end_position, "open backet was never closed") i = end_position continue else: try: output += unichr(int(input[i+1:end_position], 16)) except: output += self.handle_problematic_characters(errors, input, i, end_position+1, "invalid data between brackets") i = end_position else: output += self.handle_problematic_characters(errors, input, i, i+1, "invalid character '%s'" % c) i += 1 return output, input_length class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamReader): pass def _registry(encoding): if encoding == "safefilename": return (Codec().encode, Codec().decode, StreamReader, StreamWriter) else: return None codecs.register(_registry) if __name__ == "__main__": import doctest doctest.testmod() --8<---------------cut here---------------end--------------->8--- -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From ndbecker2 at gmail.com Mon Sep 24 14:13:18 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 24 Sep 2007 14:13:18 -0400 Subject: puzzled about floats Message-ID: from math import modf class nco (object): def __init__ (self, delta): self.delta = delta self.phase = 0.0 def __call__ (self): self.phase += self.delta f,i = modf (self.phase) print modf (self.phase) if (self.phase > 1.0): self.phase -= 1.0 return self.phase n = nco (0.1) for x in xrange (100): print '%.12f' % n() prints out [...] (0.99999999999999978, 0.0) <<< from modf 1.000000000000 << from n() I'm baffled as to why 'print modf (self.phase)' prints out the first value, but the result printed in the 2nd case is different. Without any precision spec on the first print, an approximate float value was printed, but even with %.12f, the second gives exactly 1.000.... From belred at gmail.com Mon Sep 24 20:34:38 2007 From: belred at gmail.com (belred at gmail.com) Date: Tue, 25 Sep 2007 00:34:38 -0000 Subject: ironpython with nosetest Message-ID: <1190680478.800804.207350@o80g2000hse.googlegroups.com> has anyone tried nosetest with ironpython? i installed IPCE-r6, copied the nose directory below the .egg directory from my cpython directory and copied to IPCE-r6/lib. i then created a file called n.py which contained two lines: import nose none.run() i was then able to run it against a test file such as: ipy n.py test_n.py or ipy n.py test_n.py:TestTest.test_f1 it worked as expected. what doesn't work is if i omit the file name and just run ipy n.py, it won't discover any test files. -w (working directory) and -a (attribute) options seem to be ignored. but -s for (don't capture output) and -h (help) does work. thanks, bryan From jstroud at mbi.ucla.edu Thu Sep 6 22:32:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 06 Sep 2007 19:32:37 -0700 Subject: why should I learn python In-Reply-To: <87zlzzs9by.fsf@wilson.homeunix.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> Message-ID: <9L2Ei.1850$Sd4.621@nlpi061.nbdc.sbc.com> Torsten Bronger wrote: > Hall?chen! > > Tom Brown writes: > >> [...] Python has been by far the easiest to develop in. Some >> people might say it is not "real programming" because it is so >> easy. > > I can't believe this. Have you really heard such a statement? > > Tsch?, > Torsten. > Look, a "real" programming language is scheme, not something trivial to understand like (the basics of) python. Scheme is hard to understand and takes a long time to get used to, so its perfect as a learning tool--to make the professors look smarter. This is why its what they teach as an introductory course at MIT. This is also why physicists like RPN calculators. (see (later you)) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Sep 12 18:54:52 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 13 Sep 2007 00:54:52 +0200 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <46E7D82C.40302@web.de> Message-ID: <5kr91sF53m8gU4@mid.individual.net> Stefan Behnel wrote: > Bjoern Schliessmann wrote: >> If this was needless, why do C++ and Java have the "this" >> pointer? > > Be careful when you use the word "needless" in the context of > Java. Umm, why? I didn't introduce it. Regards, Bj?rn -- BOFH excuse #8: static buildup From zentraders at gmail.com Wed Sep 19 10:50:57 2007 From: zentraders at gmail.com (Zentrader) Date: Wed, 19 Sep 2007 07:50:57 -0700 Subject: still get a using a python script in the crontab In-Reply-To: <1190196137.140718.198510@n39g2000hsh.googlegroups.com> References: <1190196137.140718.198510@n39g2000hsh.googlegroups.com> Message-ID: <1190213457.663885.313330@k35g2000prh.googlegroups.com> > If I run the command /usr/sbin/program_prgchk everything works (no > process) > But when I use it in the crontab I get a process The crontabs file on my system is stored in /var/spool/cron/ crontabs/. It appears you are checking the wrong file. Try a "crontab -e" from the command line and compare it to the contents in the /etc/crontab file. From zzbbaadd at aol.com Wed Sep 12 13:43:53 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 12 Sep 2007 10:43:53 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: <1189618530.872819.136450@57g2000hsv.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> Message-ID: <1189619033.968437.286580@g4g2000hsf.googlegroups.com> > > "this" in C++ and Java is not shown in the parameter list, which was > what he was > complaining about. He wants > > class MyClass: > def SomeFunction(someParameter): > self.someParameter = someParameter > > not > > class MyClass: > def SomeFunction(self, someParameter): > self.someParameter = someParameter > > The confusing way about the current Python method when you first > encounter it is > why is "self" being passed in when you write the function but not > when you call it. If the compiler is smart enough to know that > > a = MyClass() > a.SomeFunction(12) > > SomeFunction() has a "self" implicitly added to the parameter list, it > seems that it should be smart enough to know that a function defined > in a class has a "self" implicitly added to the parameter list. In C++ and Java I don't believe "this" is ever referred to as an implicit function parameter. It is a (sometimes necessary) way to reference the object inside one if it's methods. If it is in fact a real parameter in the underlying compiled-code implementation, that knowledge hurts more than it helps. From rampeters at gmail.com Mon Sep 10 14:53:54 2007 From: rampeters at gmail.com (johnny) Date: Mon, 10 Sep 2007 11:53:54 -0700 Subject: noob: reloading modified python file within Python Shell Message-ID: <1189450434.578698.286760@o80g2000hse.googlegroups.com> from people.models import * Now I make changes to the models.py. How do I reload this module in Python Shell? From bignose+hates-spam at benfinney.id.au Sun Sep 30 00:15:09 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 30 Sep 2007 14:15:09 +1000 Subject: Optparse and help formatting? References: Message-ID: <87abr423hu.fsf@benfinney.id.au> Tim Chase writes: > I've been learning the ropes of the optparse module and have been > having some trouble getting the help to format the way I want. A quick perusal of the 'optparse.py' code shows me this: ======== [...] class OptionParser([...]): def __init__([...], formatter=None, [...]): [...] if formatter is None: formatter = IndentedHelpFormatter() [...] ======== So, the OptionParser init method accepts the help formatter as the 'formatter' argument, defaulting to a new instance of IndentedHelpFormatter. Presumably, it's a matter of subclassing 'optparse.HelpFormatter' and overriding the behaviour you want to change, then passing an instance of your new class as the 'formatter' argument to the 'OptionParser()' invocation. -- \ "Members of the general public commonly find copyright rules | `\ implausible, and simply disbelieve them." -- Jessica Litman, | _o__) _Digital Copyright_ | Ben Finney From david at asdf.asdf Sun Sep 9 21:58:54 2007 From: david at asdf.asdf (bambam) Date: Mon, 10 Sep 2007 11:58:54 +1000 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> Message-ID: <13e99756io95p66@corp.supernews.com> I can try that, but I'm not sure that it will work. The problem is that devList is just a pointer to a list owned by someone else. Making devList point to a new list won't work: I need to make the parent list different. I could do this by adding an extra level of indirection, but I think at the risk making the call environment more complex. Still, the main thing is that I hadn't even thought of doing it that way. Thank you, Steve. "Lawrence D'Oliveiro" wrote in message news:fbqo83$8fd$1 at lust.ihug.co.nz... > In message <13dv4uqqb806ff0 at corp.supernews.com>, bambam wrote: > >> The devices are in a list, and are removed by using pop(i). This >> messes up the loop iteration, so it is actually done by setting a >> flag on each device in the exception handler, with ANOTHER >> loop after each write/read/calculate sequence. > > Why not just build a new list? E.g. > > newdevs = [] > for dev in devs : > ... > if not removing_dev : > newdevs.append(dev) > #end if > #end for > devs = newdevs From jstroud at mbi.ucla.edu Fri Sep 14 15:52:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 14 Sep 2007 12:52:52 -0700 Subject: Rename multiple files using names in a text file In-Reply-To: References: Message-ID: r?mi wrote: > Hi, > > I would like to rename files (jpg's ones) using a text file containing the > new names... > Below is the code that doesn't work : > ***** > #!/usr/bin/python > #-*- coding: utf-8 -*- > from os import listdir, getcwd, rename > import re > list_names=['new_name1','new_name2'] > list_files = listdir(getcwd()) > filtre = re.compile("jpg$", re.IGNORECASE) > list_jpg = filter(filtre.search, list_files) > #strip all element of list list_jpg > list_jpg_strip=[] > for nom in list_jpg: > #print nom.strip() > list_jpg_strip.append(nom.strip()) > #let's rename : > i=0 > while i <= len(list_jpg_strip): > rename(list_jpg_strip[i],list_names[i]) > i=i+1 > **** > The error message is : > File "ecm.py", line 17, in > rename(list_jpg_strip[i],list_names[i]) > OSError: [Errno 2] No such file or directory > and all files exists, I checked it hundred times ! :-s > Do you have a clue ? > Thanks a lot. > R?mi. Other than that your strip() is stripping off some whitespace that is part of the name, I really can't see the problem either, but did you try to add in the explicit path? E.g.: path_to = getcwd() list_files = listdir(path_to) . . . for nom in list_jpg: old_path = os.path.join(path_to, nom.strip()) list_jpg_strip.append(old_path) . . . for old_path, new_name in zip(list_jpg_strip, list_names): new_path = os.path.join(path_to, new_name) rename(old_path, new_path) James From zentraders at gmail.com Tue Sep 4 15:10:16 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 04 Sep 2007 12:10:16 -0700 Subject: gucci shoes,LV handbag chanel levi's kobe max In-Reply-To: <1188915977.444157.103850@r29g2000hsg.googlegroups.com> References: <1188915977.444157.103850@r29g2000hsg.googlegroups.com> Message-ID: <1188933016.338377.270610@r29g2000hsg.googlegroups.com> Reported as spam From __peter__ at web.de Sun Sep 2 05:18:00 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 2 Sep 2007 11:18:00 +0200 Subject: localizing a sort References: Message-ID: Am Sat, 01 Sep 2007 18:56:38 -0300 schrieb Ricardo Ar?oz: > Hi, I've been working on sorting out some words. > > My locale is : >>>> import locale >>>> locale.getdefaultlocale() > ('es_AR', 'cp1252') > > I do : >>>> a = '???????????????' >>>> print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y))) > aeiou??????????????? The lambda is superfluous. Just write cmp=locale.strcoll instead. > This is not what I am expecting. I was expecting : > a???e???i???.....etc. > > The reason is that if you want to order some words (say for a dictionary > (paper dict, where you look up words)) this is what happens : >>>> a = 'pal?bra de p?labra de pblabra' >>>> print ' '.join(sorted(a.split(), cmp=lambda x,y: locale.strcoll(x, y))) > de de pal?bra pblabra p?labra > > While any human being would expect : > > de de pal?bra p?labra pblabra > > Does anybody know a way in which I could get the desired output? I suppose it would work on your machine if you set the locale first with >>> locale.setlocale(locale.LC_ALL, "") 'de_DE.UTF-8' I have to resort to a list instead of a string on mine because it uses the UTF-8 encoding where one character may consist of more than one byte. (Providing key is more efficient than cmp.) >>> a = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', 'a', 'e', 'i', 'o', 'u'] >>> print "".join(sorted(a, key=locale.strxfrm)) a???e???i???o???u??? However, to make your program a bit more portable I recommend that you use unicode instead of str: >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'de_DE.UTF-8' >>> encoding = locale.getlocale()[1] >>> def sortkey(s): ... return locale.strxfrm(s.encode(encoding)) ... >>> print "".join(sorted(u"???????????????aeiou", key=sortkey)) a???e???i???o???u??? >>> Peter From ldo at geek-central.gen.new_zealand Mon Sep 10 20:22:32 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Sep 2007 12:22:32 +1200 Subject: /dev/null as a file-like object, or logging to nothing References: <87k5r1jdzq.fsf@wilson.homeunix.com> <5kg48jF33dv5U3@mid.uni-berlin.de> <87fy1pjbpl.fsf@wilson.homeunix.com> Message-ID: In message , Sion Arrowsmith wrote: > Torsten Bronger wrote: >>Marc 'BlackJack' Rintsch writes: > >>> `os.devnull`? > >>Yes, but I wasn't really sure how portable it is, in particular, on >>Windows. > > Windows has a NUL: device which behaves like /dev/null . It's not a device, it's a reserved file name. Or rather, a reserved file name prefix: any attempt to open a file name beginning with NUL, e.g. NUL.DAT, will cause your output to disappear into a black hole. This has bitten Windows users more than once. From pavlovevidence at gmail.com Sat Sep 29 03:26:06 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Sep 2007 03:26:06 -0400 Subject: python 2.5 and 3gb switch References: Message-ID: <46fe0a01$0$7528$4c368faf@roadrunner.com> On Sat, 29 Sep 2007 18:10:22 +1200, neil wrote: > why? An error traceback or any other information might help us understand the problem. Even if you think you know what the issue is--and you didn't seem 100% certain--an example would help other people understand the issue better. > I am asking if any one knows of a 3gb python build. The code runs > successfully in lesser missions it just wont run in the extra memory > available when I try to run it along with my other programs in a 3gb > space. > thanks for your reply though You're probably out of luck. Blender uses a built-in Python interpreter, which means you're stuck with whatever version it uses. If you were to install a different version of Python, Blender wouldn't use it--it would still use it's built-in version. (On Windows, I'm not sure if Blender ships with the Python DLL or if Python is statically linked in. If Blender does ship with the Python DLL, you could try to replace the DLL it ships with with the DLL from a 64-bit build of Python, but it would almost certainly crash Blender because the function signatures would be different. Hell, much lesser changes can cause problems: it is because of Blender that I compile Python in UCS-4 mode.) There is another possibility: perhaps it is a 64-bit version of Python built into Blender, but you need some standard libraries not supplied by Blender. (This is something a traceback might have been able to help us find out.) Does your conversion utility depend on having Python installed? If so, then installing a 64-bit version could help. But, it still behooves you to install the exact same version of Python, preferrably built with the same options. I can't help you there, though; don't run Windows myself. Did you look at the Active State distros? Maybe they have one. And finally, asking on the Blender forums would probably be more helpful. Carl Banks From dariusjack2006 at yahoo.ie Fri Sep 21 07:00:23 2007 From: dariusjack2006 at yahoo.ie (http://members.lycos.co.uk/dariusjack/) Date: Fri, 21 Sep 2007 04:00:23 -0700 Subject: Who can develop the following Python script into working application ? In-Reply-To: <1190334828.210230.293980@50g2000hsm.googlegroups.com> References: <1190334828.210230.293980@50g2000hsm.googlegroups.com> Message-ID: <1190372423.768184.60080@19g2000hsx.googlegroups.com> On Sep 21, 2:33 am, "http://members.lycos.co.uk/dariusjack/" wrote: > Hi, > > I am happy user of Nokia 770 tablett > and one application for Nokia 770 is maemo mapper (beta navigation > application). > And the following script should run under mm (for Debian). > Its developer told me it wans intended for other developers. > I have no idea how to write Python script > so please tell me how to learn how the following script works and how > to modify it to be fully working, > Frankly speaking I would prefer to pay for your kind assistance > as it may take me to much time to learn some Python and understand the > following script. > > I would like to modify it to add 2 more columns to SQL (sqlite3) POI > database, to set proximity value and spead limit as in safety cam POI > in standard car navigation systems. > > Please let me know your opinion. > > Darius > > #!/usr/bin/python2.5 > # > # This library is free software; you can redistribute it and/or > # modify it under the terms of the GNU Lesser General Public > # License as published by the Free Software Foundation; either > # version 2.1 of the License, or (at your option) any later version. > # > # This library is distributed in the hope that it will be useful, > # but WITHOUT ANY WARRANTY; without even the implied warranty of > # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU > # Lesser General Public License for more details. > # > # You should have received a copy of the GNU Lesser General Public > # License along with this library; if not, write to the Free Software > # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA > 02110-1301 USA > > __author__ = "Henri Bergius " > __version__ = "0.0.1" > __date__ = "2007-03-06" > __copyright__ = "Copyright (c) 2007 %s. All rights reserved." % > __author__ > __licence__ = "LGPL" > > import sqlite3 > import dbus > import httplib > import os > from xml.dom.minidom import parseString > > # Start with getting position from GeoClue > bus = dbus.SessionBus() > # TODO: Get the GeoClue interface to use from /schemas/apps/geoclue/ > position/defaultpath > # and /schemas/apps/geoclue/position/defaultserviceGConf keys > proxy_obj = > bus.get_object('org.foinse_project.geoclue.position.hostip', '/org/ > foinse_project/geoclue/position/hostip') > geoclue_iface = dbus.Interface(proxy_obj, > 'org.foinse_project.geoclue.position') > > # Get the coordinates from the service > coordinates = geoclue_iface.current_position() > # We can also use hardcoded > #coordinates[0] = 60.158806494564 > #coordinates[1] = 24.9426341056824 > > print "According to GeoClue you are in %s %s." % (coordinates[0], > coordinates[1]) > > # Make the HTTP request to the Geonames service > print "Pulling local Wikipedia pages from Geonames" > http_connection = httplib.HTTPConnection("ws.geonames.org") > http_connection.request("GET", "/findNearbyWikipedia?lat=%s" % > coordinates[0] + "&lng=%s" % coordinates[1] + "&maxRows=100") > http_response = http_connection.getresponse() > # TODO: Error handling > xml = http_response.read() > > def parse_entries(xml): > dom = parseString(xml) > entries = dom.getElementsByTagName('entry') > results = [] > for entry in entries: > entry_dictionary = {} > entry_dictionary['title'] = entry.getElementsByTagName('title') > [0].firstChild.data > entry_dictionary['summary'] = > entry.getElementsByTagName('summary')[0].firstChild.data + " (source: > Wikipedia)" > > if (entry.getElementsByTagName('feature')[0].firstChild): > entry_dictionary['feature'] = > entry.getElementsByTagName('feature')[0].firstChild.data > > entry_dictionary['lat'] = > float(entry.getElementsByTagName('lat')[0].firstChild.data) > entry_dictionary['lon'] = > float(entry.getElementsByTagName('lng')[0].firstChild.data) > results.append(entry_dictionary) > return results > > entries = parse_entries(xml) > > # Open SQLite connection > #sqlite_connection = sqlite3.connect(os.path.expanduser("~/ > MyDocs/.documents/poi.db")) > sqlite_connection = sqlite3.connect(os.path.expanduser("/home/user/ > MyDocs/.documents/poi.db")) > sqlite_cursor = sqlite_connection.cursor() > for entry in entries: > # Check if the entry is already in database > sql_variables = (entry["title"],) > sqlite_cursor.execute('select poi_id from poi where label=?', > sql_variables) > existing_entry_id = sqlite_cursor.fetchall() > if (existing_entry_id): > print "%s is already in database, skipping" % entry["title"] > # TODO: Update > else: > print "Inserting %s (%s, %s) into POI database" % > (entry["title"], entry["lat"], entry["lon"]) > # TODO: Be smarter about POI categories > sql_variables = (entry["lat"], entry["lon"], entry["title"], > entry["summary"], 10) > sqlite_cursor.execute("insert into poi (lat, lon, label, desc, > cat_id) values (?, ?, ?, ?, ?)", sql_variables) > > sqlite_connection.commit() > sqlite_cursor.close() > sqlite_connection.close() Please help and let me know your terms. Darius From pavlovevidence at gmail.com Mon Sep 17 04:27:51 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Sep 2007 04:27:51 -0400 Subject: Try this References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> Message-ID: <46ee460b$0$19586$4c368faf@roadrunner.com> On Sun, 16 Sep 2007 17:58:09 -0700, mensanator at aol.com wrote: > The very presence of an algorithm to detect encoding is a bug. Files > with they .txt extension should always be treated as ANSI even if they > contain binary data. Notepad should never be allowed to try to decide > what the encoding is if the the open dialog has the encoding set to > ANSI. I'm sure, then, you'll be happy to know that Python 3 will use similar (or maybe not similar) heuristics to determine the encoding of text files. At least that was the case last time I checked. FWIW, I'm not a big fan of heuristics, either (and this behavior would seriously irk me on Linux, where, unlike in Windows, there is an occasional need to create files containing only a small ascii string). But sometimes heuristics are necessary. There's too many non-ascii text files floating around out there for Microsoft to do nothing; they have clients in many countries they have to please. Carl Banks From jwrweatherley at gmail.com Sun Sep 2 09:45:16 2007 From: jwrweatherley at gmail.com (jwrweatherley at gmail.com) Date: Sun, 02 Sep 2007 06:45:16 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <1188735642.391419.103650@19g2000hsx.googlegroups.com> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> Message-ID: <1188740716.423349.304370@y42g2000hsy.googlegroups.com> [snip code] Thanks for that. I realise that improving the algorithm will speed things up. I wanted to know why my less than perfect algorithm was so much slower in python than exactly the same algorithm in C. Even when turning off gcc's optimiser with the -O0 flag, the C version is still > 100 times quicker. From mccredie at gmail.com Wed Sep 26 13:00:47 2007 From: mccredie at gmail.com (Matimus) Date: Wed, 26 Sep 2007 17:00:47 -0000 Subject: Python class method as an argument of a function in a C extension In-Reply-To: <1190794562.037602.317840@22g2000hsm.googlegroups.com> References: <1190794562.037602.317840@22g2000hsm.googlegroups.com> Message-ID: <1190826047.552990.47310@n39g2000hsh.googlegroups.com> > Can anybody give me an hint (or some link) on how to define > 'aCFunction' and how to call 'self.myMethod' in the C source code? A python function defined in C accepts a pointer to self and a tuple of arguments, each of which is also a PyObject. If you pass a function or method, it will be included in the tuple of arguments. I don't think there is any difference between passing a method and a function. You can call that method using functions in the `Object Protocol' section of the API, such as PyObject_Call(...). Here is an example from the Python documentation: http://docs.python.org/ext/callingPython.html The first part shows how to get a function as an argument. The following bits of code show how to actually call that function.The example uses PyEval_CallObject, which I can't find documentation to. I'm not sure if it even exists (it may be a documentation error). But from the example it seems to work exactly the same as PyObject_CallObject. Matt From bbxx789_05ss at yahoo.com Thu Sep 20 15:28:10 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 20 Sep 2007 12:28:10 -0700 Subject: subprocess: returncode v. poll() In-Reply-To: <1190316312.929039.85670@o80g2000hse.googlegroups.com> References: <1190315820.532320.26570@22g2000hsm.googlegroups.com> <1190316312.929039.85670@o80g2000hse.googlegroups.com> Message-ID: <1190316490.165848.248300@w3g2000hsg.googlegroups.com> On Sep 20, 1:25 pm, 7stud wrote: > On Sep 20, 1:17 pm, 7stud wrote: > > > > > Hi, > > > What is the difference between: > > > 1) getting the returncode directly from the subprocess object > > 2) calling poll() on the subprocess object? > > > Here is an example: > > > import subprocess > > > p = subprocess.Popen("ls", stdout=subprocess.PIPE) > > print p.returncode > > print p.poll() > > print > > > print p.stdout.read()[:5] > > print > > > print p.returncode > > print p.poll() > > print p.returncode > > > --output:-- > > None > > None > > > 10tes > > > None > > 0 > > 0 > > Hmm....after a little more testing, I don't think returncode > dynamically updates: > > import subprocess > import time > > p = subprocess.Popen("ls", stdout=subprocess.PIPE) > > print p.returncode > time.sleep(5) > print p.returncode > time.sleep(2) > print p.returncode > > print p.stdout.read()[:5] > print p.returncode > > --output:-- > None > None > None > 10tes > None ...but then when is p.returncode set? And what good is it? From duncan.booth at invalid.invalid Thu Sep 27 03:32:03 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Sep 2007 07:32:03 GMT Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <1190805297.182232.116830@50g2000hsm.googlegroups.com> <1190815180.945099.248670@n39g2000hsh.googlegroups.com> <1190816657.574437.80980@g4g2000hsf.googlegroups.com> <1190820026.299569.110250@n39g2000hsh.googlegroups.com> <1190846656.770087.173230@19g2000hsx.googlegroups.com> Message-ID: Paul Hankin wrote: >> A key which is in dict must be either in __keycache or in __addkeys, but >> never in both. > > Yes, I'm sorry: you're right. > > But there's a different bug: if you delete a key that's not in the > dict, you'll add it to the deleted list before the exception for the > missing key is raised. > > sd = sorteddict.sorteddict() > sd['a'] = 'a' > print sd.keys() = ['a'] > try: > del sd['b'] > except: > pass > sd['b'] = 'b' > print sd.keys() > > The second print statement produces ['a'] rather than ['a', 'b'] Yes, I think there are probably several cases where I need to account for exceptions. There's another serious problem: if Mark wants this module to be used and stand any chance at all of eventually being incorporated into the standard library, then he will have to change the license on his code: the GPL simply isn't an option here. From paul at boddie.org.uk Thu Sep 20 05:24:36 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 20 Sep 2007 02:24:36 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <1190242799.954176.279440@22g2000hsm.googlegroups.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> <1190241711.344058.238380@57g2000hsv.googlegroups.com> <1190242799.954176.279440@22g2000hsm.googlegroups.com> Message-ID: <1190280276.340286.240300@r29g2000hsg.googlegroups.com> On 20 Sep, 00:59, TheFlyingDutchman wrote: > > Paul it's a pleasure to see that you are not entirely against > complaints. Well, it seems to me that I'm usually the one making them. ;-) > The very fastest Intel processor of the last 1990's that I found came > out in October 1999 and had a speed around 783Mhz. Current fastest > processors are something like 3.74 Ghz, with larger caches. True, although you're paying silly money for a 3.8 GHz CPU with a reasonable cache. However, as always, you can get something not too far off for a reasonable sum. When I bought my CPU two or so years ago, there was a substantial premium for as little as 200 MHz over the 3.0 GHz CPU I went for, and likewise a 3.4 GHz CPU seems to be had for a reasonable price these days in comparison to the unit with an extra 400 MHz. Returning to the subject under discussion, though, one big difference between then and now is the availability of dual core CPUs, and these seem to be fairly competitive on price with single cores, although the frequencies of each core are lower and you have to decide whether you believe the AMD marketing numbers: is a dual 2.2 GHz core CPU "4200+" or not, for example? One can argue whether it's better to have two cores, especially for certain kinds of applications (and CPython, naturally), but if I were compiling lots of stuff, the ability to do a "make -j2" and have a decent speed-up would almost certainly push me in the direction of multicore units, especially if the CPU consumed less power. And if anyone thinks all this parallelism is just hypothetical, they should take a look at distcc to see a fairly clear roadmap for certain kinds of workloads. > Memory is also faster and larger. It appears that someone running a non-GIL > implementation of CPython today would have significantly faster > performance than a GIL CPython implementation of the late 1990's. > Correct me if I am wrong, but it seems that saying non-GIL CPython is > too slow, while once valid, has become invalid due to the increase in > computing power that has taken place. Although others have picked over these arguments, I can see what you're getting at: even if we take a fair proportion of the increase in computing power since the late 1990s, rather than 100% of it, CPython without the GIL would still faster and have more potential for further speed increases in more parallel architectures, rather than running as fast as possible on a "sequential" architecture where not even obscene amounts of money will buy you significantly better performance. But I don't think it's so interesting to consider this situation as merely a case of removing the GIL and using lots of threads. Let us return to the case I referenced above: even across networks, where the communications cost is significantly higher than that of physical memory, distributed compilation can provide a good performance curve. Now I'm not arguing that every computational task can be distributed in such a way, but we can see that some applications of parallelisation are mature, even mainstream. There are also less extreme cases: various network services can be scaled up relatively effectively by employing multiple processes, as is the UNIX way; some kinds of computation can be done in separate processes and the results collected later on - we do this with relational databases all the time. So, we already know that monolithic multithreaded processes are not the only answer. (Java put an emphasis on extensive multithreading and sandboxing because of the requirements of running different people's code side-by-side on embedded platforms with relatively few operating system conveniences, as well as on Microsoft Windows, of course.) If the programmer cost in removing the GIL and maintaining a GIL-free CPython ecosystem is too great, then perhaps it is less expensive to employ other, already well-understood mechanisms instead. Of course, there's no "global programmer lock", so everyone interested in doing something about removing the GIL, writing their own Python implementation, or whatever they see to be the solution can freely do so without waiting for someone else to get round to it. Like those more readily parallelisable applications mentioned above, more stuff can get done provided that everyone doesn't decide to join the same project. A lesson from the real world, indeed. Paul From BjornSteinarFjeldPettersen at gmail.com Thu Sep 20 02:18:01 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Thu, 20 Sep 2007 06:18:01 -0000 Subject: Mixin classes and single/multiple inheritance In-Reply-To: <87myviuee5.fsf@benfinney.id.au> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> <877immvye0.fsf_-_@benfinney.id.au> <1190257864.945639.199230@k79g2000hse.googlegroups.com> <87y7f2uhpp.fsf@benfinney.id.au> <1190262607.684957.49610@57g2000hsv.googlegroups.com> <87myviuee5.fsf@benfinney.id.au> Message-ID: <1190269081.359324.57300@k79g2000hse.googlegroups.com> On Sep 20, 6:52 am, Ben Finney wrote: > Michele Simionato writes: > > Since the language we have does have multiple inheritance, let's > > use it to implement mixins. > > ... > > So, multiple inheritance is giving us very little for the point of > > view of mixins; OTOH, multiple inheritance is giving us a lot of > > headaches for what concerns cooperative methods. > > I may be obtuse, but the above statements seem to be professing > contradictory viewpoints. How so? A language doesn't need MI to have mixins (e.g. Ruby does this). This doesn't seem to contradict that MI is, in general, a horrible solution to most problems -- one example being the general difficulty in groking cooperative (super) methods. A single- inheritance language, otoh, is also a chore to work with (for a specific subset of designs) -- unless there is _some_ way to do mixins. But for the general case I agree with Micele that delegation is the better solution (Explicit is better than implicit). > Do you think multiple inheritance should or should not be used in > Python to do what mixins do? Michele already answered this, Python has MI so it would just be confusing to implement mixins any other way. > > My point was that even if Python had been implemented without > > multiple inheritance, it would have been simple to implement mixins, > > or by copying the methods, or by dispatching with __getattr__. > > Can you give a code example of how you think mixins should be > implemented in Python, assuming the absence of multiple inheritance? Googling for "Ruby mixins tutorial" gave me the following link: http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/ If I tell you that self.something is written @something in Ruby, and inheritance is written class Base < Parent (as opposed to class Base(Parent):) everything else should be understandable..? How to implement include and extend in Python is left as an excercise for the reader. -- bjorn From marcobonifazi at gmail.com Thu Sep 20 05:18:25 2007 From: marcobonifazi at gmail.com (Marco Bonifazi) Date: Thu, 20 Sep 2007 02:18:25 -0700 Subject: Python and RTF In-Reply-To: <1190271676.160077.99270@w3g2000hsg.googlegroups.com> References: <1190271676.160077.99270@w3g2000hsg.googlegroups.com> Message-ID: <1190279905.435511.219510@r29g2000hsg.googlegroups.com> On 20 Set, 09:01, Rufman wrote: > Does anyone have a good rtf library for python, have exprience with > pyRTF or a link to a good tutorial? > > thx Stephane I have just used PyRtf to create a "report" with table and simple images. What is your question? Marco Bonifazi http://www.bonifazi.eu From laurent.pointal at wanadoo.fr Mon Sep 3 17:04:32 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Mon, 03 Sep 2007 23:04:32 +0200 Subject: Python object <-> XML References: <1188849714.128121.139450@r34g2000hsd.googlegroups.com> Message-ID: <46dc76e6$0$27389$ba4acef3@news.orange.fr> Samuel wrote: > Hi, > > Say you have the following XML: > > > item 1 > > > item 2 > > > > > my group > > > Is there an easy way (i.e. without writing a sax/dom parser) to load > this into a (number of) Python object(s), manipulate the instance, and > save the result back to XML? > > -Samuel I dont know if this suit your needs: http://uche.ogbuji.net/tech/4suite/amara/ Take a look at the Amara Bindery: http://uche.ogbuji.net/tech/4suite/etc/amara-manual.html#bindery A+ Laurent. From vijayeee at gmail.com Tue Sep 4 09:42:09 2007 From: vijayeee at gmail.com (vijayca) Date: Tue, 04 Sep 2007 13:42:09 -0000 Subject: Tkinter(2) Message-ID: <1188913329.457394.94220@g4g2000hsf.googlegroups.com> my python installation is:Active python 2.5.1 i am using Red Hat Linux i have the Tkinter module installed but any simple script produces an error.... script: from Tkinter import Label widget = Label(None, text='Hello GUI world!') widget.pack() widget.mainloop() error: Traceback (most recent call last): File "guy.py", line 2, in widget = Label(None, text='Hello GUI world!') File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 2464, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1923, in __init__ BaseWidget._setup(self, master, cnf) File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1898, in _setup _default_root = Tk() File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1636, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable please help me.... i hate those error messages... vijay From m.n.summerfield at googlemail.com Tue Sep 25 06:24:15 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Tue, 25 Sep 2007 10:24:15 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> Message-ID: <1190715855.858519.30540@50g2000hsm.googlegroups.com> On 25 Sep, 10:53, "A.T.Hofkamp" wrote: > On 2007-09-25, Mark Summerfield wrote: > > > If there is positive feedback I will submit the PEP to the reviewers, > > so if you think it is a good idea please say so. (I'm sure that if you > > _don't_ like it you'll tell me anyway:-) > > I like the idea, ie +1. > > > This PEP proposes the addition of a sorted dictionary class to the > > standard library's collections module. > > You don't seem to mention the sort criterium. I'd suggest to use the __lt__ > operator, which you probably intended since it is commonly used. You are right that I implicitly use __lt__ (or __cmp__ if there's no __lt__). > Also, can I specify a custom sort function, as with list.sort() ? No. That would make comparing two sorteddicts problematic. You can always use munged string keys as my second example shows. > > In addition, the keys() method has two optional arguments: > > > keys(firstindex : int = None, secondindex : int = None) -> list of > > Not sure this is a good idea. Wouldn't simply > > mysorteddict.keys()[firstindex:secondindex] > > be much better? It can do all you propose, and more (with iterators/generators > and such). I see no need to implement it inside the sorteddict as well. The reason for making it part of th > > Since the sorteddict's data is always kept in key order, indexes > > (integer offsets) into the sorteddict make sense. Five additional > > methods are proposed to take advantage of this: > > > key(index : int) -> value > > > item(index : int) -> (key, value) > > > value(index : int) -> key > > > set_value(index : int, value) > > > delete(index : int) > > I wouldn't do this. It breaks compability with the normal dict. A beginning > user will expect dict and sorteddict to behave the same (except for > sortedness), including their set of supporting functions imho. > > Otherwise, please make a case for them (and maybe even a new PEP to get them in > both types of dicts). > > > Examples > > > To keep a collection of filenames on a case-insensitive file > > system in > > sorted order, we could use code like this: > > > files = collections.sorteddict.sorteddict() > > for name in os.listdir("."): > > files[name.lower()] = name > > The more interesting case would be to you preserve case of the files within the > keys. > > I usually need this data structure with an A* algorithm implementation, where I > need to obtain the cheapest solution found so far. > > > for item in listOfItems: > > itemsByDate["%s\t%17X" % (item.date, id(item))] = item > > itemsByName["%s\t%17X" % (item.name, id(item))] = item > > itemsBySize["%s\t%17X" % (item.size, id(item))] = item > > Wouldn't a line like "itemsBySize[(item.size, id(item))] = item" do as well? > > (or with a custom sort function on items?) > > > Now we can iterate in date or name order, for example: > > > for item in itemsByDate: > > print item.name, item.date > > Hmm, not with dict: > > >>> for x in {1:10, 2:20}: > > ... print x > ... > 1 > 2 > > So you should get your "%s\t%17X" strings here. > > Sincerely, > Albert From zentraders at gmail.com Sat Sep 29 15:38:09 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 29 Sep 2007 19:38:09 -0000 Subject: question about for cycle In-Reply-To: <1191079144.724699.250470@o80g2000hse.googlegroups.com> References: <1191073123.459709.98870@g4g2000hsf.googlegroups.com> <1191079144.724699.250470@o80g2000hse.googlegroups.com> Message-ID: <1191094689.726813.235340@50g2000hsm.googlegroups.com> On Sep 29, 8:19 am, George Sakkis wrote: > On Sep 29, 10:34 am, "fdu.xia... at gmail.com" > wrote: > > > > > tokl... at gmail.com wrote: > > > > On 29 sep, 12:04, "fdu.xia... at gmail.com" wrote: > > > >> for i in generator_a: # the first "for" cycle > > >> for j in generator_b: > > >> if something_happen: > > >> # do something here ..., I want the outer cycle to break > > >> break > > > > Do you like this? > > > > generator_ab = ((x, y) for x in generator_a for y in generator_b) > > > for i, j in generator_ab: > > > if condition: > > > # do something > > > break > > > In this case, the tuple generator_ab must be generated first. > George You can get specific break points by expanding the for loop into a while loop, and this is perhaps why it has never been implemented with for loops. ctr_a=0 ctr_b=0 while ctr_a < len(generator_a): this_el_a = generator_a[ctr_a] while ctr_b < len(generator_b): this_el_b = generator_b[ctr_ b] if something_happen: ctr_b = len(generator_b) ## break this loop if something_else: ctr_a = len(generator_a) ## break outer while loop ctr_b += 1 ctr_a += 1 From scottishguy at gmail.com Tue Sep 11 08:17:55 2007 From: scottishguy at gmail.com (scottishguy) Date: Tue, 11 Sep 2007 12:17:55 -0000 Subject: Mac OSX sqlite problem. Missing? In-Reply-To: <1189489594.584753.312330@g4g2000hsf.googlegroups.com> References: <1189455305.994439.107100@r34g2000hsd.googlegroups.com> <5klocbF498ruU1@mid.uni-berlin.de> <1189457469.285055.212670@r29g2000hsg.googlegroups.com> <1189489594.584753.312330@g4g2000hsf.googlegroups.com> Message-ID: <1189513075.665508.245570@50g2000hsm.googlegroups.com> On Sep 11, 2:46 am, "attn.steven.... at gmail.com" wrote: > On Sep 10, 1:51 pm, ricardo.turp... at gmail.com wrote: > > > > > Diez B. Roggisch wrote: > > > > Are you by any chance using the python 2.3 when issuing that import > > > statement? > > > > Diez > > > Unfortunately not :( > > > ibook:~/project1$ python -V > > Python 2.5 > > ibook:~/project1$ python > > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) > > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > > Type "help", "copyright", "credits" or "license" for more information.>>> import sqlite > > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: No module named sqlite > > Isn't it sqlite3 (instead of sqlite)? > > Python 2.5.1c1 (r251c1:54692, Apr 17 2007, 21:12:16) > [GCC 4.0.0 (Apple Computer, Inc. build 5026)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> import sqlite3 > >>> sqlite3.Connection > > >>> sqlite3.Connection.__doc__ > > 'SQLite database connection object.' > > > > I also see it under that name in the repository: > > http://svn.python.org/view/python/trunk/Lib/sqlite3/ > > -- > Hope this helps, > Steven The problem is that the user is trying to install the turbogears framework, and 'tg-admin' tries to import sqlite (not sqlite3) He's getting this error: 'import sqlite. ImportError: No module named sqlite'. Without changing the turbogears code, what should he do? Set up a symbolic link from 'sqlite3' to 'sqlite' ? From cjw at sympatico.ca Fri Sep 28 16:55:20 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 28 Sep 2007 16:55:20 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <46FD40A5.8030504@holdenweb.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> <1190997769.002795.59450@57g2000hsv.googlegroups.com> <5m4qc2Fbbk19U1@mid.uni-berlin.de> <1191000394.828693.285210@k79g2000hse.googlegroups.com> <46FD40A5.8030504@holdenweb.com> Message-ID: <46FD6A38.5070606@sympatico.ca> Steve Holden wrote: > TheFlyingDutchman wrote: >> On Sep 28, 10:01 am, Marc 'BlackJack' Rintsch wrote: >>> On Fri, 28 Sep 2007 09:42:49 -0700, TheFlyingDutchman wrote: >>>> Which of the common languages have higher order functions and what is >>>> the syntax? >>> C, C++, Pascal, Perl, PHP, Ruby have them. And of course the functional >>> languages, most notably Lisp and Scheme as you asked for common languages. >>> >>> Don't know if C#'s delegates qualify. >>> >>> Ciao, >>> Marc 'BlackJack' Rintsch >> What is the syntax of a higher order function in C, C++ and Pascal? >> > This is like listening to a four-year-old torment its parents with > incessant questions. Do you *have* to ask every question that pops into > your mind? > > regards > Steve Tut Tut! A reasonable question is being asked. Colin W. From bj_666 at gmx.net Wed Sep 12 03:33:52 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Sep 2007 07:33:52 GMT Subject: Python Problem References: Message-ID: <5kpj30F4s6gmU1@mid.uni-berlin.de> On Wed, 12 Sep 2007 09:09:02 +0200, A.T.Hofkamp wrote: > On 2007-09-11, Wiseman wrote: >> >> Hi, >> >> OK - it works in WindowsXP. >> I installed "enchant" on my SuSE 10.0 (using YAST). >> The enchant Suse package looks like a general Linux package, not a >> Python specific. > > You'd seem to be right judging by this web-page: > http://www.novell.com/products/linuxpackages/suselinux/enchant.html > > As you can see, there is no file installed at a path with "python" in it. > >> What am I missing? > > Python bindings to the library perhaps? > You may be more lucky with an enchant-dev package (if it exists). I am however > not a Suse user and not an echant user (well, not from my Python code at least). PyEnchant seems to be an independent project: http://pyenchant.sourceforge.net/ So there is either an extra package for SuSE or the OP has to build it himself. Ciao, Marc 'BlackJack' Rintsch From fukazawa at gmail.com Tue Sep 25 23:11:43 2007 From: fukazawa at gmail.com (Andy) Date: Wed, 26 Sep 2007 03:11:43 -0000 Subject: stopping a while True: with the keyboard In-Reply-To: References: <1190774898.348656.190760@y42g2000hsy.googlegroups.com> Message-ID: <1190776303.793648.292610@d55g2000hsg.googlegroups.com> Hi, I think you can use the 'curses' module to catch the keyboard event. The name of the method is 'keyname()'. But I'm afraid curses is not available on Windows Python, so you may have to be a bit more imaginative. I just tried with Python 2.4 on Windows XP. To leave the while loop, use the 'break' command. Andy From deets at nospam.web.de Tue Sep 25 07:19:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Sep 2007 13:19:07 +0200 Subject: What is a good way of having several versions of a python module installed in parallell? References: Message-ID: <5ls95aF9pq3gU1@mid.uni-berlin.de> Joel Hedlund wrote: > Hi! > > I write, use and reuse a lot of small python programs for variuos purposes > in my work. These use a growing number of utility modules that I'm > continuously developing and adding to as new functionality is needed. > Sometimes I discover earlier design mistakes in these modules, and rather > than keeping old garbage I often rewrite the parts that are > unsatisfactory. This often breaks backwards compatibility, and since I > don't feel like updating all the code that relies on the old (functional > but flawed) modules, I'm left with a hack library that depends on halting > versions of my utility modules. The way I do it now is that I update the > programs as needed when I need them, but this approach makes me feel a bit > queasy. It seems to me like I'm thinking about this in the wrong way. > > Does anyone else recognize this situation in general? How do you handle > it? > > I have a feeling it should be possible to have multiple versions of the > modules installed simultaneously, and maybe do something like this: > > mymodule/ > + mymodule-1.1.3/ > + mymodule-1.1.0/ > + mymodule-0.9.5/ > - __init__.py > > and having some kind of magic in __init__.py that let's the programmer > choose version after import: > > import mymodule > mymodule.require_version("1.1.3") > > Is this a good way of thinking about it? What would be an efficient way of > implementing it? Use setuptools. It can exactly do that - install different versions parallel as eggs, and with a pre-import require-statment you require the desired one. Diez From redtiger84 at googlemail.com Wed Sep 12 05:27:39 2007 From: redtiger84 at googlemail.com (Christoph Krammer) Date: Wed, 12 Sep 2007 09:27:39 -0000 Subject: MemoryError on reading mbox file Message-ID: <1189589259.662667.149730@w3g2000hsg.googlegroups.com> Hello everybody, I have to convert a huge mbox file (~1.5G) to MySQL. I tried with the following simple code: for m in mailbox.mbox(fileName): msg = m.as_string(True) hash = md5.new(msg).hexdigest() try: dbcurs.execute("""INSERT INTO archive (hash, msg) VALUES (%s, %s)""", (hash, msg)) except MySQLdb.OperationalError, err: print "%s Error (%d): %s" % (file, err[0], err[1]) else: print "%s: Message successfully added to database" % (hash, spamSource) The problem seems to be the size of file, every time I try to execute the script, after about 20000 messages, the following error occurs: Traceback (most recent call last): File "email_to_mysql_mbox.py", line 21, in for m in mailbox.mbox(fileName): File "/usr/lib/python2.5/mailbox.py", line 98, in itervalues value = self[key] File "/usr/lib/python2.5/mailbox.py", line 70, in __getitem__ return self.get_message(key) File "/usr/lib/python2.5/mailbox.py", line 633, in get_message string = self._file.read(stop - self._file.tell()) MemoryError My system has 512M RAM and 768M swap, which seems to run out at an early stage of this. Is there a way to clean up memory for messages already processed? Thanks and regards, Christoph From shankarjee at gmail.com Thu Sep 13 09:28:27 2007 From: shankarjee at gmail.com (Shankarjee Krishnamoorthi) Date: Thu, 13 Sep 2007 08:28:27 -0500 Subject: File Parsing Question In-Reply-To: References: <1189634861.631219.143310@57g2000hsv.googlegroups.com> <13ehmjf33b3d029@corp.supernews.com> Message-ID: Great. That worked for me. I had some of my routines implemented in Perl earlier. Now that I started using Python I am trying to do all my automation scripts with Python. Thanks a ton Jee On 9/13/07, Peter Otten <__peter__ at web.de> wrote: > Dennis Lee Bieber wrote: > > > for line in inp: > > > > will read one line at a time (I'm fairly sure the iterator doesn't > > attempt to buffer multiple lines behind the scenes) > > You are wrong: > > >>> open("tmp.txt", "w").writelines("%s\n" % (9*c) for c in "ABCDE") > >>> instream = open("tmp.txt") > >>> for line in instream: > ... print instream.tell(), line.strip() > ... > 50 AAAAAAAAA > 50 BBBBBBBBB > 50 CCCCCCCCC > 50 DDDDDDDDD > 50 EEEEEEEEE > >>> > > Here's the workaround: > > >>> instream = open("tmp.txt") > >>> for line in iter(instream.readline, ""): > ... print instream.tell(), line.strip() > ... > 10 AAAAAAAAA > 20 BBBBBBBBB > 30 CCCCCCCCC > 40 DDDDDDDDD > 50 EEEEEEEEE > >>> > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From bronger at physik.rwth-aachen.de Wed Sep 5 19:36:36 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 06 Sep 2007 01:36:36 +0200 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? References: <46DEFD2E.5050205@sbcglobal.net> <87tzq898e2.fsf@wilson.homeunix.com> Message-ID: <87ejhc8z23.fsf@wilson.homeunix.com> Hall?chen! Ferenczi Viktor writes: > [...] > > Properties are very useful, since ordinary attribute access can be > transparently replaced with properties if the developer needs to > add code when it's set or needs to calculate it's value whenever > it is read. I totally agree. I like to use properties. However, Python already has properties. Their syntax is quite nice in my opinion, and rather explicit, too. Their only flaw is that they are not "virtual" (in C++ speak). In other words, you can't pass a "self" parameter to them. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From __peter__ at web.de Wed Sep 19 03:54:38 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2007 09:54:38 +0200 Subject: Help, I'm going mad with this References: <1190173561.822713.200070@d55g2000hsg.googlegroups.com> Message-ID: azrael wrote: > Help, I'm going mad with this Is "Otsu threshold algorithm" to boring as a subject? > Meanwhile I tried about 5 different implementations of the otsu > threshold algorithm. I'll go mad. > Please help me. I don't know what to do. I even tried to implement it > from c and java, but no way. nothing. > I've been reading about 5 ppt presentations and 4 pdf's and I failed. > Can someone look at this code. > If needed I can paste 3 other codes. Hmm, you just learned that quality is more important than quantity then. Choose the text that seems most accessible while still complete and try to understand it. > if __name__=="__main__": > otsu(histogram) You are using a parameter before defining it. It seems you have not yet groked the basics of cut and past then. > histogram= [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, 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, 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, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 2, 1, 2, 0, 1, 3, 3, 3, 3, 1, 3, > 1, 3, 5, 2, 3, 3, 3, 6, 3, 4, 5, 4, 9, 6, 11, 6, 10, 3, 11, 9, 9, 12, > 22, 18, 34, 22, 28, 32, 25, 34, 38, 34, 54, 65, 106, 160, 167, 203, > 282, 364, 446, 637, 816, 1022, 1264, 1456, 1646, 1753, 1845, 1922, > 2203, 2231, 1973, 2245, 2369, 2349, 2258, 2130, 2066, 1835, 1640, > 1554, 1414, 1179, 1024, 974, 938, 838, 785, 756, 803, 921, 952, 865, > 722, 625, 608, 547, 498, 412, 438, 408, 413, 415, 339, 366, 330, 320, > 293, 315, 368, 411, 434, 500, 531, 538, 552, 665, 811, 869, 998, 1021, > 1075, 1080, 1030, 934, 926, 1074, 942, 941, 1014, 1440, 2966, 5301, > 2729, 3400, 5563, 13096, 9068, 6045, 2813, 686, 180] > > > Well, this list is a example list that i have exported. for this list > the result the threshold should be at 218. If you need the result and don't want to bother with understanding the algorithm -- I found an implementation in C via Google Codesearch http://www.google.com/codesearch?hl=de&q=+otsu+threshold+show:3rXPo8eEzw0:z-1MzowD-bQ:cDGSVzqKA7M&sa=N&cd=1&ct=rc&cs_p=http://www.studio-to-go.co.uk/source-packages/2.x/gocr-0.41.tar.bz2&cs_f=gocr-0.41/src/otsu.c#a0 It gives the desired result if you use the line that is commented out // orig: sb ... instead of its current replacement. Translation to Python should be straightforward, but you can ask on c.l.py if you run into problems. Peter From ldo at geek-central.gen.new_zealand Sun Sep 9 22:58:02 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 10 Sep 2007 14:58:02 +1200 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> <7xhcm4pl5m.fsf@ruckus.brouhaha.com> <7xsl5ndau8.fsf@ruckus.brouhaha.com> Message-ID: In message <7xsl5ndau8.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Lawrence D'Oliveiro writes: >> > ... and it's to NSA's credit that SHA-1 held up for as long as it did. >> But they have no convincing proposal for a successor. That means the gap >> between the classified and non-classified state of the art has shrunk >> down to insignificance. > > The successor is SHA-2. According to this , the family of algorithms collectively described as "SHA-2" is by no means a definitive successor to SHA-1. From andre.roberge at gmail.com Fri Sep 7 08:31:22 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Fri, 07 Sep 2007 12:31:22 -0000 Subject: Is a Borg rebellion possible? (a metaclass question) Message-ID: <1189168282.665210.260840@19g2000hsx.googlegroups.com> In my application, I make use of the Borg idiom, invented by Alex Martelli. class Borg(object): '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273 Derive a class form this; all instances of that class will share the same state, provided that they don't override __new__; otherwise, remember to use Borg.__new__ within the overriden class. ''' _shared_state = {} def __new__(cls, *a, **k): obj = object.__new__(cls, *a, **k) obj.__dict__ = cls._shared_state return obj ---- This has worked very well so far, but is starting to impose some unwanted constraints on my program design. What I would like to do is, to put it figuratively, create a Borg rebellion with various splinter groups. In concrete Python terms, I would like to have class MyClass(Borg, ...): ... seven_of_nine = MyClass(...) # part of group "BORG" two_of_nine = MyClass(...) splinter1 = MyClass(..., group='splinter') splinter2 = MyClass(..., group='splinter') and have splinter 1 and splinter2 share the same state, but a different state than the one shared by members of the BORG collective. Any suggestions from the metaclass experts? Andr? From malibuster at gmail.com Wed Sep 5 17:17:40 2007 From: malibuster at gmail.com (malibuster at gmail.com) Date: Wed, 05 Sep 2007 14:17:40 -0700 Subject: Text processing and file creation In-Reply-To: <1189024097.175349.221210@w3g2000hsg.googlegroups.com> References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> <1189024097.175349.221210@w3g2000hsg.googlegroups.com> Message-ID: <1189027060.889829.282510@r34g2000hsd.googlegroups.com> On Sep 5, 1:28 pm, Paddy wrote: > On Sep 5, 5:13 pm, "malibus... at gmail.com" > wrote: > > > I have a text source file of about 20.000 lines.>From this file, I like to write the first 5 lines to a new file. Close > > > that file, grab the next 5 lines write these to a new file... grabbing > > 5 lines and creating new files until processing of all 20.000 lines is > > done. > > Is there an efficient way to do this in Python? > > In advance, thanks for your help. > > If its on unix: use split. > If its your homework: show us what you have so far... > > - Paddy. Paddy, Thanks for making me aware of the (UNIX) split command (split -l 5 inFile.txt), it's short, it's fast, it's beautiful. I am still wondering how to do this efficiently in Python (being kind of new to it... and it's not for homework). -- Martin. I am still wondering how to do this in Python (being new to Python) From jura.grozni at gmail.com Sat Sep 1 18:44:18 2007 From: jura.grozni at gmail.com (azrael) Date: Sat, 01 Sep 2007 22:44:18 -0000 Subject: Pivy problem and some other stuff In-Reply-To: <13df1kmak87mbb@corp.supernews.com> References: <1188501707.593319.23330@m37g2000prh.googlegroups.com> <5jom54Fh543U2@mid.uni-berlin.de> <13df1kmak87mbb@corp.supernews.com> Message-ID: <1188686658.296058.56960@57g2000hsv.googlegroups.com> Look, what I think about is this. I'd like to make a multi dimensional list in which evry single element would represent a function. By looping through the list I would execute the functions. But not only that, it is possible to experiment with recoursions. the return 1 2 and 3 examples are just a examples. Of course that the thing I'm thinking about is a little bit more complex. From daniel.j.larsson at gmail.com Wed Sep 5 10:43:11 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Wed, 5 Sep 2007 16:43:11 +0200 Subject: Checking if elements are empty In-Reply-To: <4866bea60709050736t5f9f6759x4a8b685bc9ad4ec@mail.gmail.com> References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <4866bea60709050736t5f9f6759x4a8b685bc9ad4ec@mail.gmail.com> Message-ID: <2bfa72fa0709050743t66a6a399mdc6cd77b7ea43ee9@mail.gmail.com> On 9/5/07, Chris Mellon wrote: > > On 9/5/07, Steve Holden wrote: > > Doran, Harold wrote: > > > > > > > Is there a way to check if the first element of y is null? > > > > > > > len(y[0]) == 0 > > > > would be the obvious way, assuming "null" means "the null string". > > > > Better spelled as > > if y[0]: Even better spelled as if not y[0]: ;-) -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From garyrob at mac.com Thu Sep 6 11:43:26 2007 From: garyrob at mac.com (Gary Robinson) Date: Thu, 6 Sep 2007 11:43:26 -0400 Subject: getting the current function Message-ID: <20070906114326335905.d48a6c2b@mac.com> Alex Martelli has a cookbook recipe, whoami, for retrieving the name of the current function: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062. It uses sys._getframe(). I'm a little wary about using sys._getframe() because of the underscore prefix and the fact that the python docs say "This function should be used for internal and specialized purposes only." I feel more comfortable using the equivalent functionality in the inspect module. Also, I wanted a way to get access to the current function, not just its name. I came up with: import inspect def thisfunc(n=0): currentFrame = inspect.currentframe() outerFrames = inspect.getouterframes(currentFrame) callingFrame = outerFrames[n + 1][0] callersCallingFrame = outerFrames[n + 2][0] return callersCallingFrame.f_locals[callingFrame.f_code.co_name] The n argument lets you go up the stack to get callers of callers if that's convenient. For instance: def attr(name, value): caller = thisfunc(1) if not hasattr(caller, name): setattr(caller, name, value) def x(): attr('counter', 0) thisfunc().counter += 1 print thisfunc().counter x() x() x() Returns the output 1 2 3 Of course you don't need an attr() function for creating a function attribute, but this way your code won't break if you change the name of the function. I was about to create a cookbook recipe, but decided to ask for some feedback from the community first. Do you see situations where this function wouldn't work right? Also, the python docs warn about storing frame objects due to the possibility of reference cycles being created (http://docs.python.org/lib/inspect-stack.html). But I don't think that's a worry here since thisfunc() stores the references on the stack rather than the heap. But I'm not sure. Obviously, it would be easy to add a try/finally with appropriate del's, but I don't want to do it if it's not necessary. I welcome feedback of any type. Thanks, Gary -- Gary Robinson CTO Emergent Music, LLC garyrob at mac.com 207-942-3463 Company: http://www.goombah.com Blog: http://www.garyrobinson.net From martijn at gamecreators.nl Wed Sep 19 06:02:17 2007 From: martijn at gamecreators.nl (martijn at gamecreators.nl) Date: Wed, 19 Sep 2007 03:02:17 -0700 Subject: still get a using a python script in the crontab Message-ID: <1190196137.140718.198510@n39g2000hsh.googlegroups.com> H! I have made a program that is checking if a program is running or not. If the program is not running then it must start the program again. in the /etc/crontab: * * * * * root /usr/sbin/ program_prgchk in the /usr/sbin/program_prgchk: /usr/local/bin/python /home/reseller/domeinaanvraag/program_prgchk.py in the program_prgchk.py: ---------------------------------------- import string import os import commands def checkifrunning(): line = string.strip(commands.getoutput("ps x -o pid,command | grep program_reseller.py | grep -v 'grep'")) pid = string.split(line,' ')[0] if pid<>'':pid = int(pid) return pid if checkifrunning()=='': os.system('/usr/sbin/program_reseller') # os.wait() # os.waitpid(checkifrunning(),0) os._exit(0) If I run the command /usr/sbin/program_prgchk everything works (no process) But when I use it in the crontab I get a process Thanks for helping, GC-Martijn From wangzq at gmail.com Wed Sep 12 21:45:03 2007 From: wangzq at gmail.com (wangzq) Date: Thu, 13 Sep 2007 01:45:03 -0000 Subject: Get the complete command line as-is In-Reply-To: References: <1189566000.793354.308420@19g2000hsx.googlegroups.com> Message-ID: <1189647903.978946.38350@r29g2000hsg.googlegroups.com> On Sep 12, 3:20 pm, Laurent Pointal wrote: > wangzq a ?crit : > > > Hello, > > > I'm passing command line parameters to my browser, I need to pass the > > complete command line as-is, for example: > > > test.py "abc def" xyz > > > If I use ' '.join(sys.argv[1:]), then the double quotes around "abc > > def" is gone, but I need to pass the complete command line ("abc def" > > xyz) to the browser, how can I do this? > > > I'm on Windows. > > As Windows command-line parsing seem to remove some chars, maybe you can > try to use the GetCommandLine() function from Win32 API (I dont know if > it is available in pywin32 package - you may need to write a wrapper > with ctypes). > > Seehttp://msdn2.microsoft.com/en-us/library/ms683156.aspx > > A+ > > Laurent. Thank you for the tip. It works: import ctypes p = ctypes.windll.kernel32.GetCommandLineA() print ctypes.c_char_p(p).value Now I only need to split the whole command line into 3 parts and get the last one. Thanks for all your input. From gagsl-py2 at yahoo.com.ar Sat Sep 29 22:45:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Sep 2007 23:45:59 -0300 Subject: Command-line does work when scheduled References: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> <1191104269.578536.56470@g4g2000hsf.googlegroups.com> <1191114246.668635.327080@o80g2000hse.googlegroups.com> Message-ID: En Sat, 29 Sep 2007 22:04:06 -0300, Jim escribi?: >> If it works this way, maybe the .py file extension is not correctly >> registered. > > Yes, it works this way. > How do I register the .py extension correctly? From a command line, type: assoc .py You should get: .py=Python.File If you get an error, or another thing like py_auto_file: assoc .py=Python.File Then: ftype Python.File You should get: Python.File=c:\path\to\python.exe "%1" %* If you don't: ftype Python.File=c:\path\to\python.exe "%1" %* The %* at the end is important: if you created the association by using "Open with...", or selecting Python from the list of installed programs, very likely the command says only "%1" - that is, the script being open, but without any additional arguments. Better if you have administrative rights to do this tasks. -- Gabriel Genellina From openopt at ukr.net Sun Sep 2 16:28:26 2007 From: openopt at ukr.net (dmitrey) Date: Sun, 02 Sep 2007 13:28:26 -0700 Subject: howto reload Python module? Message-ID: <1188764906.354022.86370@50g2000hsm.googlegroups.com> my Python module was changed in HDD (hardware disk drive), moreover, changed its location (but still present in sys.path). how can I reload a func "myfunc" from the module? (or howto reload whole module)? Thank you in advance, D. From ricaraoz at gmail.com Sat Sep 1 09:33:42 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Sep 2007 10:33:42 -0300 Subject: list index() (OT) In-Reply-To: References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1cnfd31du01el95u70o8mjn9cb5r5aluiu@4ax.com> <1188631457.050512.103060@y42g2000hsy.googlegroups.com> <46D95EEC.2000603@bigfoot.com> Message-ID: <46D96A36.1050006@bigfoot.com> Steve Holden wrote: > Ricardo Ar?oz wrote: >> Paddy wrote: >>> On Sep 1, 7:57 am, "Hendrik van Rooyen" wrote: >>>> "Richie Hindle" wrote: >>>>> But - the word for someone who posts to the internet with the intention of >>>>> stirring up trouble derives from the word for what fishermen do, not from >>>>> the word for something that lives under a bridge. It derives from "trolling >>>>> for suckers" or "trolling for newbies". >>>> So am I right in asserting that there is a difference in pronunciation >>>> of the noun and the verb? >>>> >>>> He is a Troll - like the excellent frolic example >>>> He likes to Troll - rhymes with roll? >>>> >>>> - Hendrik >>> No difference. A troll is a troll is a troll. >>> >>> :-) >>> >>> - Paddy. >> >> BTW people , the word for what fishermen do is T R A W L and not troll >> (Ha! and I'm not a native English speaker). > > Just read the whole thread, or use a dictionary: in fishing, trolling > and trawling are two different things; the first is done with a net, the > second with a line. > > regards > Steve Damn Wikipedia! It always gets things upside down, specially when I 'read the whole thread' : "Trolling for fish" is a form of angling where lines with hook-rigged lures are dragged behind a boat to entice fish to bite. Compare the term "Trawling for fish," which involves dragging a net behind a boat to catch large numbers of fish. ;c) (Don't mind me. Just trolling...) From richie at entrian.com Thu Sep 13 09:48:46 2007 From: richie at entrian.com (Richie Hindle) Date: Thu, 13 Sep 2007 14:48:46 +0100 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: <46fie3h8j1tbfq4cfuf94gagddvaei714p@4ax.com> [Amer] > Can you or anyone see anything in the posted code that might be the > cause? > #!/usr/bin/python > import cgitb; cgitb.enable(display=0, logdir=".") > import sys > sys.stderr = sys.stdout > print "Content-Type: text/html" > print My guess would be that you don't have cgitb in your server environment, or that you have a bogus one. Rearrange things like this: #!/usr/bin/python print "Content-Type: text/html" print import sys sys.stderr = sys.stdout import cgitb; cgitb.enable(display=0, logdir=".") -- Richie Hindle richie at entrian.com From trekker182 at gmail.com Fri Sep 21 10:44:05 2007 From: trekker182 at gmail.com (Shawn Minisall) Date: Fri, 21 Sep 2007 10:44:05 -0400 Subject: acronym program Message-ID: <46F3D8B5.60908@gmail.com> I'm trying to write a program that gets the first letter of every word of a phrase and prints it on screen. I'm having problems with it. I'm thinking a for loop would be good since I don't know the exact number of words the user is going to enter, but after that I get confused. How do I tell python to just goto the beg of each word in the phrase and include it in the acronym? Am I on the right track? for a in string.split(phrase) acronym = phrase [0] acronym = acronym + 1 thx From jura.grozni at gmail.com Wed Sep 19 07:24:46 2007 From: jura.grozni at gmail.com (azrael) Date: Wed, 19 Sep 2007 11:24:46 -0000 Subject: Help for Otsu implementation from C Message-ID: <1190201086.468348.274850@g4g2000hsf.googlegroups.com> Can somone look at this def otsu(hi): fmax=-1.0 border=len(hi) for i in range(border): if hi[i]!=0:break for j in range(border-1,0-1,-1): if hi[j] != 0:break s = sum([k*hi[k] for k in range(border)]) n = sum(hi) # product(im.size) n1=n2=csum=0.0 for k in range(i,j): n1 += hi[k] n2 = n - n1 csum+= k * hi[k] m1 = csum/ n1 m2 = (s - csum)/n2 sb = n1 * n2 * (m2 - m1) if sb > fmax: fmax = sb V=k+1 print V I try to implement it from C from this location. http://www.google.com/codesearch?hl=de&q=+otsu+threshold+show:3rXPo8eEzw0:z-1MzowD-bQ:cDGSVzqKA7M&sa=N&cd=1&ct=rc&cs_p=http://www.studio-to-go.co.uk/source-packages/2.x/gocr-0.41.tar.bz2&cs_f=gocr-0.41/src/otsu.c#a0 It gives me till now the closest threshold value but still not the exact Testing Histogram given to the function as an atribute is: hi = [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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 2, 1, 2, 0, 1, 3, 3, 3, 3, 1, 3, 1, 3, 5, 2, 3, 3, 3, 6, 3, 4, 5, 4, 9, 6, 11, 6, 10, 3, 11, 9, 9, 12, 22, 18, 34, 22, 28, 32, 25, 34, 38, 34, 54, 65, 106, 160, 167, 203, 282, 364, 446, 637, 816, 1022, 1264, 1456, 1646, 1753, 1845, 1922, 2203, 2231, 1973, 2245, 2369, 2349, 2258, 2130, 2066, 1835, 1640, 1554, 1414, 1179, 1024, 974, 938, 838, 785, 756, 803, 921, 952, 865, 722, 625, 608, 547, 498, 412, 438, 408, 413, 415, 339, 366, 330, 320, 293, 315, 368, 411, 434, 500, 531, 538, 552, 665, 811, 869, 998, 1021, 1075, 1080, 1030, 934, 926, 1074, 942, 941, 1014, 1440, 2966, 5301, 2729, 3400, 5563, 13096, 9068, 6045, 2813, 686, 180] it gives me 221 value but it should give me 218 Thanks in advance From bj_666 at gmx.net Fri Sep 7 09:46:14 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2007 13:46:14 GMT Subject: Class design (information hiding) References: <46e1305e$0$18302$426a74cc@news.free.fr> Message-ID: <5kd316F31i6hU5@mid.uni-berlin.de> On Fri, 07 Sep 2007 15:17:06 +0200, Alexander Eisenhuth wrote: > Bruno Desthuilliers schrieb: > >> Nope. It's either 'interface' (no leading underscore), 'implementation' >> (single leading underscore), 'implementation with some protection >> against accidental overriding' (two leading underscores). > > What do you mean with 'implementation'? What does it express? I guess he meant 'implementation detail', i.e. someone other then the author of the class should not use until he really knows the implementation and that this all might change without notice in the next release. Ciao, Marc 'BlackJack' Rintsch From siona at chiark.greenend.org.uk Wed Sep 19 09:22:22 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 19 Sep 2007 14:22:22 +0100 (BST) Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <876427zhzq.fsf@benfinney.id.au> <13f196qktorgc88@corp.supernews.com> <873axbxl2f.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > If a function is named 'super' and operates on >classes, it's a pretty strong implication that it's about >superclasses. But it doesn't (under normal circumstances) operate on classes. It operates on an *instance*. And what you get back is a (proxy to) a superclass/ancestor of the *instance*. (And in the super(A, B) case, you get a superclass/ancestor of *B*. As has just been said somewhere very near here, what is misleading is the prominence of A, which isn't really the most important class involved.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From robert.rawlins at thinkbluemedia.co.uk Thu Sep 20 05:35:12 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Thu, 20 Sep 2007 10:35:12 +0100 Subject: Killing A Process By PID Message-ID: <00ec01c7fb69$8b2b5840$a18208c0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got some code here which I'm using to kill a process if it freezes. However I have no real way of testing it as I can't force a freeze on my application. So thought I would run the code past you lot to see if anything jumps out as not being quite right. Now, my main application when it starts creates a lock file containing its process ID using the following code: file('/var/lock/Application.lock', 'w').write(str(os.getpid())) Which to be honest appears to run just fine, when I look in that file it always contains the correct process ID, for instance, 3419 or something like that. This application also writes a date stamp to a log file every 10 seconds or so, and it's this date stamp that I use to determine if the application has crashed. def doCheck(): try: f = open('/pblue/new/Logs/Alive.log','r') try: timestamp = f.read() finally: f.close() except Exception, e: logging.error(str(e)) nowdatetime = timestuff.now() filedatetime = timestuff.strptime(timestamp, '%Y-%m-%d %H:%M:%S') if timestuff.RelativeDateTimeDiff(nowdatetime,filedatetime).minutes > 1: killApplication() def killApplication(): pid = file('/var/lock/Application.lock').read().strip() if file('/proc/%s/cmdline' % pid).read().endswith('python'): os.system('kill %s' % pid) Now, this second script is run every minute on the system, the idea is to check that time stamp file, and if it hasn't been updated in the past minute, then kill the process, inittab can then pick it back up and it will be as right as rain again. Now the problem is that I'm unable to test it properly, and from what I've seen so far, when the app does freeze, the process isn't being killed, which leads me to believe something isn't quite right in my second script above. Does anyone spot anything that sticks out? Or perhaps something I could be doing a little better? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From jgardner.jonathangardner.net at gmail.com Thu Sep 13 16:00:22 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Thu, 13 Sep 2007 20:00:22 -0000 Subject: Python Database Apps In-Reply-To: <1189658282.646375.160150@19g2000hsx.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> <1189536987.259907.68650@e34g2000pro.googlegroups.com> <1189608814.932322.301950@22g2000hsm.googlegroups.com> <1189658282.646375.160150@19g2000hsx.googlegroups.com> Message-ID: <1189713622.239555.164720@r29g2000hsg.googlegroups.com> On Sep 12, 9:38 pm, Prateek wrote: > Have you checked out Brainwave?http://www.brainwavelive.com > > We provide a schema-free non-relational database bundled with an app > server which is basically CherryPy with a few enhancements (rich JS > widgets, Cheetah/Clearsilver templates). Free for non-commercial use. > You might want to rethink how you are handling databases. What sets your database apart from hierarchical or object-oriented databases? Do you understand why people prefer relational databases over the other options? There's a reason why SQL has won out over all the other options available. You would do well to understand it rather than trying out things we already know do not work. From kar1107 at gmail.com Tue Sep 18 19:44:58 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 18 Sep 2007 23:44:58 -0000 Subject: How can I know how much to read from a subprocess In-Reply-To: <1190070896.332844.23080@22g2000hsm.googlegroups.com> References: <1190070896.332844.23080@22g2000hsm.googlegroups.com> Message-ID: <1190159098.980853.117290@v23g2000prn.googlegroups.com> On Sep 17, 4:14 pm, spam.n... at gmail.com wrote: > Hello, > > I want to write a terminal program in pygtk. It will run a subprocess, > display everything it writes in its standard output and standard > error, and let the user write text into its standard input. > > The question is, how can I know if the process wrote something to its > output, and how much it wrote? I can't just call read(), since it will > block my process. The solution is not simple. You may try a separate thread to do the reading (so that you can afford to block that single thread). You can also run into other I/O deadlocks with a simple solution (ie if you try to feed the whole stdin before reading any stdout, your stdin feeding can block because the process's stdout is full -- it's a bit confusing but for large stdin/stdout, a deadlock is very much possible). Did you try subprocess.Popen.communicate() ? Under the covers it should take care of th ese deadlock issues. It may read and buffer the whole stdout/stderr, so don't use it if the process generates infinite/ very-large stdout/stderr. If the process you launch needs two way communication, like an ssh/ftp session (where the stdin depends on process's prior stdout), the only viable solution is to simulate a human (e.g. pexpect module) Karthik > > Thanks, > Noam From mensanator at aol.com Mon Sep 17 13:57:55 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 17 Sep 2007 10:57:55 -0700 Subject: Try this In-Reply-To: References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> <1190008502.986300.286280@22g2000hsm.googlegroups.com> Message-ID: <1190051875.433350.150820@50g2000hsm.googlegroups.com> On Sep 17, 6:09 am, Steve Holden wrote: > mensana... at aol.com wrote: > > On Sep 16, 9:27?pm, "Gabriel Genellina" > > wrote: > >> En Sun, 16 Sep 2007 21:58:09 -0300, mensana... at aol.com > [...] > >> What about the rest of the world that don't speak > >> English or even worse, don't use the Latin alpabet? > > > When the rest of the world creates the next > > generation of computers, THEY can chosse the > > defaults. > > Right, because of course US companies have no desire to do business with > the rest of the world. I'm merely pointing out that it is the legacy of the history of information technology that is chauvinistic. That happens to be the way things are, I did not say that's the way they should be. > > I'm not given to ad hominem attacks, but this remark really seems to > indicate that "chauvinistic cretin" might apply to you. _I_ didn't invent ASCII or EBCDIC. Why weren't the European and Chinese languages considered when these were developed 40-50 years ago? Because they were "chauvinistic cretins"? Is that what you think? > You'll be gald > to know you are unlikely to hear from me again. Why? Because I tend to act as a gadfly? To point out that the emperor is, in fact, naked? Because the professional programming community doesn't like their dirty laundry aired in public? > > Your perception of the development of information technology is so > skewed you would be better off knowing nothing. My perception is skewed? Why then, does Unicode even exist? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline From m.n.summerfield at googlemail.com Thu Sep 27 04:26:16 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Thu, 27 Sep 2007 08:26:16 -0000 Subject: sorteddict [was a PEP proposal, but isn't anymore!] In-Reply-To: <1190829592.800804.242260@50g2000hsm.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190829592.800804.242260@50g2000hsm.googlegroups.com> Message-ID: <1190881576.186259.313720@57g2000hsv.googlegroups.com> On 26 Sep, 18:59, Raymond Hettinger wrote: > [Mark Summerfield] > > > Below is a PEP proposal for a sorteddict. It arises out of a > > discussion on this list that began a few weeks ago with the subject of > > "An ordered dictionary for the Python library?" > > It is worth remembering that the long sought after datatype was a dict > that could loop over keys in *insertion* order, not based on some > function of the key itself. > > > If there is positive feedback I will submit the PEP to the reviewers, > > so if you think it is a good idea please say so. > > As one who was submitted many PEPs, I can advise that the quickest way > to irrevocably kill an idea is to submit a PEP to early (we almost > didn't get genexps because the PEP was submitted pre-maturely). > Instead, I advise posting an ASPN recipe so the details can be > hammered-out and a fan club can be grown. > > For this particular idea, I am -1 on inclusion in the standard > library. The PEP focuses mainly on implementation but is weakest in > the rationale section. Its advantages over "for k in sorted(d)" are > miniscule. To be considered for the collections module, there needs > to be compelling use case advantages either in terms of usability or > performance. [snip] I gave up on the idea of submitting it as a PEP many postings ago:-) I've now changed the subject line to reflect that. I will leave the pure python sorteddict on PyPI for anyone who wants it. I won't put it on the cookbook site for the time being, simply because it is eating up much more time than I thought! From andre.roberge at gmail.com Fri Sep 7 11:54:38 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Fri, 07 Sep 2007 15:54:38 -0000 Subject: Is a Borg rebellion possible? (a metaclass question) In-Reply-To: References: <1189168282.665210.260840@19g2000hsx.googlegroups.com> Message-ID: <1189180478.257790.60160@g4g2000hsf.googlegroups.com> On Sep 7, 10:27 am, Carsten Haese wrote: > On Fri, 2007-09-07 at 12:31 +0000, Andr? wrote: > > In my application, I make use of the Borg idiom, invented by Alex > > Martelli. > > > class Borg(object): > > '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273 > > > Derive a class form this; all instances of that class will share > > the > > same state, provided that they don't override __new__; otherwise, > > remember to use Borg.__new__ within the overriden class. > > ''' > > _shared_state = {} > > def __new__(cls, *a, **k): > > obj = object.__new__(cls, *a, **k) > > obj.__dict__ = cls._shared_state > > return obj > > > ---- > > This has worked very well so far, but is starting to impose some > > unwanted constraints on my program design. > > > What I would like to do is, to put it figuratively, create a Borg > > rebellion with various splinter groups. In concrete Python terms, I > > would like to have > > > class MyClass(Borg, ...): > > ... > > > seven_of_nine = MyClass(...) # part of group "BORG" > > two_of_nine = MyClass(...) > > > splinter1 = MyClass(..., group='splinter') > > splinter2 = MyClass(..., group='splinter') > > > and have splinter 1 and splinter2 share the same state, but a > > different state than the one shared by members of the BORG collective. > > > Any suggestions from the metaclass experts? > > You don't need a metaclass. Just turn _shared_state into a dictionary of > shared states, keyed by the group name: > > class SplinterBorg(object): > _shared_states = {} > def __new__(cls, *a, **k): > group = k.pop("group","BORG") > obj = object.__new__(cls, *a, **k) > obj.__dict__ = cls._shared_states.setdefault(group,{}) > return obj > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net Unfortunately, it fails. Here's what I tried, followed by the traceback class SplinterBorg(object): _shared_states = {} def __new__(cls, *a, **k): group = k.pop("group","BORG") obj = object.__new__(cls, *a, **k) obj.__dict__ = cls._shared_states.setdefault(group,{}) return obj class MyClass(SplinterBorg): def __init__(self, name): self.name = name a1 = MyClass('a') a2 = MyClass('aa') b1 = MyClass('b', group="B") Traceback (most recent call last): File "test.py", line 15, in b1 = MyClass('b', group="B") TypeError: __init__() got an unexpected keyword argument 'group' From sergio.correia at gmail.com Mon Sep 3 01:43:58 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Mon, 3 Sep 2007 00:43:58 -0500 Subject: PYTHONPATH not working on Windows XP (?) Message-ID: Hi, I'm trying to add a personal folder to the path used by python in searching for packages and modules. This folder, "C:\docs\utils" , has some packages not yet ready for "site-packages". First, I tried sys.path.append("C:\docs\utils") BUT this only lasts for the current python session. Then, I read about PYTHONPATH and went to Control Panel - System - Advanced - Enviromental Variables, and created a new variable (PYTHONPATH) containing the folder. However, sys.path does not detects it.. keeps printing the same old files: >>> import sys; import pprint; pprint.pprint(sys.path) ['C:\\Program Files\\AutoHotkey', 'C:\\Program Files\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Program Files\\Python25\\DLLs', 'C:\\Program Files\\Python25\\lib', 'C:\\Program Files\\Python25\\lib\\plat-win', 'C:\\Program Files\\Python25\\lib\\lib-tk', 'C:\\Program Files\\Python25', 'C:\\Program Files\\Python25\\lib\\site-packages'] (By the way, how did that AutoHotkey folder got there? Can I remove it from sys.path?) After my second failure, I went to the registry HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.5\PythonPath and added my folder there. Still nothing on sys.path , and my imports fail. Any suggestions for adding my path to sys.path permanently? I'm running out of ideas Thanks, Sergio From steve at holdenweb.com Tue Sep 11 18:15:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 18:15:20 -0400 Subject: Python.org mirror In-Reply-To: References: Message-ID: <46E71378.40505@holdenweb.com> Stream Service || Mark Scholten wrote: > Dear sir, madam, > > Stream Service would be happy to provide a free mirror for python.org. > We also host nl.php.net for free and we are happy to support more > opensource websites with free hosting. > > Could you inform me about the options to become an officiel python.org > mirror? > You may or may not be aware that the main Python site is hosted in the Netherlands. Many thanks for your offer, but we have in any case discontinued the addition of new mirrors. See item 14 in http://www.python.org/psf/records/board/minutes/2007-03-12/ regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From horpner at yahoo.com Fri Sep 14 10:20:41 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 14 Sep 2007 14:20:41 GMT Subject: recursion References: <5kvbn3F5h7l3U1@mid.uni-berlin.de> <1189774387.132173.282890@r29g2000hsg.googlegroups.com> Message-ID: On 2007-09-14, John Machin wrote: > On Sep 14, 10:04 pm, Marc 'BlackJack' Rintsch wrote: >> On Fri, 14 Sep 2007 13:40:17 +0200, Gigs_ wrote: >> > sorry i think that i express wrong. having problem with english >> >> > what i mean is how python knows to add all thing at the end of recursion >> >> Because you have written code that tells Python to do so. ;-) >> >> > >>> def f(l): >> > if l == []: >> > return [] >> > else: >> > return f(l[1:]) + l[:1] >> >> > f([1,2,3]) >> >> > recursion1 f([2,3]) + [1] >> >> > recursion2 f([3]) + [2] or [2, 1]? >> >> > recursion3 f([]) + [3] or [3, 2, 1] >> >> Both alternatives in recursion 2 and 3 are wrong. You have to >> simply replace the function invocation by its result which >> gives: >> >> f([1, 2, 3]) >> r1 f([2, 3]) + [1] >> r2 f([3]) + [2] + [1] >> r3 f([]) + [3] + [2] + [1] >> r4 [] + [3] + [2] + [1] >> >> And now the calls return: >> >> r3 [3] + [2] + [1] >> r2 [3, 2] + [1] >> r1 [3, 2, 1] >> >> > i dont get all this >> >> > >>> def f(l): >> > if l == []: >> > print l >> > return [] >> > else: >> > return f(l[1:]) + l[:1] >> >> > >>> f([1,2,3]) >> > [] >> > [3, 2, 1] # how this come here? how python save variables from each >> > recursion? >> >> There is not just one `l` but one distinct `l` in each call. >> > > I reckon that what the OP wants is a simple explanation of how > function calls use a stack mechanism for arguments and local > variables, and how this allows recursive calls, unlike the good ol' > FORTRAN IV of blessed memory. Perhaps someone could oblige him? > > I'd try but it's time for my beauty sleep :-) > > Good night all I may as well stick my neck out again, since I'm already beautiful. ;) Another way of understanding recursion is to break it up into seperate functions, so the spectre of a function calling itself doesn't appear. def f(l): if l == []: return [] else: return f(l[1:]) + l[:1] The function above reverses a list of arbitrary length. To help understand how it works, I'll write several discreet functions that sort lists of fixed lengths. I start with a simple case (though not the simplest case--that only comes with experience), reversing a two-element list: def f2(l): # reverse a two-element list return [l[1], l[0]] Next build up to the next level, writing a function that can reverse a three-element list. The key is to be as lazy as possible. You must figure out a way of taking advantage of the function that reverses a two-element list. The obvious solution is to use f2 to reverse the last two elements in our list, and append the first element in the list to that result: def f3(l): # reverse a three-element list return f2(l[1:]) + l[:1] And so on: def f4(l): return f3(l[1:]) + l[:1] def f5(l): return f4(l[1:]) + l[:1] def f6(l): return f5(l[1:]) + l[:1] A definite pattern had emerged, and it should be apparent now how to combine all those functions into one: def f_(l): if len(l) == 2: return [l[1], l[0]] else: return f_(l[1:]) + l[:1] But the function above breaks for lists with less than two items. >>> f_([1]) Traceback (most recent call last): File "", line 1, in File "", line 2, in f2 IndexError: list index out of range We can handle that. The reverse of a zero or one-element list is just itself. def f_(l): if len(l) < 2: return l elif len(l) == 2: return [l[1], l[0]] else: return f_(l[1:]) + l[:1] And we've arrived at an OK recursive function that can handle arbitrary length lists. It's not as simple as it could be, however. A little intuitive leap, perhaps, will allow you to note that the case of a two-element list can actually be handled without a special case: def f(l): if len(l) < 2: return l else: return f(l[1:]) + l[:1] Final note: for reasons of tradition, base cases are almost always set up as it was in the original function, checking for a zero-length list, and returning a new empty list, the truly simplest base case. Another intuitive leap is possibly required to note that a one-element list is not a special case after all: it's a reverse of a zero-element list with that one element appended. def f(l): if len(l) == 0: return [] else: return f(l[1:]) + l[:1] Clear as mud? -- Neil Cerutti From ldo at geek-central.gen.new_zealand Sun Sep 23 22:54:54 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 24 Sep 2007 14:54:54 +1200 Subject: [Bulk] Re: Writing Object Data to Disk References: <1190443648.5838.6.camel@ubuntu-laptop> <18c1e6480709230934k61504fa1r528c2f4ade9722f0@mail.gmail.com> Message-ID: In message , Amit Kumar Saha wrote: > I appreciate the XML related comment, but as of now I am ready-to-roll > with Python specific pickling. XML will be used in a later version of my > code! Will you need to maintain backward compatibility with data written by the current version of your code? From steve at holdenweb.com Sat Sep 15 18:40:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 15 Sep 2007 18:40:22 -0400 Subject: problems using pythom tempfile module In-Reply-To: <1189894434.135052.283420@w3g2000hsg.googlegroups.com> References: <1189890699.807384.258580@o80g2000hse.googlegroups.com> <1189891458.583774.171030@22g2000hsm.googlegroups.com> <1189894434.135052.283420@w3g2000hsg.googlegroups.com> Message-ID: samir.vds at googlemail.com wrote: > On Sep 15, 5:24 pm, buffi wrote: >> On Sep 15, 11:11 pm, "samir.... at googlemail.com" >> >> >> >> wrote: >>> Hello everyone, >>> I'm trying to test the tempfile module with the following script, >>> which basically creates a temporary file, fills the file with some >>> test data and prints it. >>> import tempfile >>> t = tempfile.TemporaryFile() >>> t.write("lalalala") >>> t.flush() >>> print t.read() >>> Unfortunately, the print statement gives me an empty string. Can >>> somebody tell me what I'm doing wrong ? >>> regards Samir >> Do a t.seek(0) before you do the read to "rewind" the file and then it >> should work. > > Ok, this really worked. Can you elaborate why I have to insert this > statement? > Each file has a "current position". As you write a file the current position moves to stay just ahead of what's been written. So if you read it without resetting the current position (back to the beginning with seek(0)) you will get an immediate end of file (i.e. 0 bytes) returned. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From korovev76 at gmail.com Wed Sep 19 10:22:49 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Wed, 19 Sep 2007 07:22:49 -0700 Subject: ONYX Message-ID: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> Hi everybody! Is there anything out there that can validate and parse some "onyx-style" xml? I searched the web, but coulnd't find nothing really interesting about it... thank you! korovev From chris.monsanto at gmail.com Fri Sep 21 22:12:26 2007 From: chris.monsanto at gmail.com (chris.monsanto at gmail.com) Date: Sat, 22 Sep 2007 02:12:26 -0000 Subject: Counting method calls In-Reply-To: References: Message-ID: <1190427146.685440.111640@50g2000hsm.googlegroups.com> On Sep 21, 7:15 pm, Ricardo Ar?oz wrote: > Hi, I know I'm being dumb but, why does it not work? > > >>> class MyList(list): > > ... def __init__(self): > ... self.calls = 0 > ... def __getattr__(self, name): > ... self.calls += 1 > ... return list.__getattribute__(self, name) > > >>> a = MyList() > >>> a > [] > >>> a.append(1) > >>> a > [1] > >>> a.calls > 88 > >>> a.append(3) > >>> a.calls > 88 > >>> a.sort() > >>> a > [1, 3] > >>> a.calls > > 176 > > TIA __getattr__ only works for attributes that don't exist. The name is sorta confusing... From koutoo at hotmail.com Tue Sep 18 16:59:47 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Tue, 18 Sep 2007 13:59:47 -0700 Subject: How do you limit the # of lines Read? Message-ID: <1190149187.799482.151320@19g2000hsx.googlegroups.com> I am working on a loop for my code and was wondering if there is a way to limit the number of lines read through? I'd hate to cut the test file in order to run the code in the testing phase. Can you add a value in the parenthesis of the readline() function? t = string.readline() # Limit this somehow? Kou From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 21 03:36:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 21 Sep 2007 09:36:16 +0200 Subject: Zope review In-Reply-To: <1190331847.514475.284200@22g2000hsm.googlegroups.com> References: <1190331847.514475.284200@22g2000hsm.googlegroups.com> Message-ID: <46f37471$0$16854$426a74cc@news.free.fr> Norm a ?crit : > Hi, > > without meaning to start a flame war between the various python web > tools, I was wondering if anyone had a review of the status of Zope. > For example, is it being used for new projects or just maintenance? > > I really like the look of Zope 3, and the interface/schema pattern for > defining objects looks very useful - but if the general feeling is to > use a different tool since Zope 3 isn't being used in the community > then I would prefer to start with that as I get to grips with Python > again. Zope is kinda of a world by itself, and it's often considered as not very pythonic. FWIW, it has it's own community. As far as I'm concerned, having working experience with Zope2, I'd say that Zope3 is certainly an interesting evolution, but absolutely not the kind of framework I'm after. My bet is that Pylons is the next big thing. From __peter__ at web.de Wed Sep 19 10:03:50 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2007 16:03:50 +0200 Subject: Keeping a database connection with a Singleton? References: <1190208406.041953.115580@g4g2000hsf.googlegroups.com> <1190209817.842068.280270@w3g2000hsg.googlegroups.com> Message-ID: exhuma.twn wrote: > On Sep 19, 3:45 pm, Peter Otten <__pete... at web.de> wrote: >> exhuma.twn wrote: > [...] >> >> By the way, there is a pythonic (near) singleton: the module. So if you go >> with option 2, just move the connection setup into a separate module that >> you can import into client code. >> >> Peter > > You say "(near)" singleton. What's the difference then? I was thinking of the main script of an application. If you import that by its name import main # assuming the file is main.py you end up with two instances sys.modules["main"] and sys.modules["__main__"]. Peter From xah at xahlee.org Mon Sep 10 18:14:51 2007 From: xah at xahlee.org (Xah Lee) Date: Mon, 10 Sep 2007 15:14:51 -0700 Subject: printing list containing unicode string In-Reply-To: References: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> Message-ID: <1189462491.541100.107150@22g2000hsm.googlegroups.com> On Sep 10, 8:12 am, Carsten Haese wrote: Xah Lee wrote: If i have a nested list, where the atoms are unicode strings, e.g. # -*- coding: utf-8 -*- ttt=[[u"?",u"?"], [u"???"],...] print ttt how can i print it without getting the u'\u1234' notation? i.e. i want it print just like this: [[u"?"], ...] Carsten Haese wrote: It's not quite clear why you want to do this, but this is how you could do it: print repr(ttt).decode("unicode_escape").encode("utf-8") Super! Thanks a lot. About why i want to... i think it's just simpler and easier on the eye? here's a example output from my program: [[u' ', 1022], [u'?', 472], [u' ', 128], [u'?w', 300], [u'?s', 12], [u'?|', 184],...] wouldn't it be preferable if Python print like this by default... Xah xah at xahlee.org ? http://xahlee.org/ From luojiang2 at tom.com Mon Sep 10 22:45:20 2007 From: luojiang2 at tom.com (Ginger) Date: Tue, 11 Sep 2007 10:45:20 +0800 Subject: anybody has py modules emulating symbian 60 on PC? References: Message-ID: <005f01c7f41d$cb9cfa80$4de1a8c0@amd.com> like appuifw/graphics/sysinfo modules, i've get some primary modules of these, they do what they did on S60 platform. u can get them from http://pdis.hiit.fi/pdis/ but these modules i get are rather simple ones, and a full emulation is needed ..., so anyone who has it, plz send me a copy, with my appreciation. thanks and regards Ginger From xdicry at gmail.com Wed Sep 12 04:17:21 2007 From: xdicry at gmail.com (Evan) Date: Wed, 12 Sep 2007 01:17:21 -0700 Subject: How can I work on VIM for python code such as cscope for C code? Message-ID: <1189585041.556933.77350@22g2000hsm.googlegroups.com> Hi, guys ~~ How can i work on VIM for python code? I use cscope plugin on VIM for C code before, it helps me to different function and search C variable where it is defined. I'm now starting to learn python, and I'd like to know how works on VIM. I saw that the VIM is support python such as syntax highlighting, autocmd,etc. but I really want to know if it can work with TAG. Do I need to downlaod other software/plugin? Thanks, From dotancohen at gmail.com Sun Sep 16 12:07:30 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 16 Sep 2007 18:07:30 +0200 Subject: Cannot formulate regex In-Reply-To: <5dcHi.108404$Y95.5768344@phobos.telenet-ops.be> References: <5dcHi.108404$Y95.5768344@phobos.telenet-ops.be> Message-ID: <880dece00709160907l5d512305k9cb074f99da38175@mail.gmail.com> On 16/09/2007, Roel Schroeven wrote: > FYI Kodos (http://kodos.sourceforge.net/) can be very useful for > developing, testing and debugging such regexes. Thanks, it's even in the Ubuntu repos. > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton Liebnitz should have quoted Newton on that one, too! Dotan From walter at livinglogic.de Wed Sep 12 08:13:48 2007 From: walter at livinglogic.de (=?UTF-8?B?V2FsdGVyIETDtnJ3YWxk?=) Date: Wed, 12 Sep 2007 14:13:48 +0200 Subject: Generating HTML In-Reply-To: <9e2f512b0709112133l41ce5ef1g815962a81becf6b9@mail.gmail.com> References: <9e2f512b0709112133l41ce5ef1g815962a81becf6b9@mail.gmail.com> Message-ID: <46E7D7FC.8070002@livinglogic.de> Sebastian Bassi wrote: > Hello, > > What are people using these days to generate HTML? I still use > HTMLgen, but I want to know if there are new options. I don't > want/need a web-framework a la Zope, just want to produce valid HTML > from Python. If you want something that works similar to HTMLgen, you could use XIST: http://www.livinglogic.de/Python/xist/ Servus, Walter From steve at holdenweb.com Mon Sep 17 07:09:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Sep 2007 07:09:26 -0400 Subject: Try this In-Reply-To: <1190008502.986300.286280@22g2000hsm.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> <1190008502.986300.286280@22g2000hsm.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Sep 16, 9:27?pm, "Gabriel Genellina" > wrote: >> En Sun, 16 Sep 2007 21:58:09 -0300, mensana... at aol.com [...] >> What about the rest of the world that don't speak >> English or even worse, don't use the Latin alpabet? > > When the rest of the world creates the next > generation of computers, THEY can chosse the > defaults. > Right, because of course US companies have no desire to do business with the rest of the world. I'm not given to ad hominem attacks, but this remark really seems to indicate that "chauvinistic cretin" might apply to you. You'll be gald to know you are unlikely to hear from me again. Your perception of the development of information technology is so skewed you would be better off knowing nothing. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From rafael81 at dif.um.es Thu Sep 20 04:28:49 2007 From: rafael81 at dif.um.es (Rafael Marin Perez) Date: Thu, 20 Sep 2007 10:28:49 +0200 Subject: Python for NSLU2 Message-ID: <1190276929.11755.41.camel@rapema-desktop> Hello, I am Rafael Marin Perez, and work as a researcher in University of Murcia (Spain). We are using the Network Storage Link for USB2.0 (NSLU2) device to desploy a wireless sensor network (WSN). And I need to install a bootstrap-loader of MSP430 in my NSLU2 to transfer the compiled images to the nodes. This bootstrap work over python. Therefore, I'm trying to install and compile modules of python2.4 for the ARM architecture of NSLU2 device. But I don't get to compile correctly. I'm using the cross compiler: http://peter.korsgaard.com/articles/crosstool-armv5b-softfloat-gcc-3.3.4-glibc-2.2.5.tar.gz Any idea, How can I do this? Thanks for your help. Regards, Rafa. From deets at nospam.web.de Tue Sep 25 18:15:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Sep 2007 00:15:42 +0200 Subject: jack audio connection kit In-Reply-To: References: Message-ID: <5ltfleF9tgibU1@mid.uni-berlin.de> patrick schrieb: > hello everyone, > > is there a way to make python output audio in jack: > http://jackaudio.org/ > > jack is the best audio solution for linux, mac and lately windows. i > found 1 project called pyjack, but the author remove the software from > his website. > > that would be neat! It seems to be a C-API-based app - simply use ctypes to access it. Shouldn't be hard. Diez From writser at gmail.com Wed Sep 19 12:17:06 2007 From: writser at gmail.com (writser at gmail.com) Date: Wed, 19 Sep 2007 09:17:06 -0700 Subject: Simple threading example freezes IDLE? Message-ID: <1190218626.334442.255450@57g2000hsv.googlegroups.com> hey all, For my study I'm writing a simple threaded webcrawler and I am trying to do this in python. But somehow, using threads causes IDLE to crash on Windows XP (with the latest python distribution 2.5.1). Even a simple example such as this: import thread, time def doSomething(): print "something" for i in range(2): thread.start_new(doSomething, ()) causes IDLE to freeze when I type it in the interpreter. Using the python command line everything works just fine. Using IDLE on Debian linux also does not cause anything to crash. What am I overlooking? regards, Writser Cleveringa From brown at esteem.com Thu Sep 6 19:24:09 2007 From: brown at esteem.com (Tom Brown) Date: Thu, 6 Sep 2007 16:24:09 -0700 Subject: why should I learn python In-Reply-To: <1189119676.239459.325280@w3g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> <1189119676.239459.325280@w3g2000hsg.googlegroups.com> Message-ID: <200709061624.10112.brown@esteem.com> On Thursday 06 September 2007 16:01, windandwaves wrote: > Hmmm, thank you all for your replies. I will do some research on the > net (i did some already, but because I am really not much of a > programmer, it is often too detailed for me). I have limited time, > but it does sound like something to learn, just for fun and for > practical use. How would you use it in a web development > environment? I mean, in real practical terms. Could it assist with > php? Is it easy to write GUI programs in Python? Checkout http://www.djangoproject.com/ or http://turbogears.org/ for web development. Checkout http://www.riverbankcomputing.co.uk/pyqt/index.php for writing GUI programs. There are other options for GUI apps. That is the one I use all the time. Good luck, Tom From fakeaddress at nowhere.org Wed Sep 19 00:08:23 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 19 Sep 2007 04:08:23 GMT Subject: can Python be useful as functional? In-Reply-To: References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> <1i4lvih.8g4kwjijx8e2N%aleax@mac.com> Message-ID: Rustom Mody asked: > [...] why does > > (yield(x) for x in si(l) if x % p != 0) > > not work? I would have expected generator expression to play better > with generators. You have a statement, "yield(x)", where the construct requires an expression. -- --Bryan From kf9150 at gmail.com Fri Sep 28 17:59:33 2007 From: kf9150 at gmail.com (kf9150 at gmail.com) Date: Fri, 28 Sep 2007 14:59:33 -0700 Subject: your opinion on book "Foundations of Python Network Programming"? Message-ID: <1191016773.834049.8940@19g2000hsx.googlegroups.com> Hello, i'm debating if i should buy this book. it received good reviews at Amazon: http://tinyurl.com/24zvrf. but it was published in 2004 and i'm afraid quite some materials might be outdated? any input? thanks, kelie From charles.fox at gmail.com Thu Sep 13 12:05:10 2007 From: charles.fox at gmail.com (Charles Fox) Date: Thu, 13 Sep 2007 09:05:10 -0700 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <13eim00ha4lf356@corp.supernews.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> Message-ID: <1189699510.244755.85080@r34g2000hsd.googlegroups.com> hmm, I guess this is the difference between numerical programming and the rest -- sure, if I was writing a database server or something it would be great to have thisObject.veryLongName to know what everything is -- however when you are implementing a model from a published paper, the variables tend to be single greek or roman letter names, possibly with subscripts and superscripts, and it helps if the name you see on the screen is the same as the name on the paper, as is the case in matlab. You want the equation on screen to look as similar to the one on the paper as possible, especially if its going to be read by another programmer who is familiar with the paper. Maybe for now I will just fix up my emacs to display the world 'self' in 10% gray... :-) From hanke at brailcom.org Thu Sep 20 09:26:56 2007 From: hanke at brailcom.org (Hynek Hanke) Date: Thu, 20 Sep 2007 09:26:56 -0400 Subject: pdb attach? Message-ID: <46F27520.40603@brailcom.org> Hello, please, is there something like 'attach' in pdb yet? My application uses threads and when it freezes (e.g. due to a deadlock situation), I'd like to get the traceback of all threads and inspect at which point did the application get into problems. Or could I send a signal to such a python process so that it would output backtraces from all threads before terminating? Because currently, if a thread runs into deadlock problems (or a thread fails on an exception and the other thread can't join it), I have no way of determining what went wrong. Such processes are not possible to terminate via CTRL-C in the interpreter, so I can't get the backtrace this way. Furthermore, I also need to debug subprocesses, so these are difficult to invoke interactively. I'm happy for any suggestions. Thank you, Hynek Hanke From rrr at ronadam.com Fri Sep 21 20:33:16 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 21 Sep 2007 19:33:16 -0500 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190415741.380795.259050@y42g2000hsy.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> Message-ID: Cristian wrote: > On Sep 21, 3:44 pm, Ron Adam wrote: > >> I think key may be to discuss names and name binding with your friend. How >> a name is not the object it self, like a variable is in other languages. >> For example show him how an object can have more than one name. And discus >> how names can be bound to nearly anything, including classes and functions. > > I could discuss name binding but it would be great if Python said this > itself. After all, you can even bind a module with the foo = bar > syntax by using __import__ function. If function definitions followed > the same pattern, I think a beginner would subconsciously (maybe even > consciously) realize that function names are just like everything > else. Actually, this would be helpful for many people. If you come > from a language like Java you're used to thinking of attributes and > methods as living in different namespaces. I think a new syntax will > encourage seasoned programmers think in a more Pythonic way. I could see methods having their own keywords. Then functions defined in classes would be static methods without any extra work. But to do that would break a lot of already existing code as well as confuse a lot of current users. > Python has done a very good job in easing people into programming. My > friend doesn't come to me very often because the syntax is clear and > simple and the builtin datatypes allow you to do so much. My goal is > that I would never have to explain to him about name binding; that > he'd pick it up by learning the language on his own. He's learned > lists, dictionaries and even some OOP without me. I don't think name > binding would be a stretch. Chances are he'll run into a gotcha where an object has two names and sort it out that way. Which is why I suggested starting there. It will save him some grief if he hasn't run into it yet. >> You could also discus factory functions with him. Once he gets that a >> function can return another function, then it won't be so much of a leap >> for a function to take a function as an argument. > > I think this isn't the most intuitive way of approaching first order > functions. The Python tutorial does this by defining a function, then assigning it to another name and calling it from the new name. http://www.python.org/doc/current/tut/tut.html > It's true that if a function can return another function > then a function must be first order (i.e., it's just like any other > variable), but that seems almost backwards to me. I think it would > make more sense to have beginners _know_ that functions are like all > other variables and can therefore be passed by other functions or > returned by other functions. That I think would be better accomplished > if they define functions the same way you would define other variables > that you know can be passed and returned. I think it gets awkward fairly quick if you try and work out how to do this. There have been requests in the past to have functions assigned to names like other things. The nice thing about the current syntax is it more closely resembles what you would type at call time, so it is more self documenting. def sum(x, y): return x + Y total = sum(1, 2) I think changing that would be trading one type of clarity for another. Ron From dominique.pignon at free.fr Mon Sep 24 19:54:42 2007 From: dominique.pignon at free.fr (Dominique Pignon) Date: Tue, 25 Sep 2007 01:54:42 +0200 Subject: Pyrex installation on windows XP: step-by-step guide Message-ID: <000501c7ff06$4939cd40$0200a8c0@amilo> Bravo pour le guide d'installation! Je suppose que vous parlez fran?ais. J'ai install? pyrex suivant vos conseils tout se passe normalement l'exemple primes est install? dans /Lib/site_packages/primes.pyd le programme a ?t? compil? mais je n'arrive pas ? faore le test le module n'est pas reconnu: >>> primes Traceback (most recent call last): File "", line 1, in -toplevel- primes NameError: name 'primes' is not defined que se passe-t-il? cela doit sans doute ?tre trivial merci de me r?pondre Dominique Pignon -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjt22 at bath.ac.uk Fri Sep 7 09:57:35 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Fri, 07 Sep 2007 06:57:35 -0700 Subject: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute Message-ID: <1189173455.525144.326300@y42g2000hsy.googlegroups.com> Hi there I am fairly new to Python and have not really used regular expressions before (I think this might be needed for my query) and wondered if you could help I have a step class and store in a list step instances A step instance contains variables: name, startTime etc and startTime is stored as a string %H:%M:%S What I would like to do is to be able to sort this list of objects based on the startTime object so that the first item in the list is the object with the earliest Start time and last item is the object with the last Start time. I belive my key has to be = strpTime(step.sTime, "%H:%M:%S") But don't know how to create the comparison funciton. Any help on how I can perform this whole operation would be much appreciated. Thanks Chris From maxim.gavrilov at gmail.com Mon Sep 24 14:31:56 2007 From: maxim.gavrilov at gmail.com (Vircom) Date: Mon, 24 Sep 2007 11:31:56 -0700 Subject: Small changes in side library In-Reply-To: <1190658364.739221.39030@k79g2000hse.googlegroups.com> References: <1190509647.227883.226460@d55g2000hsg.googlegroups.com> <1190658364.739221.39030@k79g2000hse.googlegroups.com> Message-ID: <1190658716.773690.171020@50g2000hsm.googlegroups.com> On Sep 24, 10:26 pm, Vircom wrote: > On Sep 24, 1:16 am, "Gabriel Genellina" > wrote: > > > > > En Sat, 22 Sep 2007 22:07:27 -0300, maxim.gavri... at gmail.com > > escribi?: > > > > I have the side library which provides wide set of different > > > functions, but I'm going to replace some of them with mine and > > > provided such 'modified' library thought my project. > > > > The following way works well for my purpose: > > > > ------- mylib.py ------- > > > import sidelib > > > > import os, sys, .... > > > > def func(): > > > ..... > > > sidelib.func = func > > > ...... > > > ?!?!?!?! > > > -------------------------- > > > > But this cause to write mylib.sidelib.func() to function call, is it > > > any way to 'map' definitions from sidelib to mylib (possible at point > > > marked ?!?!?!?!) such that constructions like mylib.func() will be > > > provided and client code don't see difference between changed and > > > original library in syntax way? > > > Your code already works as you like: > > import sidelib > > sidelib.func() > > and you get the modified function. > > > You don't have to say mylib.sidelib.func - in fact, mylib.sidelib is the > > same module object as sidelib > > But you have to ensure that the replacing code (mylib.py) runs *before* > > anyone tries to import something from sidelib. > > > > One my idea was to do from sidelib import * and then modify globals() > > > dictionary, but this isn't good too because mylib imports many other > > > modules and they all mapped into it's namespace (like mylib.os, > > > mylib.sys). > > > As you said, a bad idea. > > > -- > > Gabriel Genellina > > Thank you for reply! > I make a mistake in my problem description, because I'm going not only > use my own functions (it'll be simple import library question), but > also using side library many functions (with only a few one replaced > by me). For now I'm stay at the following solution: > ----- mylib.py ----- > import sidelib > from sidelib import * > > _sidelib_set = set(dir(sidelib)) > _mylib_set = set(['replacedfunc1', 'replacedfunc2', ....]) # all > exports > __all__ = list(_sidelib_set.union(_mylib_set)) > > ....implementations of _mylib_set functions.... > -------------------- > > Seems it's pretty good for my task, mylib seems fully the same as the > sidelib one. > > Thanks for you attention, anyway! Sorry, I'm misunderstand your propose by first reading. Importing sidelib after my changes are really the best idea. I'm changingmy project this way. Thank you!!! From tuomas.vesterinen at pp.inet.fi Tue Sep 4 11:33:55 2007 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Tue, 04 Sep 2007 15:33:55 GMT Subject: REGULAR EXPRESSION In-Reply-To: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> References: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> Message-ID: AniNair wrote: > hi.. I am trying to match '+ %&/-' etc using regular expression in > expressions like 879+34343. I tried \W+ but it matches only in the > beginning of the string Plz help Thanking you in advance... > Is this what you are seeking for? >>> re.compile('(\+{0,1})?([0-9]+)').findall('879+34343') [('', '879'), ('+', '34343')] Tuomas Vesterinen From wizzardx at gmail.com Fri Sep 28 03:27:40 2007 From: wizzardx at gmail.com (David) Date: Fri, 28 Sep 2007 09:27:40 +0200 Subject: marshal bug? In-Reply-To: <18c1e6480709280011g1fcc4976v77dd0eec0e416752@mail.gmail.com> References: <1190961020.258850.215130@g4g2000hsf.googlegroups.com> <18c1e6480709280011g1fcc4976v77dd0eec0e416752@mail.gmail.com> Message-ID: <18c1e6480709280027p43b6fcd4v83c9d262953bae09@mail.gmail.com> > I'm not sure why, but marshal does dump the 2 differently. ie: > > >>> marshal.dumps(str(123)) > 's\x03\x00\x00\x00123' > > >>> marshal.dumps(str("123")) > 't\x03\x00\x00\x00123' > I've just checked the source [1]. 's' refers to a regular string, 't' refers to an interned[2] string. In other words the difference between the 2 marshal dumps is an internal python implementation detail. You probably shouldn't be comparing marshal dumps in your app in the first place. [1] http://coverage.livinglogic.de/Python/marshal.c.html. (Actually, I checked the downloaded bz2, but this is the only URL for marshal.c I could find) [2] http://mindprod.com/jgloss/interned.html From shriphanip at gmail.com Tue Sep 25 11:39:45 2007 From: shriphanip at gmail.com (Shriphani) Date: Tue, 25 Sep 2007 08:39:45 -0700 Subject: comparing elements of a list with a string Message-ID: <1190734785.439839.303030@50g2000hsm.googlegroups.com> Hello all, I have a problem here. I have a list named list_of_files which contains filenames with their timestamps attached to the name. If I have a string "fstab", and I want to list out the files in whose names the word fstab appears should I go about like this : def listAllbackups(file): list_of_files = os.listdir("/home/shriphani/backupdir") for element in list_of_files: if element.find(file) != -1: date = ### time = #### return (date, time) The major trouble is that the return statement causes it to exit after attempt one. How do I use the yield statement here? Regards, Shriphani Palakodety From nagle at animats.com Thu Sep 20 21:38:44 2007 From: nagle at animats.com (John Nagle) Date: Thu, 20 Sep 2007 18:38:44 -0700 Subject: M2Crypto 0.18 - new version, same old build bugs. In-Reply-To: <1190325086.825866.319760@k79g2000hse.googlegroups.com> References: <1190325086.825866.319760@k79g2000hse.googlegroups.com> Message-ID: <54FIi.10130$z_5.1294@nlpi069.nbdc.sbc.com> Paul Boddie wrote: > On 20 Sep, 22:12, John Nagle wrote: > >> That was for M2Crypto 0.17. >> >> It's still broken in M2Crypto 0.18. >> >> And there's no RPM or Windows binary. >> >> Nobody actually uses this stuff, do they? > > > I can find Ubuntu packages for 0.16 and 0.17: > > http://packages.ubuntu.com/feisty/libs/python-m2crypto > http://packages.ubuntu.com/gutsy/libs/python-m2crypto > > So, clearly some people are managing to build the library, even if it > isn't the absolute latest version. You might want to take a look at > the source packages and the patches the distribution people apply, > although it doesn't look like they are actually doing much patching. > The source packages suggest that they use SWIG 1.3.24 to build > M2Crypto - is that what you're using? > > Paul I have builds of 0.17 of M2Crypto for both Linux and Windows. I want the new bug fixes. The 0.17 version mishandles SSL certs that specify more than one domain name, and that's supposedly fixed in 0.18. But there are enough changes that just copying over the relevant file (Checker.py) isn't sufficient. John Nagle From ldo at geek-central.gen.new_zealand Sun Sep 9 02:56:16 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 09 Sep 2007 18:56:16 +1200 Subject: pdb question - spew out "steps" until crash needed References: <7xbqcd4s2y.fsf@ruckus.brouhaha.com> Message-ID: In message <7xbqcd4s2y.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > However, the malloc problem has probably already screwed things up > long before the application actually freezes. Your best bet is > to recompile Python with malloc debugging enabled and/or run Python > itself under a debugger. A simple thing to try would be to invoke Python with MALLOC_CHECK_ set to 3. This enables extra checking in the glibc malloc routine, which might help shed some light on the problem. From __peter__ at web.de Thu Sep 27 13:34:04 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Sep 2007 19:34:04 +0200 Subject: getopt with negative numbers? References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> Message-ID: Casey wrote: > Is there an easy way to use getopt and still allow negative numbers as > args? I can easily write a workaround (pre-process the tail end of > the arguments, stripping off any non-options including negative > numbers into a separate sequence and ignore the (now empty) args list > returned by getopt, but it would seem this is such a common > requirement that there would be an option to treat a negative value as > an argument. Note that this is only a problem if the first non-option > is a negative value, since getopt stops processing options as soon as > it identifies the first argument value. > > Alternatively, does optparse handle this? I haven't used optparse (I > know it is more powerful and OO, but you tend to stick with what you > know, especially when it is part of my normal python programming > template), but if it handles negative numbers I'm willing to learn it. optparse can handle options with a negative int value; "--" can be used to signal that no more options will follow: >>> import optparse >>> parser = optparse.OptionParser() >>> parser.add_option("-a", type="int")

Back to episode %d\n" >> % >> ( >> LinkToMe({"ep" : Link["from_episode"]}), >> Link["from_episode"] >> ) >> ) >> #end for > > What do you mean by not possible!? This compiles fine for me. He means he has to use backslashes instead of parentheses here. Which is not true, you could easily rephrase this as: for link in GetEachRecord( "links", ....): out.write( .... ) See? No backslash! Stefan From Scott.Daniels at Acm.Org Sun Sep 23 17:26:32 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 23 Sep 2007 14:26:32 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <13f8unjjeqs5p97@corp.supernews.com> <13faa66cb1phre1@corp.supernews.com> Message-ID: <13fdmdmsaasak91@corp.supernews.com> Ron Adam wrote: > Scott David Daniels wrote: >> Ron Adam wrote: >>> .... How about this? >>> def integrate(fn, x1, x2, n=100):... >> The point was a pedagogic suggestion, ... > I understood your point. I just found it interesting since I've been > trying to extend my math (for use with python) skills in this area. Ah, sorry. I had realized I wasn't explicit in my first message. Yes, a perfectly fine integration. You can then (and this is a major jump to get used to): import functools Sine = functools.partial(integrate, math.cos, 0.0, n=100) Similarly, you can define a derivative that will behave fairly well, all without examining the definition of the function being operated upon. -Scott From f.braennstroem at gmx.de Thu Sep 13 17:09:16 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Thu, 13 Sep 2007 21:09:16 +0000 Subject: extract text from log file using re Message-ID: Hi, I would like to delete a region on a log file which has this kind of structure: #------flutest------------------------------------------------------------ 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 reversed flow in 1 faces on pressure-outlet 35. Writing "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.cas"... 5429199 mixed cells, zone 29, binary. 11187656 mixed interior faces, zone 30, binary. 20004 triangular wall faces, zone 31, binary. 1104 mixed velocity-inlet faces, zone 32, binary. 133638 triangular wall faces, zone 33, binary. 14529 triangular wall faces, zone 34, binary. 1350 mixed pressure-outlet faces, zone 35, binary. 11714 mixed wall faces, zone 36, binary. 1232141 nodes, binary. 1232141 node flags, binary. Done. Writing "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.dat"... Done. 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 reversed flow in 2 faces on pressure-outlet 35. 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 #------------------------------------------------------------------ I have a small script, which removes lines starting with '(re)versed', '(i)teration' and '(t)urbulent' and put the rest into an array: # -- plot residuals ---------------------------------------- import re filename="flutest" reversed_flow=re.compile('^\ re') turbulent_viscosity_ratio=re.compile('^\ tu') iteration=re.compile('^\ \ i') begin_of_res=re.compile('>\ \ \ i') end_of_res=re.compile('^\ ad') begin_of_writing=re.compile('^\Writing') end_of_writing=re.compile('^\Done') end_number=0 begin_number=0 n = 0 for line in open(filename).readlines(): n = n + 1 if begin_of_res.match(line): begin_number=n+1 print "Line Number (begin): " + str(n) if end_of_res.match(line): end_number=n print "Line Number (end): " + str(n) if begin_of_writing.match(line): begin_w=n+1 print "BeginWriting: " + str(n) print "HALLO" if end_of_writing.match(line): end_w=n+1 print "EndWriting: " +str(n) if n > end_number: end_number=n print "Line Number (end): " + str(end_number) n = 0 array = [] array_dummy = [] array_mapped = [] mapped = [] mappe = [] n = 0 for line in open(filename).readlines(): n = n + 1 if (begin_number <= n) and (end_number > n): # if (begin_w <= n) and (end_w > n): if not reversed_flow.match(line) and not iteration.match(line) and not turbulent_viscosity_ratio.match(line): m=(line.strip().split()) print m if len(m) > 0: # print len(m) laenge_liste=len(m) # print len(m) mappe.append(m) #--end plot residuals------------------------------------------------- This works fine ; except for the region with the writing information: #-----writing information ----------------------------------------- Writing "/home/fb/fluent-0500.cas"... 5429199 mixed cells, zone 29, binary. 11187656 mixed interior faces, zone 30, binary. 20004 triangular wall faces, zone 31, binary. 1104 mixed velocity-inlet faces, zone 32, binary. 133638 triangular wall faces, zone 33, binary. 14529 triangular wall faces, zone 34, binary. 1350 mixed pressure-outlet faces, zone 35, binary. 11714 mixed wall faces, zone 36, binary. 1232141 nodes, binary. 1232141 node flags, binary. Done. # -------end writing information ------------------------------- Does anyone know, how I can this 'writing' stuff too? The matchingIt occurs a lot :-( Regards! Fabian From carsten at uniqsys.com Fri Sep 7 09:27:35 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 07 Sep 2007 09:27:35 -0400 Subject: Is a Borg rebellion possible? (a metaclass question) In-Reply-To: <1189168282.665210.260840@19g2000hsx.googlegroups.com> References: <1189168282.665210.260840@19g2000hsx.googlegroups.com> Message-ID: <1189171655.3367.38.camel@dot.uniqsys.com> On Fri, 2007-09-07 at 12:31 +0000, Andr? wrote: > In my application, I make use of the Borg idiom, invented by Alex > Martelli. > > class Borg(object): > '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273 > > Derive a class form this; all instances of that class will share > the > same state, provided that they don't override __new__; otherwise, > remember to use Borg.__new__ within the overriden class. > ''' > _shared_state = {} > def __new__(cls, *a, **k): > obj = object.__new__(cls, *a, **k) > obj.__dict__ = cls._shared_state > return obj > > ---- > This has worked very well so far, but is starting to impose some > unwanted constraints on my program design. > > What I would like to do is, to put it figuratively, create a Borg > rebellion with various splinter groups. In concrete Python terms, I > would like to have > > class MyClass(Borg, ...): > ... > > seven_of_nine = MyClass(...) # part of group "BORG" > two_of_nine = MyClass(...) > > splinter1 = MyClass(..., group='splinter') > splinter2 = MyClass(..., group='splinter') > > and have splinter 1 and splinter2 share the same state, but a > different state than the one shared by members of the BORG collective. > > Any suggestions from the metaclass experts? You don't need a metaclass. Just turn _shared_state into a dictionary of shared states, keyed by the group name: class SplinterBorg(object): _shared_states = {} def __new__(cls, *a, **k): group = k.pop("group","BORG") obj = object.__new__(cls, *a, **k) obj.__dict__ = cls._shared_states.setdefault(group,{}) return obj HTH, -- Carsten Haese http://informixdb.sourceforge.net From Shawn at Milochik.com Fri Sep 14 09:44:23 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Fri, 14 Sep 2007 09:44:23 -0400 Subject: [Tutor] Just bought Python in a Nutshell In-Reply-To: References: Message-ID: <2dc0c81b0709140644w629acda6vee05d589a2e54043@mail.gmail.com> My best advice: Skim it -- just flip the pages, glancing at each one without really reading it -- maybe just read the bold type. You'll find that very rewarding when you run into a problem in your coding and remember that you saw *something* which could be related. You will probably notice some built-in functions that you will need and possibly would have re-invented if you didn't know they were there. I don't really find it to be a "reading" book -- it's more of a reference book. Flip through it, then keep it within reach of your keyboard. Shawn From ldo at geek-central.gen.new_zealand Mon Sep 10 03:52:26 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 10 Sep 2007 19:52:26 +1200 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> <7xhcm4pl5m.fsf@ruckus.brouhaha.com> <13e7roq4dbo6043@corp.supernews.com> Message-ID: In message <13e7roq4dbo6043 at corp.supernews.com>, Steven D'Aprano wrote: > On Sun, 09 Sep 2007 18:53:32 +1200, Lawrence D'Oliveiro wrote: > >> In message <7xhcm4pl5m.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >> >>> Lawrence D'Oliveiro writes: >>> >>>> Except that the NSA's reputation has taken a dent since they failed to >>>> anticipate the attacks on MD5 and SHA-1. >>> >>> NSA had nothing to do with MD5 ... >> >> Nevertheless, it was their job to anticipate attacks on it. After all, >> they call themselves the "National _Security_ Agency", don't they? > > The NSA has many jobs, and doing public research in crypto is only one of > them -- and a particularly small one at that. For all we know, they had > an attack on MD5 ten years before anyone else and didn't tell anyone > because keeping it secret made it useful for one of their other jobs. Yes, but they're supposed to look after US _National_ security, not their own security. Since people in strategic jobs make so much use of hash functions in crypto, that means it is most certainly an important part of the NSA's function to ensure that there are good hash functions available. They've fallen down on that job. >>> ... and it's to NSA's credit that SHA-1 held up for as long as it did. >> >> But they have no convincing proposal for a successor. That means the gap >> between the classified and non-classified state of the art has shrunk >> down to insignificance. > > I don't see how that follows. Because previously, the NSA has done things that it took open researchers years, even decades, to figure out. But not any more. From steve at holdenweb.com Mon Sep 17 07:02:14 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Sep 2007 07:02:14 -0400 Subject: Python 3K or Python 2.9? In-Reply-To: <1190013827.107324.111820@w3g2000hsg.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1190013827.107324.111820@w3g2000hsg.googlegroups.com> Message-ID: TheFlyingDutchman wrote: >> The other half of the confusion is cleared up by considering that >> Python methods are ordinary functions that don't magically "know" in >> which "class" context they are executing: they must be told via the >> first parameter. >> > > They can be told all they want by the compiler/runtime - implicitly - > under-the-covers, out-of-sight. > I wish you would keep these deep insightful comments to yourself. Your knowledge of the interpreter internals appears to be based on examination by crystal ball. You conveniently ignore the fact that the situation described by David Trudgett (and, by the way, your quoting with no attributions is also becoming tiresome very quickly) is a *design choice*, not a mistake. It's done precisely to make an explicit reference to the instance available to methods. You also conveniently ignore the fact that changing tis would also change other aspects of the language, such as the ability to graft functions into instances and classes as methods. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From w_a_x_man at yahoo.com Sun Sep 30 16:06:39 2007 From: w_a_x_man at yahoo.com (William James) Date: Sun, 30 Sep 2007 13:06:39 -0700 Subject: Delete spaces In-Reply-To: <1191064960.624796.115790@d55g2000hsg.googlegroups.com> References: <1190994234.526554.110870@y42g2000hsy.googlegroups.com> <1191064960.624796.115790@d55g2000hsg.googlegroups.com> Message-ID: <1191182799.149749.174140@57g2000hsv.googlegroups.com> John Machin wrote: > On Sep 29, 1:43 am, kou... at hotmail.com wrote: > > If I have a text file that is delimited by spaces, how do I import it > > and get to comma delimited? Here is a row of data from the text file: > > > > 1 1 10:55:14 2 65 8.5 > > 1.4+1.1 2.5 Class-2 0 > > > > I tried a few examples from the group and it didn't work, since the > > file also has a header row and a row of seperators ( -------). The > > lengths of each row is something like 130, so there are extra spaces > > after the last value as well. I have tried joining and other things, > > but I couldn't figure out how to get the values to come together. > > Thanks. > > > > Kou > > It would help enormously if you could show us UNAMBIGUOUSLY what is in > say the first 3 lines after the headings and separators -- do this: > > print repr(open("thefile", "rb").read()[:400]) > > The other thing you need is to know enough about the file format to > show us what is the CSV output that you require from the sample input > -- we don't have crystal balls, and are likely to make half-donkeyed > guesses, like these: > > If the spaces are really tabs, use line.split('\t') > > Otherwise: the file has fixed column widths, and any use of line.split > will mangle it. > > The clumsy way to handle this is to count column positions, and write > something ugly like: > field1 = line[0:8] > field2 = line[8:20] > etc > > "a row of seperators ( -------)" sounds suspiciously like the "column > aligned" format that can be produced by running a SQL query on a SQL > Server database using MS's "Query Analyser". It looks like this: > > RecordType ID1 ID2 Description > ----------- -------------------- ----------- ---------------------- > 1 12345678 123456 Widget > 4 87654321 654321 Gizmoid > etc > > Does your file look something like that? If so, then all you have to > do is leverage off the fact that the second line has one-space gaps > between each bunch of dashes, and you can write a little module that > will read any file like that, just as though it were a CSV file. If the fields are separated by whitespace, this Awk program can handle the situation: awk 'BEGIN{OFS=","} {$1=$1} 1' oldfile >newfile If the fields are fixed-width and the 2nd line is a guide to those widths, then this Ruby program should work (not optimized for speed): lines = IO.readlines( 'data2' ) # Dump header. lines.shift # Save column guide. guide = lines.shift.scan( /-+ */ ) for line in lines do puts guide.map{|s| line.slice!(0,s.size).strip}.join(",") end From steve at holdenweb.com Tue Sep 18 15:46:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Sep 2007 15:46:37 -0400 Subject: can Python be useful as functional? In-Reply-To: <871wcvlwly.fsf@rudin.co.uk> References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> <871wcvlwly.fsf@rudin.co.uk> Message-ID: Paul Rudin wrote: > Robin Becker writes: > >> Steve Holden wrote: >>> Lorenzo Stella wrote: >> ...... >>> So, which environment do you habitually use that provides an >>> *unlimited* stack? >>> >>> You remind me of the conversation between the philosopher and an >>> attractive lady whom he was seated next to at dinner. He asked her >>> if she would sleep with him for a million dollars, to which she >>> readily agreed. So he followed this by asking her if she'd sleep >>> with him for a dollar. She replied: "No. Do you take me for a >>> prostitutte?", to which his riposte was "We have already established >>> that fact, and are now merely haggling about the price". >>> >> allegedly G B Shaw >> (http://findarticles.com/p/articles/mi_qn4158/is_19980925/ai_n14182408) > > Also allegedly Winston Churchill, although wikiquote says: > > "This is a very old joke where the participants vary dramatically > from each telling. It's very unlikely though not impossible that > the joke originated from Churchill." Also allegedly Bertrand Russell, who was going to be the subject of my version until I realized that I would get many corrections to any asserted identity of the originator. I should have know to expect just as many corrections to the absence of any such assertion, this being c.l.py :-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From lew at lewscanon.com Tue Sep 18 18:05:27 2007 From: lew at lewscanon.com (Lew) Date: Tue, 18 Sep 2007 18:05:27 -0400 Subject: The meaning of a = b in object oriented languages In-Reply-To: References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> Message-ID: <_4OdnQi5jow61m3bnZ2dnUVZ_tvinZ2d@comcast.com> Roel Schroeven wrote: > Laurent Pointal schreef: >> Summercool a ?crit : >>> >>> The meaning of a = b in object oriented languages. >>> ==================================================== >> >> >> Oups, reading the subject I thought it was a Xah Lee post. > > me too ... Nah, this dude's all right, so far. As if my opinion mattered. Stay with it, Summercool. It's what discussion groups are for. Here's why the reaction: cross-posting of computer-science-type essays, something Xah Lee does. But he recycles all his decades-old crap and really doesn't participate in the discussion. This isn't that at all. -- Lew From Shawn at Milochik.com Wed Sep 5 13:03:38 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 5 Sep 2007 13:03:38 -0400 Subject: Text processing and file creation In-Reply-To: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> Message-ID: <2dc0c81b0709051003n6b81493ah373ce626e172309e@mail.gmail.com> On 9/5/07, malibuster at gmail.com wrote: > I have a text source file of about 20.000 lines. > >From this file, I like to write the first 5 lines to a new file. Close > that file, grab the next 5 lines write these to a new file... grabbing > 5 lines and creating new files until processing of all 20.000 lines is > done. > Is there an efficient way to do this in Python? > In advance, thanks for your help. > I have written a working test of this. Here's the basic setup: open the input file function newFileName: generate a filename (starting with 00001.tmp). If filename exists, increment and test again (0002.tmp and so on). return fileName read a line until input file is empty: test to see whether I have written five lines. If so, get a new file name, close file, and open new file write line to file close output file final time Once you get some code running, feel free to post it and we'll help. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 24 07:29:48 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 24 Sep 2007 13:29:48 +0200 Subject: Writing Object Data to Disk In-Reply-To: References: <1190443648.5838.6.camel@ubuntu-laptop> Message-ID: <46f79f99$0$30457$426a34cc@news.free.fr> David a ?crit : >> I would like to know if "Pickling" the class object is the only way of >> writing it to disk for persistent storage. Also, do we have a concept >> similar to "array of objects" in Python? The number of objects is only >> known at "run-time". > > Have a look at YAML. > > http://freshmeat.net/projects/syck/ > > Also it is possible to persist python data to and from XML. See > xml.marshal.generic.dumps or JSON... From byte8bits at gmail.com Mon Sep 24 09:42:22 2007 From: byte8bits at gmail.com (byte8bits at gmail.com) Date: Mon, 24 Sep 2007 06:42:22 -0700 Subject: Converting numbers to unicode charaters Message-ID: <1190641342.127770.115610@y42g2000hsy.googlegroups.com> Here's how I'm doing this right now, It's a bit slow. I've just got the code working. I was wondering if there is a more efficient way of doing this... simple example from interactive Python: >>> word = '' >>> hexs = ['42', '72', '61', '64'] >>> for h in hexs: ... char = unichr(int(h, 16)) ... word += char ... print char ... B r a d >>> print word Brad Each hex_number is two digits. unichr converts that to a character that I append to previous ints that have been converted to chars. In this way, I convert a string of hex numbers to ints to letters, to words. Perhaps I'm doing it wrong... any tips? Thanks, Brad From dotancohen at gmail.com Sun Sep 16 11:18:21 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 16 Sep 2007 17:18:21 +0200 Subject: Cannot formulate regex Message-ID: <880dece00709160818h7463ec2apc5b54454315d32f6@mail.gmail.com> I'd like to filter spam from a certain company. Here are examples of strings found in their spam: Mega Dik Mega D1k MegaDik Mega. Dik M eg ad ik M E _G_A_D_ IK M_E_G. ADI. K I figured that this regex would match all but the second example, yet it matches none: |[^a-z]m[^a-z]e[^a-z]g[^a-z]a[^a-z]d[^a-z]i[^a-z]k[^a-z]|i What would be the regex that matches "megadik" regardless of whatever characters are sprinkled throughout? Thanks in advance. Dotan From christopher.saunter at durham.ac.uk Sun Sep 23 10:25:53 2007 From: christopher.saunter at durham.ac.uk (c d saunter) Date: Sun, 23 Sep 2007 14:25:53 +0000 (UTC) Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> Message-ID: : arguments and dicts, which are lot more versatile. Another major use, : talking to hardware, is not something oft done in Python either. Are you sure? I've been doing lots of exactly that for 4 years, and I'm not the only one round here... Python makes an excellent language for talking to hardware. cds From jcd at sdf.lonestar.org Fri Sep 21 17:53:10 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 21 Sep 2007 17:53:10 -0400 Subject: RE Help In-Reply-To: <200709212209.29148.thomas@jollans.com> References: <1190399985.324448.242610@d55g2000hsg.googlegroups.com> <200709212209.29148.thomas@jollans.com> Message-ID: <46F43D45.3000600@sdf.lonestar.org> Thomas Jollans wrote: > On Friday 21 September 2007, byte8bits at gmail.com wrote: > >> Not specific to Python, but it will be implemented in it... how do I >> compile a RE to catch everything between two know values? Here's what >> I've tried (but failed) to accomplish... the knowns here are START and >> END: >> >> data = "asdfasgSTARTpruyerfghdfjENDhfawrgbqfgsfgsdfg" >> x = re.compile('START.END', re.DOTALL) >> >> x.findall(data) >> > > I'm not sure finding a variable number of occurences can be done with re. How > about > > # data = the string > strings = [] > for s in data.split('START')[1:]: > strings.append(s.split('END')[0]) > Nice. I've noticed that since I switched from Perl to Python, I hardly ever use regular expressions anymore. In perl, they're so easy to fire up that they become the first tool out of the toolbox, but when you make the barrier to access just a tiny bit higher (import re/re.compile) you start noticing how easy it is to accomplish most of those feats without regexes, and much more readably, too. Of course, it should be noted that the different implementations suggested behave differently, which could also affect the choice of method. If you have "abcSTARTdefSTARTghiEND", your version will spit out strings = ['def', 'ghi'], but a regex, depending on whether it is greedy or non greedy, will either spit out ['STARTdefSTARTghiEND'] or ['STARTghiEND']. Correction, it will spit out the first one, whether greedy or not. The difference comes with two END tags in a row. Cheers, Cliff From bj_666 at gmx.net Thu Sep 27 12:53:09 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Sep 2007 16:53:09 GMT Subject: comparing elements of a list with a string References: <1190734785.439839.303030@50g2000hsm.googlegroups.com> <1190889848.653434.178450@g4g2000hsf.googlegroups.com> Message-ID: <5m25flFatlbuU3@mid.uni-berlin.de> On Thu, 27 Sep 2007 08:16:59 -0400, Steve Holden wrote: > Shriphani wrote: >> Hello, >> Would that mean that if I wanted to append all the (date, time) tuples >> to a list, I should do something like: >> >> for file in list_of_backup_files: >> some_list.append(file) > > That would be one way to do it (assuming you started with some_list as > an empty list). But a faster way would be to use a list comprehension > and say > > some_list = [f for f in list_of_backup_files] Or: some_list = list(list_of_backup_files) If `some_list` is not empty: some_list.extend(list_of_backup_files) Ciao, Marc 'BlackJack' Rintsch From erik at myemma.com Fri Sep 28 10:37:15 2007 From: erik at myemma.com (Erik Jones) Date: Fri, 28 Sep 2007 09:37:15 -0500 Subject: Python 3.0 migration plans? In-Reply-To: References: Message-ID: <8D62705E-2E4D-4F97-9553-9B1460923057@myemma.com> On Sep 27, 2007, at 8:17 PM, Steve Holden wrote: > James Stroud wrote: >> Steve Holden wrote: >>> I wondered if a straw poll could get some idea of readers' thoughts >>> about when they will be migrating to 3.0 on, so I used the new >>> widget on >>> Blogger to add a poll for that. >>> >>> I'd appreciate if if you would go to >>> >>> http://holdenweb.blogspot.com/ >>> >>> and register your vote on your intended migration timescale. >>> >>> Thanks! >> >> I'm going to abstain voting until 'public beta + about 1 year' is >> a choice. >> > Richard Jones wrote: >> I'll use the "no plans" response for my actual "no simple answer" >> real >> response. >> >> > So what we need is a poll on what the questions should be. I *love* > c.l.py. Does professional vs. personal use matter here? What if I plan to switch in the morning or at midnight on the first solstice after the second alpha release? Is Mercury or Venus in retrograde? These things matter... :) Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From cjt22 at bath.ac.uk Tue Sep 11 04:08:39 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Tue, 11 Sep 2007 01:08:39 -0700 Subject: Using a time duration to print out data where every 2 seconds is a pixel In-Reply-To: <6hice3hjf9r8tv6ru5pm7rhldge0cd3pra@4ax.com> References: <1189427545.322679.260970@r29g2000hsg.googlegroups.com> <1189436278.456311.128260@22g2000hsm.googlegroups.com> <6hice3hjf9r8tv6ru5pm7rhldge0cd3pra@4ax.com> Message-ID: <1189498119.318745.242690@y42g2000hsy.googlegroups.com> On Sep 11, 8:58 am, Tim Roberts wrote: > cj... at bath.ac.uk wrote: > >Thanks however I am still having a problem using the time module for > >arithmetic > > >My string times are of values such as 09:55:17 > > >and I have code such as: > > >>from time import * > >>startPoint = strptime(step.sTime, "%H:%S:%M") > >>finishPoint = strptime(step.fTime, "%H:%S:%M") > > Your conversion strings cannot be correct. Sure, there are international > differences in rendering dates and times, but not even in Eastern > WhereTheHeckIsStan do they encode hours, then seconds, then minutes. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. Sorry I meant %H:%M:%S just wrote it wrong! Any advice on how to print out the duration though would be much appreciated. I think I have now got the time conversion problems sorted thanks to the help from google groups! From vijayeee at gmail.com Wed Sep 5 07:15:44 2007 From: vijayeee at gmail.com (vijayca) Date: Wed, 05 Sep 2007 11:15:44 -0000 Subject: Looping through File Question In-Reply-To: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> References: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> Message-ID: <1188990944.650558.153230@22g2000hsm.googlegroups.com> On Sep 5, 3:58 pm, planetmatt wrote: > I am a Python beginner. I am trying to loop through a CSV file which > I can do. What I want to change though is for the loop to start at > row 2 in the file thus excluding column headers. > > At present I am using this statement to initiate a loop though the > records: > > for line in f.readlines(): > > How do I start this at row 2? just use readline() method...this will move the file pointer to the next line.... example: fd=open("/tmp.txt","r") fd.readline() ##THIS MOVES THE FILE POINTER TO THE SECOND LINE now carry on with... for line in f.readlines(): #THIS WILL BEGIN WITH THE SECOND ROW AS THE FILE POINTER IS IN 2NDLINE .... From michele.simionato at gmail.com Wed Sep 19 23:11:04 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 20 Sep 2007 03:11:04 -0000 Subject: Mixin classes and single/multiple inheritance (was: super() doesn't get superclass) In-Reply-To: <877immvye0.fsf_-_@benfinney.id.au> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> <877immvye0.fsf_-_@benfinney.id.au> Message-ID: <1190257864.945639.199230@k79g2000hse.googlegroups.com> On Sep 20, 4:55 am, Ben Finney wrote: > Michele Simionato writes: > > I am not against mixins (even if I am certainly very much against > > the *abuse* of mixins, such as in Zope 2). What I would advocate > > (but I realize that it will never happen in Python) is single > > inheritance + mixins a la Ruby. > > For those unfamiliar with Ruby, could you explain how you see this > being done in Python? I don't see this being done in Python, it is too late now (for backward compatibility and all that). But you can still do it by yourself, the simplest thing being copying the methods of the mixin class. It is already possible to use a syntax like this class MyClass(Base): mixin(Mixin1, Mixin2, ...) using P.J. Eby's trick for implementing what he calls class decorators (see also http://www.phyast.pitt.edu/~micheles/python/classinitializer.html) But I would not use it, let's use the language we have, not to invent our own. > What do you see as an appropriate use of mixin classes, and what an > abuse? An example of fine usage of mixin is Tkinter; an example of bad usage if Zope 2. In any case, I think using composition in the end is a better solution than mixins (it is much more scalable). > What would the semantics be in Python for "single inheritance + mixins > a la Ruby"? Can you give example syntax? > Already done. Since all hierarchies would be flat, super syntax would be trivial as in Ruby/Java/etc (self.super.meth(args, kw)). Michele Simionato From bbxx789_05ss at yahoo.com Mon Sep 24 04:57:05 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Sep 2007 01:57:05 -0700 Subject: vim - what's a smarttab? Message-ID: <1190624225.926815.149720@50g2000hsm.googlegroups.com> Is smarttab one of these: 1) Expands tabs into the number of spaces set with tabstop at the start of a line, and uses a tabstop sized tab elsewhere. 2) Expands tabs into the number of spaces set with shiftwidth at the start of a line, and expands tabs into the number spaces set with tabstop elsewhere. 3) Doesn't do any expanding: uses shiftwidth sized tabs at beginning of line, and tabstop sized tabs elsewhere. Alternatively, what is a smarttab? Thanks. From koutoo at hotmail.com Thu Sep 27 12:33:34 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Thu, 27 Sep 2007 09:33:34 -0700 Subject: True of False Message-ID: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> I tried writing a true and false If statement and didn't get anything? I read some previous posts, but I must be missing something. I just tried something easy: a = ["a", "b", "c", "d", "e", "f"] if "c" in a == True: Print "Yes" When I run this, it runs, but nothing prints. What am I doing wrong? Thanks. Kou From gdi.promoter at gmail.com Thu Sep 20 02:01:38 2007 From: gdi.promoter at gmail.com (GDI groups) Date: Wed, 19 Sep 2007 23:01:38 -0700 Subject: Income for life Message-ID: <1190268098.206437.10150@i13g2000prf.googlegroups.com> Hi, all I'm recommended GDI website http://www.globalrichonline.com/ You can make the money online 100% Good day. From steve at holdenweb.com Fri Sep 28 13:57:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 13:57:57 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191000394.828693.285210@k79g2000hse.googlegroups.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> <1190997769.002795.59450@57g2000hsv.googlegroups.com> <5m4qc2Fbbk19U1@mid.uni-berlin.de> <1191000394.828693.285210@k79g2000hse.googlegroups.com> Message-ID: <46FD40A5.8030504@holdenweb.com> TheFlyingDutchman wrote: > On Sep 28, 10:01 am, Marc 'BlackJack' Rintsch wrote: >> On Fri, 28 Sep 2007 09:42:49 -0700, TheFlyingDutchman wrote: >>> Which of the common languages have higher order functions and what is >>> the syntax? >> C, C++, Pascal, Perl, PHP, Ruby have them. And of course the functional >> languages, most notably Lisp and Scheme as you asked for common languages. >> >> Don't know if C#'s delegates qualify. >> >> Ciao, >> Marc 'BlackJack' Rintsch > > What is the syntax of a higher order function in C, C++ and Pascal? > This is like listening to a four-year-old torment its parents with incessant questions. Do you *have* to ask every question that pops into your mind? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From f.guerrieri at gmail.com Mon Sep 10 03:55:33 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 10 Sep 2007 09:55:33 +0200 Subject: concise code (beginner) In-Reply-To: <13e9taoa44icgb4@corp.supernews.com> References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> <13e99756io95p66@corp.supernews.com> <13e9taoa44icgb4@corp.supernews.com> Message-ID: <79b79e730709100055v50839390g28848e5e9d920d00@mail.gmail.com> On 9/10/07, bambam wrote: > > I have a number of news readers here, but all of them work > better with top-posting, and in none of them is top posting > a problem. What software are you using? > > Steve. > I use gmail and I can assure you that top posting is annoying. francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From techwr-l-bounces at lists.techwr-l.com Mon Sep 17 20:49:27 2007 From: techwr-l-bounces at lists.techwr-l.com (techwr-l-bounces at lists.techwr-l.com) Date: Mon, 17 Sep 2007 18:49:27 -0600 Subject: You have been unsubscribed from the TECHWR-L mailing list Message-ID: We're sorry to see that you're leaving TECHWR-L. If there is anything you believe TECHWR-L should have offered but didn't, or if there are any other suggestions you may have for the list, please feel free to write directly to us. TECHWR-L Administrators admin at techwr-l.com From paddy3118 at googlemail.com Sat Sep 15 11:58:59 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 15 Sep 2007 15:58:59 -0000 Subject: regexp search on infinite string? In-Reply-To: <1189861667.962508.76850@57g2000hsv.googlegroups.com> References: <1189802940.518794.129130@r29g2000hsg.googlegroups.com> <1189860966.073168.33840@50g2000hsm.googlegroups.com> <1189861667.962508.76850@57g2000hsv.googlegroups.com> Message-ID: <1189871939.267407.114000@n39g2000hsh.googlegroups.com> On Sep 15, 2:07 pm, John Machin wrote: > On Sep 15, 10:56 pm, Paddy wrote: > > > > > On Sep 14, 9:49 pm, Paddy wrote: > > > > Lets say i have a generator running that generates successive > > > characters of a 'string'>From what I know, if I want to do a regexp search for a pattern of > > > > characters then I would have to 'freeze' the generator and pass the > > > characters so far to re.search. > > > It is expensive to create successive characters, but caching could be > > > used for past characters. is it possible to wrap the generator in a > > > class, possibly inheriting from string, that would allow the regexp > > > searching of the string but without terminating the generator? In > > > other words duck typing for the usual string object needed by > > > re.search? > > > > - Paddy. > > > There seems to be no way of breaking into the re library accessing > > characters from the string: > > > >>> class S(str): > > > ... def __getitem__(self, *a): > > ... print "getitem:",a > > ... return str.__getitem__(self, *a) > > ... def __get__(self, *a): > > ... print "get:",a > > ... return str.__get__(self, *a) > > ...>>> s = S('sdasd') > > >>> m = re.search('as', s); m.span() > > (2, 4) > > >>> m = sre.search('as', s); m.span() > > (2, 4) > > >>> class A(array.array): > > > ... def __getitem__(self, *a): > > ... print "getitem:",a > > ... return str.__getitem__(self, *a) > > ... def __get__(self, *a): > > ... print "get:",a > > ... return str.__get__(self, *a) > > ... > > > >>> s = A('c','sdasd') > > >>> m = re.search('as', s); m.span() > > (2, 4) > > >>> m = sre.search('as', s); m.span() > > (2, 4) > > > - Paddy. > > That would no doubt be because it either copies the input [we hope > not] or more likely because it hands off the grunt work to a C module > (_sre). Yes, it seems to need a buffer/string so probably access a contiguous area of memory from C. o > > Why do you want to "break into" it, anyway? A simulation generates stream of data that could be gigabytes from which I'd like to find interesting bits by doing a regexp search. I could use megabyte length sliding buffers, and probably will have to. - Paddy. From orsenthil at gmail.com Mon Sep 3 14:12:11 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Mon, 3 Sep 2007 23:42:11 +0530 Subject: 400 Bad Request calling urllib2.urlopen() In-Reply-To: <1188824817.761125.190520@k79g2000hse.googlegroups.com> References: <1188824817.761125.190520@k79g2000hse.googlegroups.com> Message-ID: <20070903181211.GB5077@gmail.com> > I have an url which redirects the client to another url. If I paste > the url into a browser, it works fine. If I open it via Any redirection is setup using either of the 301, 302, 303, 307 return codes of HTTP. Atleast, thats what standard determines. > File "C:\Python25\lib\urllib2.py", line 575, in http_error_302 > return self.parent.open(new) Here we see that redirect handler http_error_302 has taken effect. > File "C:\Python25\lib\urllib2.py", line 499, in http_error_default > raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) > urllib2.HTTPError: HTTP Error 400: Bad Request The redirected page is not getting fetched by the OpenerDirector of urllib2. This could be due to various reasons. - the protocol is unsupported. - there is some prevention from accessing the resource directly. If its possible, can you share the url which is throwing this error? To me, it does seem urllib2 issue, it could be the (improper ??) redirection setup at webserver. > -- > http://mail.python.org/mailman/listinfo/python-list -- O.R.Senthil Kumaran http://uthcode.sarovar.org From kskuhlman at gmail.com Tue Sep 25 21:41:31 2007 From: kskuhlman at gmail.com (Ken Kuhlman) Date: Wed, 26 Sep 2007 01:41:31 -0000 Subject: Best way to do attribute docstrings? In-Reply-To: <1189540345.260656.115760@q5g2000prf.googlegroups.com> References: <1189195567.238990.54440@57g2000hsv.googlegroups.com> <1189540345.260656.115760@q5g2000prf.googlegroups.com> Message-ID: <1190770891.044084.123540@50g2000hsm.googlegroups.com> Replying to myself in case someone finds this interesting. Anyway, I took another shot at this with a little fresher mind, and it was quickly obvious that I was trying to force attributes to behave more like classes. It was a small step from there to creating a factory function to return instances of the appropriate class. I'm much happier with the result than either of the two previously posted kludges. # A factory function for generating attributes that can be annotated. def attr(value, doc=None): base = type(value) if base == bool: # bool class can't be used as a base, so we make one that can. class MyBool(int): def __str__(self): return str(bool(self)) __repr__ = __str__ base = MyBool class FancyAttr(base): pass fa = FancyAttr(value) fa.__doc__ = doc return fa class Animal(object): four_legs = attr(value = True, doc = "Animal has four legs") favorite_food = attr('cheese', doc = "Animal's favorite food") has_fur = attr(False) has_fur.__doc__ "Animal has fur" print Animal.four_legs.__doc__, '::', Animal.four_legs print Animal.favorite_food.__doc__, '::', Animal.favorite_food print Animal.has_fur.__doc__, '::', Animal.has_fur From fakeaddress at nowhere.org Sun Sep 2 03:49:26 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 02 Sep 2007 07:49:26 GMT Subject: So what exactly is a complex number? In-Reply-To: References: <451mq4-les.ln1@ozzie.tundraware.com> Message-ID: Tim Daneliuk wrote: > Grzegorz S?odkowicz wrote: [...] >> You're mixing definition with application. You didn't say a word about >> what complex numbers are, not a word about the imaginary unit, where > > I was trying to motivate the idea by means of analogy. This is a > legitimate thing to do. It helps lead people to a conceptual understanding > long before they understand the minutae. I am well aware of the > imaginary unit and from whence complex analysis springs. I just didn't > think that was the best place to start explicating the *concept*. Gotta side with Grzegorz on this. Simplifying an explanation of complex numbers to the point of omitting the imaginary unit helps lead people to a conceptual *misunderstanding*. I don't like feeling confused, but where I really screw up is where I think I understand what I do not. -- --Bryan From deets at nospam.web.de Mon Sep 3 08:22:14 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Sep 2007 14:22:14 +0200 Subject: TypeError: 'module object is not callable' References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> Message-ID: <5k2cjmF1r2aiU1@mid.uni-berlin.de> christophertidy at hotmail.com wrote: > Thank you for your help that seems to have done the trick. > You are correct Diez B. Roggisch that I come from a java background! > > I have a new tiny problem I can't understand either. > Withing Step.py I have the following method > > def isCompleted(self): > "Check whether data step has been processed" > return self.isCompleted > > Then within main.py I simply wish to print the value of isCompleted > which I try to do by the following > print 'Magn completed status is',a.isCompleted() > > Which returns the following error: > a.isCompleted() > TypeError: 'int' object is not callable > > I have tried ideas such as int(a.isCompleted) but to no prevail. Any > ideas? The others spottet the error I missed. But I can offer something else: http://dirtsimple.org/2004/12/python-is-not-java.html It's a worthy read for someone coming from Java, needing time to adjust. Diez From f.guerrieri at gmail.com Tue Sep 18 15:10:10 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Tue, 18 Sep 2007 21:10:10 +0200 Subject: Newbie question In-Reply-To: <1190139661.046103.45440@19g2000hsx.googlegroups.com> References: <1190139661.046103.45440@19g2000hsx.googlegroups.com> Message-ID: <79b79e730709181210m72a39ea7xa0aeed9dcfa44f20@mail.gmail.com> On 9/18/07, koutoo at hotmail.com wrote: > If I have a file name: AVC1030708.14. How do I strip out certain > characters from the file name? I am so used to using MID, LEFT, and > RIGHT functions, that I have no idea how to do this in python? I have > had trouble as well with most newbies on finding the help. But I have > used the command line built in help, but with no luck. Thanks. > > Kou As a newbie, you would do well to read and study the tutorial which you can find at http://docs.python.org/tut/tut.html In particular there is an interesting section on Strings: http://docs.python.org/tut/node5.html#SECTION005120000000000000000 and http://docs.python.org/lib/string-methods.html Francesco From aboudouvas at panafonet.gr Mon Sep 3 06:19:40 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 03 Sep 2007 03:19:40 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <87tzqc9jda.fsf@benfinney.id.au> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1188803759.498517.198900@g4g2000hsf.googlegroups.com> <87tzqc9jda.fsf@benfinney.id.au> Message-ID: <1188814780.980563.158150@57g2000hsv.googlegroups.com> I was wondering (and maybe i still do) about this GIL "problem". I am relatively new to Python (less than a year) and when i started to think about it i said: "Oh, this IS a problem". But when i dig a little more, i found that "Ah, maybe it isn't". I strongly believe that the best usage of multiple cores processor will be achieved if programming languages are modified to support this on their "hearts". Code blocks that would be identified by the compiler and run in parallel and such things. Laboratories are working on these stuff but i do not expect something in the very-near future. So, as i mentioned above, there are solutions for that right now ("parallel python" and others) that enabled us with little effort to spawn a new python interpreter, thus allowing the OS to schedule it on a different core and do the job this way relatively cheap. I wouldn't recommend going to IronPython despite the fact that the CLR better utilize MP. The reason for this is that i would NEVER give up the freedom that CPython gives me by exchange "better" usage of the MP and platform lock-in. From steve at REMOVE-THIS-cybersource.com.au Sun Sep 16 08:53:30 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 12:53:30 -0000 Subject: generate list of partially accumulated values References: <1189936564.932553.148800@50g2000hsm.googlegroups.com> <1189936979.276166.103080@w3g2000hsg.googlegroups.com> <1189937183.100462.175070@o80g2000hse.googlegroups.com> <1189938119.469599.171960@w3g2000hsg.googlegroups.com> Message-ID: <13eq9qak4pbqr3f@corp.supernews.com> On Sun, 16 Sep 2007 10:21:59 +0000, cesco wrote: > The list is composed of objects: > l = [obj1, obj2, obj3, obj4] > and I need to call a method (say method1) on each object as follow: l1 = > [obj1.method1(obj2), obj2.method1(obj3), obj3.method1(obj4), obj4] > > Is there a clean way of doing this? Yes, write a function that loops over the list doing what you want. Not everything needs to be a one-liner. -- Steven. From cai.haibin at gmail.com Wed Sep 26 18:56:51 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 26 Sep 2007 22:56:51 -0000 Subject: regex with specific list of string In-Reply-To: References: <1190821357.753909.178210@50g2000hsm.googlegroups.com> <1190827835.3397.76.camel@dot.uniqsys.com> Message-ID: <1190847411.999166.87060@w3g2000hsg.googlegroups.com> Hi all, > This is fine IMO since the OP didn't specify the opposite. > Thanks for all your replies, though I don't understand quite well the going argument? What do you mean when you say "the OP didn't specify the opposite"? There reason for using regex is because I am going to use it in Django's URL pattern Thanks james From jjl at pobox.com Sat Sep 22 03:27:56 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 22 Sep 2007 07:27:56 GMT Subject: frange() question References: <87tzppjhe4.fsf@pobox.com> Message-ID: <87lkaz40sj.fsf@pobox.com> Carsten Haese writes: > On Thu, 2007-09-20 at 18:55 +0000, John J. Lee wrote: >> Functions are never generators, senso stricto. There are "generator >> functions", which *return* (or yield) generators when you call them. > > Actually, a generator function is a function that returns a generator. Read what I wrote again. What makes you begin your sentence with "Actually", rather than "Putting it another way"? [...snip more sensible stuff I must assume was directed at the OP...] John From bronger at physik.rwth-aachen.de Thu Sep 6 18:42:53 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 07 Sep 2007 00:42:53 +0200 Subject: why should I learn python References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <1189117798.506367.278560@y42g2000hsy.googlegroups.com> Message-ID: <874pi7tnyq.fsf@wilson.homeunix.com> Hall?chen! windandwaves writes: > On Sep 7, 9:50 am, James Stroud wrote: >> Seewww.python.org. Trust us all when we say that its the best. >> > > I get that feeling - yes. Question is: > > 1. what is it good for? > 2. why is it so good? Your questions are very general. I think it is best to do some Internet research on it instead of asking in newsgroups. Newsgroups or web forums become interesting when you have more specific questions. When I chose my new favourite language 2.5 years ago, I also used Goggle for it. There is a lot of material about Python out there. You may start on Wikipedia, and you may look for "Python v. another-language" pages. They are often very informative. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From jscrerar at compuserve.com Sat Sep 29 18:17:49 2007 From: jscrerar at compuserve.com (Jim) Date: Sat, 29 Sep 2007 15:17:49 -0700 Subject: Command-line does work when scheduled In-Reply-To: References: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> Message-ID: <1191104269.578536.56470@g4g2000hsf.googlegroups.com> On Sep 29, 3:19 pm, "Gabriel Genellina" wrote: > En Sat, 29 Sep 2007 17:34:34 -0300, Jim escribi?: > > > I want to schedule a Python program that reads the command line for > > input. However, when adding an argument to the command line Python > > will not pick it up when using Windows scheduled tasks. > > > How do I get it to work? > > Do you write the command line when defining the task? Using double quotes > around arguments with spaces? > It works fine for me. > > -- > Gabriel Genellina I ran the following on the Scheduled Tasks: "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py" n "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py n" "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py" "n" None of them work. However, no problem with running from *.bat file or directly from shortcut on my Desktop. Thanks, Jim From cjt22 at bath.ac.uk Mon Sep 10 08:32:25 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Mon, 10 Sep 2007 05:32:25 -0700 Subject: Using a time duration to print out data where every 2 seconds is a pixel Message-ID: <1189427545.322679.260970@r29g2000hsg.googlegroups.com> Hi there, I wonder if any of you could tell me the best way to going about solving this little problem! I have a list of Step objects containing their start and finish times The steps are sorted so that they are in order of their step times The start and finish times are in string format of "%H:%S:%M" all on the same day I want to be able print out the Steps as a visual representation so that I can show 1. The order the steps started 2. The duration of the steps i.e. a print out such as: [ a ] [ b ] [ c ] so: [ stepName ] is the duration of the Step (i.e. 1 pixel for every 2 seconds it lasted) [ a ] started first so it is printed first, [ b ] started x seconds later so it is printed y pixels tabbed away form the side etc etc Any help would be much appreciated. Another related question is that I can't seem to do arithmetic when the variables are in String format of %H:%M:%S or converted to type struct_time i.e. > startPoint = strptime(step.sTime, "%H:%S:%M") > finishPoint = strptime(step.fTime, "%H:%S:%M") > duration = finishPoint - startPoint generates a error: Type error: unsupport operand types for: 'time.struct_time' and 'time.struct_time' trying to do time arithmetic when the times are stored in this format as strings also fails so any help regarding any of this would be muhc appreciated From BjornSteinarFjeldPettersen at gmail.com Thu Sep 20 03:50:20 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Thu, 20 Sep 2007 07:50:20 -0000 Subject: Sets in Python In-Reply-To: <1190260923.243865.312190@z24g2000prh.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <13f3m15igkstq2e@corp.supernews.com> <1190260923.243865.312190@z24g2000prh.googlegroups.com> Message-ID: <1190274620.912027.322880@50g2000hsm.googlegroups.com> On Sep 20, 6:02 am, Karthik Gurusamy wrote: > On Sep 19, 7:17 pm, Steven D'Aprano [...] > > (2) Allow the hash of mutable objects to change, which means you can use > > mutable objects as keys in dicts but if you change them, you can no > > longer find them in the dict. They'll still be there, using up memory, > > but you can't get to them. > > In the new model, at the time of addition, you need to remember the > key at that time. If it's a list, you make a copy of the items. Eek! Barf! Gag me with a spoon! etc. etc. :-) And you mean a deep-copy, not just a copy, right? Or perhaps you were thinking of something like this (mdict ::= mutable dict): class mdict(dict): def __setitem__(self, k, val): super(mdict,self).__setitem__(`k`, val) def __getitem__(self, k): return super(mdict,self).__getitem__(`k`) def __contains__(self, k): return super(mdict,self).__contains__(`k`) def keys(self): return list(eval(k) for k in super(mdict,self).keys()) def __iter__(self): for k in super(mdict,self).__iter__(): yield eval(k) def items(self): return list((eval(k),v) for k,v in super(mdict,self).items()) def __repr__(self): items = ', '.join('%s: %s' % (k,repr(v)) for k,v in self.items()) return '{' + items + '}' I think it does what you want..?: >>> m = mdict() >>> a, b = [], [1,2] >>> print m {} >>> m[a] = a >>> m[b] = b >>> m {[1, 2]: [1, 2], []: []} >>> m.keys() [[1, 2], []] >>> for k in m: ... m[k].append('foo') ... >>> m {[1, 2]: [1, 2, 'foo'], []: ['foo']} >>> m.items() [([1, 2], [1, 2, 'foo']), ([], ['foo'])] >>> m.values() [[1, 2, 'foo'], ['foo']] >>> a in m False >>> a ['foo'] >>> b [1, 2, 'foo'] >>> [] in m True >>> [1,2] in m True >>> m[{'key':['val']}] = 'this works too' It'll work for all keys, k, where eval(`k`) == k, and repr(a) == repr(b) when a == b (I'm pretty sure the latter isn't always true for dicts, although I haven't looked at the implementation.) -- bjorn From cjw at sympatico.ca Mon Sep 17 20:15:44 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 17 Sep 2007 20:15:44 -0400 Subject: Use GUI for Python In-Reply-To: <1190044523.666991.273910@y42g2000hsy.googlegroups.com> References: <1190043073.093736.272750@k79g2000hse.googlegroups.com> <1190044523.666991.273910@y42g2000hsy.googlegroups.com> Message-ID: <46EF18B0.1060505@sympatico.ca> Jason wrote: > On Sep 17, 9:31 am, kou... at hotmail.com wrote: >> I am new to python as I have been a VB programmer. I am used to the >> GUI interface, and was wondering if I had to choose between a GUI for >> Python, which one should I go with? Thanks. >> >> Kou > > You need to be more specific. Do you mean that you are used to > working in an IDE environment, where you can readily access the list > of classes, methods, and such? You might be interested in Eclipse > [1], then installing the PyDev [2] plug-in to add Python support. > Wing-IDE [3] and Komodo [4] may also be very suitable (but they cost > money). > > If you mean that you want to develop programs with a GUI interface, > then you have a number of choices [5]. Most of these choices do not > work in the same way that Microsoft Studio's GUI designer works, > partly because Python isn't tied to any of them. > o wxWidgets is MFC-like > o PyQT and PyGTK are similar to their underlying interfaces > o Tkinter comes with the default Python install, and provides the > Tk widget set > o With IronPython, you can access the regular Microsoft .NET GUIs > o PythonCard and EasyGUI are supposed to be pretty easy GUIs to use > o Dabo is a full-on database/GUI/platform set to easy cross- > platform GUI and database programming. > > The links to all those can be found at link [5]. Don't be afraid if > the choices are overwhelming. You have choices. I highly recommend > that you learn Python first, then examine the different GUI systems, > keeping in mind any requirements you may have and your previous > experience. > > [1] http://www.eclipse.org/ > [2] http://pydev.sourceforge.net/ > [3] http://wingware.com/ > [4] http://www.activestate.com/products/komodo_ide/ > [5] http://wiki.python.org/moin/GuiProgramming > If you are looking for a good IDE and you are in the Windows World, have a look at PyScripter. It is in development and the developer gives an excellent response to any queries or potential bugs. Colin W. From mail at timgolden.me.uk Tue Sep 11 08:58:26 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Sep 2007 13:58:26 +0100 Subject: shared memory pointer In-Reply-To: <1189437684.476993.130390@g4g2000hsf.googlegroups.com> References: <1189436265.841415.234050@w3g2000hsg.googlegroups.com> <1189437684.476993.130390@g4g2000hsf.googlegroups.com> Message-ID: <46E690F2.9060306@timgolden.me.uk> Tim wrote: > I saw the mmap function in the shared memory example. I had some > concern with my large memory size being written to the disk drive. I > though it might slow down my application. The reason I am writting > this new code is because the existing method using a file. I thought > shared memory would be much faster. > > I have tried using the memcpy and addresses, casting, etc. Is there a > way to use memcpy with the pData returned by MapViewOfFile()? Tim, let's try to back up on this a moment. As I understand, you're running under Windows and you want to use shared memory, presumably between two processes. You know about the CreateFileMapping/MapViewOfFile API, possibly from this example on MSDN [1] and you want to use that technique in Windows *without* an explicit file backing. Am I right so far? I suggested the mmap module, and you seemed to pick up on it and be trying to use both your ctypes solution *and* the mmap module as two halves of the same mechanism. Maybe I misunderstood, but that's what it looked like. Then you asked a question about getting hold of a Python object's memory address to be able to pass it into your ctypes solution. (Which makes sense, given the nature of that solution). What you seem to have missed is that your ctypes code is doing *exactly* what the mmapmodule.c code (which is the implementation of the mmap module) is doing for you behind the scenes. Here's your code (very slightly reformatted): szName = c_char_p(name) hMapObject = windll.kernel32.CreateFileMappingA( INVALID_HANDLE_VALUE, None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName ) if (hMapObject == 0): print "OpenKey: Could not open name file mapping object" raise WinError() self.pData = windll.kernel32.MapViewOfFile( hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE ) and here's the code from mmapmodule.c (also reformatted and snipped about): m_obj->map_handle = CreateFileMapping( m_obj->file_handle, NULL, flProtect, size_hi, size_lo, m_obj->tagname ); if (m_obj->map_handle != NULL) { m_obj->data = (char *) MapViewOfFile( m_obj->map_handle, dwDesiredAccess, 0, 0, 0 ); I hope you can see that they're basically doing the same thing. (given the appropriate parameters). The only clear difference is that the final param to MapViewOfFile is 0 in the Python code, which the MSDN docs[2] indicate "If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping." It's not clear from that how it applies to a non-file-backed FileMapping, but I *assume* that the Python devs have tested that out. In short, to have two Python processes talk via shared memory (not linking to a specific file) the following works for me: import mmap # # The 0 special file value can be -1 in Python 2.5 # shmem = mmap.mmap (0, 1000, "TJG", mmap.ACCESS_WRITE) shmem.write ("blah blah") import mmap shmem = mmap.mmap (0, 1000, "TJG", mmap.ACCESS_WRITE) print shmem.read (9) Obviously, I've used dummy codes and values, but since the .write and .read (and the other helper methods) use strings, you can always pickle or marshal arbitrary Python data to move it around. I hope all that's helpful; if nothing else, it's given me some exercise in reading the code of the stdlib, which can't be bad! TJG [1] http://msdn2.microsoft.com/en-us/library/aa366551.aspx [2] http://msdn2.microsoft.com/en-us/library/aa366761.aspx From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Sep 13 14:54:29 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 13 Sep 2007 20:54:29 +0200 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> Message-ID: <5ktfb5F5ctrvU1@mid.individual.net> OKB (not okblacke) wrote: What kind of name is this? > No, but the point being made is that it would be better IN > THIS CASE. It wouldn't. IMHO, rewriting the code to two or three lines would be better. No need to scream, BTW. Regards, Bj?rn -- BOFH excuse #447: According to Microsoft, it's by design From bignose+hates-spam at benfinney.id.au Mon Sep 17 22:07:39 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 18 Sep 2007 12:07:39 +1000 Subject: Why 'class spam(object)' instead of class spam(Object)' ? References: <46e10916$0$16518$4c368faf@roadrunner.com> Message-ID: <87d4wg20b8.fsf@benfinney.id.au> [Colin, you posted your message to both of 'comp.lang.python' and 'gmane.comp.python.general'. The latter is merely a view on the former, and your message appears in exactly the same places if you post only to 'comp.lang.python'.] "Colin J. Williams" writes: > > Carl Banks wrote: > >> The reason why "object" is lower case is because built-in types > >> are spelled in lower-case. > Does the user care whether an object is implemented in C? Probably not. But they probably do care that the type is built-in. -- \ "The trouble with the rat race is that even if you win, you're | `\ still a rat." -- Jane Wagner, via Lily Tomlin | _o__) | Ben Finney From dstanek at dstanek.com Thu Sep 6 05:00:12 2007 From: dstanek at dstanek.com (David Stanek) Date: Thu, 6 Sep 2007 05:00:12 -0400 Subject: Autogenerate functions (array of lambdas) In-Reply-To: <1189067829.685339.50550@y42g2000hsy.googlegroups.com> References: <1189067829.685339.50550@y42g2000hsy.googlegroups.com> Message-ID: On 9/6/07, Chris Johnson wrote: > > What I want to do is build an array of lambda functions, like so: > > a = [lambda: i for i in range(10)] > > (This is just a demonstrative dummy array. I don't need better ways to > achieve the above functionality.) > > print [f() for f in a] > > results in: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] > rather than the hoped for: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > Clearly, lambda is returning the object i, which is left at the last > value of range(10). The following is my solution. > > t = lambda i: lambda: i > a = [t(i) for i in range(10)] > > or the somewhat more terse: > > a = [(lambda i: lambda: i)(i) for i in range(10)] > > This gives the behavior which, intuitively, I expected from the > original syntax. So my questions are: > 1) Does this make sense as what should be done here? That is, would > this be the behavior you'd want more often than not? As I said, > intuitively, I would think the lambda would treat the iterator > variable as a constant in this context. > 2) Is there a better or preferred method than the one I've found? A more explicit example of your solution would be: >>> def gen(i): ... return lambda: i # bind to the i passed in ... >>> l = [gen(i) for i in range(10)] >>> [f() for f in l] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Your initial lambda: i creates a function that binds to i in the current scope. When you wrapped that in another lambda you were creating a new scope with a new value of i and returning a function bound to that value for i. Take a look at closures: http://www.ibm.com/developerworks/linux/library/l-prog2.html#h1 http://ivan.truemesh.com/archives/000392.html David -- http://www.traceback.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexandre.badez at gmail.com Thu Sep 27 11:46:55 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Thu, 27 Sep 2007 15:46:55 -0000 Subject: Launching command on windows In-Reply-To: <1190902803.222738.52050@w3g2000hsg.googlegroups.com> References: <1190899078.141370.116190@57g2000hsv.googlegroups.com> <1190902803.222738.52050@w3g2000hsg.googlegroups.com> Message-ID: <1190908015.102664.323390@w3g2000hsg.googlegroups.com> On Sep 27, 4:20 pm, kyoso... at gmail.com wrote: > > I got it to work using subprocess.Popen > > Not sure why it doesn't work with os.system though. > > Mike Thanks Mike and Mauro, Mauro, your solution do not seems to work (or I made a mistake..) Mike your solution work great, thanks. But, I steel think it's a bug (python or window ??). I will try to take a look about it, when I have time. Alex From guruyaya at gmail.com Sun Sep 16 06:06:45 2007 From: guruyaya at gmail.com (guruyaya) Date: Sun, 16 Sep 2007 03:06:45 -0700 Subject: Half off topic, getting python development lib from mingw Message-ID: <1189937205.093048.238900@k79g2000hse.googlegroups.com> Hi guys. I'm using python 2.3 on XP. At the moment, I might add, I cannot change any of these: I cannot move back to linux, and I cannot use a higher version of python. Trying to install sip 4.7, using gcc version 3.4.2 (mingw-special), created this error: siplib.o:siplib.c:(.text+0x17): undefined reference to `_imp__PyType_Type' that led me to understand, that I just didn't install the mingw port of python development libs. That's cool, but I just can't find it anywhere. Anyone has a link? From gherzig at fmed.uba.ar Wed Sep 5 09:38:50 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Wed, 05 Sep 2007 10:38:50 -0300 Subject: Help me understand this script In-Reply-To: References: Message-ID: <46DEB16A.5060200@fmed.uba.ar> Ryan J Nauman wrote: >Can someone help me understand this script please? >I understand everything except for the anagram function. Could you break >it down into more than 1 line of code for me or explain it? (I understand >WHAT it does but HOW?) Thanks. > >Script >> > >### ># SCRABBLE.PY ># ># purpose: ># find usable "bingos" based on your rack ># ># usage: ># python scrabble.py eilsnsy ># ># output: ># Straight anagrams: ># linseys ># lysines ># Possible other words: ># + B ># sensibly >#+ K ># skylines >#+ V ># sylvines >### ># Scrabble is a registered trademark of J. W. Spear & Son PLC and ># Hasbro Inc. Any and all uses of the word "Scrabble" in this code ># refers to this trademark. ># ># This code is not affiliated with any company. >### > >import sys > >WORDS = [ i.rstrip ().lower() for i in file ('c:\python25\TWL06.txt') ] ># you can download the current TWL and/or SOWPODS dictionaries from ># http://67.19.18.90/twl.zip and http://67.19.18.90/sowpods.zip . ># Update the file name above as appropriate if you want to use a "proper" ># Scrabble dictionary. > > > >def alphabetise(word): > x = [i for i in word] > x.sort() > > return "".join(x) > >def anagram(word): > wordLength = len(word) > sortedWord = alphabetise(word.lower()) > return [i for i in WORDS if len(i) == wordLength and alphabetise(i) == >sortedWord] > >for word in sys.argv[1:]: > print "Straight anagrams: " > for i in anagram(word): > print " " + i > print "Possible other words: " > for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": > a = anagram(i + word) > if a: > print "+", i > for h in a: > print " ", h > ><< End script > > I guess the difficult part remains in the last line. (Untested code bellow) [code] def anagram(word): resultValue = [] wordLength = len(word) sortedWord = alphabetise(word.lower()) #not much to change until here for WORD in WORDS: if wordLength == len(WORD) and alphabetise(WORD) == sortedWord: resultValue.append(WORD) return resultValue [/code] Cheers. Gerardo From bbxx789_05ss at yahoo.com Mon Sep 17 11:54:06 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 17 Sep 2007 08:54:06 -0700 Subject: curses: x, y positioning In-Reply-To: <1190044252.770768.241100@w3g2000hsg.googlegroups.com> References: <1189891633.622313.81850@r29g2000hsg.googlegroups.com> <1190035292.415363.22320@50g2000hsm.googlegroups.com> <1190044252.770768.241100@w3g2000hsg.googlegroups.com> Message-ID: <1190044446.102835.323950@n39g2000hsh.googlegroups.com> On Sep 17, 9:50 am, 7stud wrote: > Ok. This works: > > import curses > import curses.wrapper Oops. That second import statement isn't necessary. From mridula.ccpl at gmail.com Fri Sep 28 07:41:35 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Fri, 28 Sep 2007 17:11:35 +0530 Subject: Bug: spurious indentation error Message-ID: <33dffc910709280441p14f78175n8549bdb315416328@mail.gmail.com> hi. is this the right place to report a bug? i had written this by mistake: filemenu = Menu(menu) , bg="White") instead of filemenu = Menu(menu, bg="Pink") and the compiler kept giving me an indentation error in a line much further down which was perfectly okay. i am using python 2.5.1 with IDLE 1.2.1 on a windows XP machine. anyone else struggling with the same thing, beware! :) -mridula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From daniel.j.larsson at gmail.com Tue Sep 4 17:52:37 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Tue, 4 Sep 2007 23:52:37 +0200 Subject: doctest and decorators In-Reply-To: <200709042316.08263.python@cx.hu> References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> <200709042236.37712.python@cx.hu> <2bfa72fa0709041401g63e5f6aem55bcabe9e00134b@mail.gmail.com> <200709042316.08263.python@cx.hu> Message-ID: <2bfa72fa0709041452o72d9a98fp939852d061a2cda3@mail.gmail.com> On 9/4/07, Ferenczi Viktor wrote: > > > @functools.wraps > > Correctly: > > @functools.wraps(f) > > Pass the function to be wrapped by the decorator to the wraps function. Ooops, right. That doesn't change the fact that decorated functions get hidden from doctest though. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jgardner.jonathangardner.net at gmail.com Thu Sep 6 16:52:34 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Thu, 06 Sep 2007 20:52:34 -0000 Subject: parsing long `To' and 'Cc' from email In-Reply-To: References: Message-ID: <1189111954.287203.123440@o80g2000hse.googlegroups.com> On Sep 6, 1:25 pm, Gerardo Herzig wrote: > the email.* package dont seems to parse that kind of headers > `correctly'. What i want is to get a list with all the email address in > the `To' header. > > Someone know if there is a more sofisticated parser for doing this? > If you're not interested in parsing the entire email message, you may just want to run a regex on the message itself, looking for the "to" header. Here's a good start: r"^to:\s*(.*)$" You'll want to use the multi-line and case-insensitive options when you use it. From jweida at gmail.com Sat Sep 1 22:48:57 2007 From: jweida at gmail.com (Jerry) Date: Sun, 02 Sep 2007 02:48:57 -0000 Subject: Automation and scheduling of FrontPage publishing using Python In-Reply-To: <1188698223.393723.151140@d55g2000hsg.googlegroups.com> References: <1188517723.279932.299400@x40g2000prg.googlegroups.com> <1188698223.393723.151140@d55g2000hsg.googlegroups.com> Message-ID: <1188701337.798785.188420@19g2000hsx.googlegroups.com> andrew, I would try looking into Windows automation with Python. http://www.google.com/search?q=windows+automation+python should get you started. The winGuiAuto package may help you out as it is like have a human click and move throughout the interface. The only downside is that there is no recorder to help you build the script, so I would try to do as much in VBA as you can (does FrontPage even support VBA?) and then just write your python script to get through the program enough to execute the macro. From bj_666 at gmx.net Mon Sep 24 08:25:35 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Sep 2007 12:25:35 GMT Subject: rules from an xml file References: <1190633685.275142.264540@r29g2000hsg.googlegroups.com> <5lpm4dF93534U1@mid.uni-berlin.de> Message-ID: <5lpolvF95s07U4@mid.uni-berlin.de> On Mon, 24 Sep 2007 13:42:05 +0200, Diez B. Roggisch wrote: > jonny wrote: > >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> Something is wrong! >> >> >> ... >> ... >> >> [?] > [?] > Just a note: the use of "par_X" as attributes is unfortunate, to say the > least. It doesn't allow for easy argument swapping, can cause troubles > because you delete one attribute and miss renaming the others, and in > general it's not good design to have arbitrary numbers of parameters. Quite the same is true for numbers in tag names. If you (the OP) need to number the rules better use an attribute for the numbers. Ciao, Marc 'BlackJack' Rintsch From jstroud at mbi.ucla.edu Mon Sep 24 15:49:55 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 24 Sep 2007 12:49:55 -0700 Subject: Nested For and While Statements In-Reply-To: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> Message-ID: koutoo at hotmail.com wrote: > I start my code with some constants then a while statement. But I > have some For statements towards the end within the While statement > where I start getting some errors. I'm hoping I won't have to post my > code, but it looks something like this: > > Import os, string > > while this: > > All Code indented like it should > > > Last line in While. > > For i in range(1) > class = [] > class2 = [] > For i in range(2) > Do this > And this > And that. > > Next Line hits snag here? Where should this line > be? > Your for loops both use the same counting index. From grante at visi.com Tue Sep 18 12:00:11 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 18 Sep 2007 16:00:11 -0000 Subject: How can I know how much to read from a subprocess References: <1190070896.332844.23080@22g2000hsm.googlegroups.com> <1190072376.600475.254260@y42g2000hsy.googlegroups.com> <1190130585.255648.312730@q3g2000prf.googlegroups.com> Message-ID: <13evtgbv6aqtf0@corp.supernews.com> On 2007-09-18, spam.noam at gmail.com wrote: > But even if it's fast enough, how do you know how many times you > should call read(1)? If you do it too much, you'll be blocked until > more output is available. You don't know. That's why you use non-blocking mode. -- Grant Edwards grante Yow! BELA LUGOSI is my at co-pilot ... visi.com From paddy3118 at googlemail.com Fri Sep 14 02:37:49 2007 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 14 Sep 2007 06:37:49 -0000 Subject: Extended slicing and Ellipsis - where are they used? In-Reply-To: References: <1189699345.436400.233460@g4g2000hsf.googlegroups.com> Message-ID: <1189751869.773724.165040@w3g2000hsg.googlegroups.com> On Sep 14, 1:50 am, James Stroud wrote: > Rodney Maxwell wrote: > > The following are apparently legal Python syntactically: > > L[1:3, 8:10] > > L[1, ..., 5:-2] > > > But they don't seem to work on lists: > >>>> l = [0,1,2,3] > >>>> l[0:2,3] > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: list indices must be integers > >>>> l[...] > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: list indices must be integers > > > So where is this extended slicing used? > > AFAICT this syntax is not used in the standard library. However, the > mega-beauty of it is that you can make use of it in your own classes: > > py> class Bob(list): > ... def __getitem__(self, i): > ... try: > ... return [list.__getitem__(self, j) for j in i] > ... except TypeError: > ... return list.__getitem__(self, i) > ... > py> b = Bob(xrange(15, 30)) > py> b[3, 5, 7, 13] > [18, 20, 22, 28] > > James And the ellipses ... ? - Paddy. From gandalf at designaproduct.biz Thu Sep 13 07:29:06 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 13 Sep 2007 13:29:06 +0200 Subject: wx.ToplevelWindow.SetIcon: Native MS Windows error dialog pops up in wxPython app, no exception raised, no stack trace Message-ID: <46E91F02.7080806@designaproduct.biz> Hello, I wrote a small program that works uses wxPython. The same application works on Linux and Windows. When I start it from MS Windows, I see this error message appearing each time I open a window: --------------------------- Warehouseclient Error --------------------------- Can't load image from file '': file does not exist. --------------------------- OK --------------------------- The message box itself is a native MS Windows dialog. Otherwise the program works fine, just here is this annoying message. There is no exception raised in the Python program. Nothing printed on console. I figured out that this happens only when I set the icon of the window using this code: self.SetIcon(icon) However, the error dialog is not displayed right after the SetIcon call and no exception is raised. The dialog is displayed after __init__ has been called, and probably before EVT_SHOW gets called. Documentation of SetIcon (http://wxwidgets.org/manuals/stable/wx_wxtoplevelwindow.html#wxtoplevelwindowseticon) says that it is safe to delete the icon after calling this function. Now here are the wreid things: 1. The icon is displayed correctly in the left top corner, so where is the error? 2. The error message complains about a file. What has wx.ToplevelFrame.SetIcon do with files? I'm using: Windows XP Professional, Python 2.5, wxPython 2.8 Thanks, Laszlo From namesagame-usenet at yahoo.com Thu Sep 13 07:03:17 2007 From: namesagame-usenet at yahoo.com (gamename) Date: Thu, 13 Sep 2007 04:03:17 -0700 Subject: Python+Expect+Win32 = Not Possible? In-Reply-To: <1189672955.321701.164050@57g2000hsv.googlegroups.com> References: <1189657637.539038.317280@k79g2000hse.googlegroups.com> <1189672955.321701.164050@57g2000hsv.googlegroups.com> Message-ID: <1189681397.349994.126130@57g2000hsv.googlegroups.com> On Sep 13, 1:42 am, half.ital... at gmail.com wrote: > On Sep 12, 9:27 pm, gamename wrote: > > > Hi, > > > Is it still the case there is no practical Expect-like module for > > win32? I know that cygwin can support pexpect, but that isn't an > > option here --- I have to use a native win32 Python version. > > > Are there alternatives, or is it simply not an option to replicate > > Expect on win32 with python? > > > All I'm trying to do is start a couple processes, wait for each to say > > "done" on stdout and then quit (or timeout if something went wrong). > > > TIA, > > -T > > I had planned on using telnet to do the same thing on windows. I > don't think I ever proved it, but I'm pretty sure it will work. Thanks, Sean. The problem is that telnet is generally disabled on most hosts nowadays. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52228 > > ~Sean From furkankuru at gmail.com Sat Sep 22 06:28:40 2007 From: furkankuru at gmail.com (Furkan Kuru) Date: Sat, 22 Sep 2007 13:28:40 +0300 Subject: calling the function of one class from another class In-Reply-To: <33dffc910709220024l74b14267v93564df10f5af9a6@mail.gmail.com> References: <33dffc910709220024l74b14267v93564df10f5af9a6@mail.gmail.com> Message-ID: <3a4a8f930709220328h1ae25d10jd772e265cd298bcd@mail.gmail.com> On 9/22/07, Mridula Ramesh wrote: > > hi. > > i currently have code structured like this: > > classA(): > > def __init__(): > > .............. > > .............. > > > > def fnc1(): > > .................... > > .................... > > > > > > classB(): > > def __init__(): > > ........................ > > ........................ > > classA.fnc1() #this is where i get an error > > > > TypeError: unbound method fnc1() must be called with classA instance as > first argument (got nothing instead) > > when i do fnc1(classA) i get: > > NameError: global name 'fnc1' is not defined > > am i violating some programming rule by trying to call fnc1 in classB? i > am only now learning OO alongside python, so i'm not sure! also, can someone > please tell me where to go for more articles on the classes and functions > and calling them from other places? > > thanks a lot! > > mridula. > > -- > http://mail.python.org/mailman/listinfo/python-list > you should create an instance of ClassA: a = ClassA() a.fnc1() or if you want a static function you should declare the method as static classA(): def __init__(): .............. .............. @staticmethod def fnc1(): .................... .................... -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Wed Sep 19 23:41:46 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 20 Sep 2007 13:41:46 +1000 Subject: Mixin classes and single/multiple inheritance References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> <877immvye0.fsf_-_@benfinney.id.au> <1190257864.945639.199230@k79g2000hse.googlegroups.com> Message-ID: <87tzpquhol.fsf@benfinney.id.au> Michele Simionato writes: > Ben Finney wrote: > > What do you see as an appropriate use of mixin classes, and what > > an abuse? > > An example of fine usage of mixin is Tkinter; an example of bad > usage if Zope 2. Which parts of those two very large code sets do I need to look at to see the examples you have in mind? I was hoping you could demonstrate with short code examples. -- \ "One thing vampire children have to be taught early on is, | `\ don't run with a wooden stake." -- Jack Handey | _o__) | Ben Finney From bronger at physik.rwth-aachen.de Thu Sep 6 02:02:33 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 06 Sep 2007 08:02:33 +0200 Subject: Wanted: safe codec for filenames References: <87sl5tcrw9.fsf@wilson.homeunix.com> <87ps0w92ki.fsf@wilson.homeunix.com> Message-ID: <871wdcz5za.fsf@wilson.homeunix.com> Hall?chen! Gabriel Genellina writes: > En Wed, 05 Sep 2007 19:20:45 -0300, Torsten Bronger > escribi?: > >> Torsten Bronger writes: >> >>> I'd like to map general unicode strings to safe filename. I >>> tried punycode but it is case-sensitive, which Windows is not. >>> [...] >> >> Okay, the following works fine for me: > > Nice codec. Altough if one is looking for really portable file > names, there are additional rules, collected here > http://www.boost.org/libs/filesystem/doc/portability_guide.htm > Hard to comply with all the character set rules *and* keep all name > lengths below the limits. Yes, and therefore, a *very* careful encoding was not an option. For my own application, I need long filenames for example. So I used a Wikipedia table to find a sensible compromise. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From deets at nospam.web.de Thu Sep 6 03:21:08 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 06 Sep 2007 09:21:08 +0200 Subject: Using wild character In-Reply-To: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> Message-ID: <5k9o3gF2n8u0U1@mid.uni-berlin.de> Sreeraj schrieb: > hi, > > I am a beginner in Python. I wish to know how can i filter a list of > strings using wild characters.ie > Lets say i have list countries = > ["india","africa","atlanta","artica","nigeria"]. I need only the list > of string starting with 'a'. While the startswith-method others pointed out works, I wanted to direct you attention to the module fnmatch. http://www.python.org/doc/current/lib/module-fnmatch.html It will work with real wildcards. Diez From fakeaddress at nowhere.org Sat Sep 22 11:13:22 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Sep 2007 15:13:22 GMT Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <46f49740$0$32514$4c368faf@roadrunner.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> Message-ID: Carl Banks wrote: > Not many people are bit-fiddling these days. One of the main uses of bit > fields is flags, but that's not often done in Python because of keyword > arguments and dicts, which are lot more versatile. Another major use, > talking to hardware, is not something oft done in Python either. [...] > Of course I'm not suggesting to get rid of bitwise operations altogether; > just make them builtin functions: "x & 1" becomes "bitwise_and(x,1)" and > so on. Based on one informal survey (of my recollection), many Pythoneers bit-twiddle, and all of them also know C. For this population, Python's adoption of C's bitwise operators helps avoid user-out-of-memory errors. Python even kept C's counter-intuitive low precedence for shifts. One surprising result was that more of the Python programmers surveyed use bitwise operators than are aware of the exponentiation operator, which C does not offer. Possibly the study used a bias sample. -- --Bryan From yosuke at ccwf.cc.utexas.edu Mon Sep 17 18:10:30 2007 From: yosuke at ccwf.cc.utexas.edu (yosuke at ccwf.cc.utexas.edu) Date: Mon, 17 Sep 2007 22:10:30 +0000 (UTC) Subject: class that keeps track of instances Message-ID: Hello all, I'd like some advices from more experienced python users. I want to have a class in my python application that does not allow multiple instance with same "name". I want to have a class (call it kls) that behave at least following way: 1) New instance has to have a property called 'name' 2) When instance is attemped to created, e.g., x=kls(name='myname'), and there already exists an instance with obj.name =='myname', that pre-existing instance is returned, instead of making new one. 3) A class property 'all' for class gives me a list of all the instances. So kls.all lets me iterates through all instances. 4) When all the hard-link to an instance is deleted, the instance should be deleted, just like an instance from any regular class does. My question is if i can find metaclass or something that allows me to create such class easily. I tried to search such thing on internet, but I even don't know how to call this kind of thing. It is in a sense like singleton, but less restrictive. Assuming that I have to write it on my own, what should I do? I tried to implement it using weakref.WeakValueDictionary and metaclass, but instance doesn't disappear when I think it should disappear. I am also wondering if it is easier to keeping {name:id(obj)} would be a better solution. Any other suggestions are very much appreciated as well. -- yosuke kimura Center for Energy and Environmental Resources The Univ. of Texas at Austin, USA From stephane.larouche at polymtl.ca Mon Sep 24 13:56:04 2007 From: stephane.larouche at polymtl.ca (=?utf-8?b?U3TDqXBoYW5l?= Larouche) Date: Mon, 24 Sep 2007 17:56:04 +0000 (UTC) Subject: Can a base class know if a method has been overridden? References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> <46f7d897$0$25150$426a74cc@news.free.fr> <1190648887.051630.168520@r29g2000hsg.googlegroups.com> <46f7e8df$0$21052$426a74cc@news.free.fr> Message-ID: What about something like: class A(object): def my_method(self): print "A.my_method" def call_my_method(self): if type(self).my_method == A.my_method: print "Calling base class method." else: print "Calling derived class method." self.my_method() class B(A): pass class C(A): def my_method(self): print "C.my_method" a = A() b = B() c = C() a.call_my_method() b.call_my_method() c.call_my_method() St?phane From effigies at gmail.com Thu Sep 6 11:46:42 2007 From: effigies at gmail.com (Chris Johnson) Date: Thu, 06 Sep 2007 15:46:42 -0000 Subject: Autogenerate functions (array of lambdas) In-Reply-To: <7xr6lc6v49.fsf@ruckus.brouhaha.com> References: <1189067829.685339.50550@y42g2000hsy.googlegroups.com> <7xr6lc6v49.fsf@ruckus.brouhaha.com> Message-ID: <1189093602.253138.147650@50g2000hsm.googlegroups.com> On Sep 6, 3:44 am, Paul Rubin wrote: > Chris Johnson writes: > > a = [lambda: i for i in range(10)] > > print [f() for f in a] > > results in: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] > > rather than the hoped for: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > The usual idiom is > > a = [lambda i=i: i for i in range(10)] > > That way i is not a free variable in the lambda. Thanks. I figured there had to be a better way than what I was doing. From jgardner.jonathangardner.net at gmail.com Thu Sep 6 19:08:35 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Thu, 06 Sep 2007 23:08:35 -0000 Subject: SSL Issue In-Reply-To: References: Message-ID: <1189120115.915370.307810@57g2000hsv.googlegroups.com> On Sep 5, 10:47 pm, Harry George wrote: > Jurian Botha writes: > > Sorry if this is a real dumb question, but I'm totally stumped. > > > I'm trying to connect to a https url in order to do some xml-rpc method > > calls, but I'm getting the following error: > > > Error Type: sslerror > > Error Value: (6, 'TLS/SSL connection has been closed') > > > What could be causing this error, any clues would be greatly appreciated. > > > Thanks > > -- > > View this message in context:http://www.nabble.com/SSL-Issue-tf4388062.html#a12510772 > > Sent from the Python - python-list mailing list archive at Nabble.com. > > I don't have a complete story, but here are some hints: > > 1. The message is from:http://www.openssl.org/docs/ssl/SSL_get_error.html > (see "ZERO RETURN") > probably as filtered by > PyOpenSSL, which has its own issues:http://mail.python.org/pipermail/python-dev/2007-August/074322.html > > 2. Chances are that your certificates are out of whack, or you are > misusing the SSL context parameters, or are not telling the HTTP > Connection object about the SSL Connection properly. > > 3. Debugging at the python layer is easier (put print statements in > M2Crypto's SSL/Context and SSL/Connection) but if necessary, dive into > openssl: > http://www.mail-archive.com/openssl-us... at openssl.org/msg49287.html > > 4. You can check for the "hello" handshake using WireShark. > > 5. I haven't found a tutorial for full Python client/server over HTTPS > with verification of both client and server certificates. If that is > where you are going, let me know what works. > Try the "openssl s_client :" command to get some handy info on what is happening. It's kind of like telnet but for SSL. This will help isolate SSL issues from the Python layer. From bh at izb.knu.ac.kr Sun Sep 30 09:35:06 2007 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Sun, 30 Sep 2007 22:35:06 +0900 Subject: Can you please give me some advice? In-Reply-To: <46ff7b44$0$4798$4fafbaef@reader4.news.tin.it> References: <46ff7b44$0$4798$4fafbaef@reader4.news.tin.it> Message-ID: <1191159306.2127.13.camel@viola.izb.knu.ac.kr> On Sun, 2007-09-30 at 12:33 +0200, morphine wrote: > Byung-Hee HWANG wrote: > > > Hi there, > > > > What is different between Ruby and Python? I am wondering what language > > is really mine for work. Somebody tell me Ruby is clean or Python is > > really easy! Anyway I will really make decision today what I have to > > study from now on. > > What kind of advice do you expect on a NG called comp.lang.PYTHON ? ^^^^^^^^ Your advice is the best.. really it hit my head very strongly.. > > > What I make the decision is more difficult than to > > know why I have to learn English. Yeah I do not like to learn English > > because it is just very painful.. > > Then stop learning it ;) ^^^^^^^^^^^^^^^^^^^^^^^ You are bad.. I'm really pain.. sorry for noise.. but I really wanted to say about the above matters.. From jjl at pobox.com Thu Sep 20 15:18:25 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 20 Sep 2007 19:18:25 GMT Subject: Python tickets summary References: Message-ID: <87hclpjgce.fsf@pobox.com> "Facundo Batista" writes: [...] > Based on an idea from Dennis Benzinger, now the temporal bars show the > moments where each comment was made, so it's easy to see the "rhythm" > of the ticket activity: > > http://www.taniquetil.com.ar/facundo/py_tickets.html I like that. I've often scrolled up and down tickets trying to get a sense of what your display tells you at a glance. John From garywlee at gmail.com Sun Sep 16 08:28:48 2007 From: garywlee at gmail.com (GaryLee) Date: Sun, 16 Sep 2007 05:28:48 -0700 Subject: Can't see the arguements when use Python in WSH. Message-ID: <1189945728.024735.3960@w3g2000hsg.googlegroups.com> Hi, Folks: I am using Python in WSH. However, I got a strange problem on my computer. Here is a small program to show the problem. # xxx.pys objArgs = WScript.Arguments for i in xrange(objArgs.Count()): WScript.Echo(objArgs(i)) WScript.Echo('Total %d arguments.' % objArgs.Count()) If I execute this document by following command, the objArgs.Count() always return 0 and no argument was included. > xxx.pys 1 2 3 4 Because, the script will show "Totals 0 arguments", the program can be executed normally. It just can't get the arguments. However, if I use following command to execute the script. I can get the arguments. > wscript.exe xxx.py 1 2 3 4 If I drag some documents and drop them onto the icon of xxx.pys file, it still can't get the arguments. I am sure that the DropHandler has been set properly. Finally, I use a wsf file to embeded the same script file. It looks like this: blah blah This wsf file can work very well. When I drop some files onto it, it can show the path of those documents. However, I just want to know why my pys file can't work. Does anyone have the same situation? Is it my pywin32 package corrupted? I've downloaded the last pywin32 package and executed the site-packages\win32comext\axscript\client\pyscript.py to register the PyScript. But, the problem is still there. Sincerely yours, Gary From rhamph at gmail.com Fri Sep 7 12:46:00 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 07 Sep 2007 16:46:00 -0000 Subject: concise code (beginner) In-Reply-To: <1189108607.080926.103650@19g2000hsx.googlegroups.com> References: <13dsvqrqivtf092@corp.supernews.com> <1189020188.842700.50950@d55g2000hsg.googlegroups.com> <1189108607.080926.103650@19g2000hsx.googlegroups.com> Message-ID: <1189183560.572177.56930@r34g2000hsd.googlegroups.com> On Sep 6, 1:56 pm, Karthik Gurusamy wrote: > That said, it may be a good future language enhancement to define a > reasonable consistent behavior for an iterator over a changing > collection. This occurs quite common when we walk a collection and > usually delete the current item. > > For a sequence, what the expected behavior is quite obvious (just > remove this element and go over to the next). For other collections > like dictionary/set, again if the operation is delete, the expected > behavior is obvious. If we are doing insertion, for sequence a well- > defined behavior can be formulated (based on insert before or after > current position -- if after we will see it in the walk, if before we > won't see it) . For dict/set I see this isn't simple (as based on hash > key we may insert ahead or later of the current 'cursor'/position. Removing from a list while you iterate will had quadratic performance though. O(n) to find the element you wish to remove and move over everything after it, multiplied by your original O(n) of iterating, gives O(n**2). That, combined with the fact that adding enough accounting to invalidate or update your iterator would be a cost on all the correct users too, is why it's not done. The best approach in almost all cases in python is to create a new container as you iterate over the old one. After you finish, you replace the old one with the new one. This lets you keep an overall O(n) performance, as well as avoiding the tricky semantics. -- Adam Olsen, aka Rhamphoryncus From llothar at web.de Sun Sep 2 22:16:19 2007 From: llothar at web.de (llothar) Date: Sun, 02 Sep 2007 19:16:19 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> Message-ID: <1188785779.956824.143860@w3g2000hsg.googlegroups.com> On 3 Sep., 07:38, "Eduardo O. Padoan" wrote: > > No.http://www.artima.com/weblogs/viewpost.jsp?thread=211430 > > Ops, I meant:http://www.artima.com/forums/threaded.jsp?forum=106&thread=211200 > Thanks. I whish there would be a project for rewritting the C interpreter to make it better and more useable for threading use. But the CPU infrastructure is also not perfect enough so maybe it's good to wait with this a few more years until Intel and AMD know what they are doing. From gregpinero at gmail.com Mon Sep 24 17:22:40 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Mon, 24 Sep 2007 21:22:40 -0000 Subject: subprocess -popen - reading stdout from child - hangs In-Reply-To: <1190530682.420121.31520@y42g2000hsy.googlegroups.com> References: <1190518129.356844.242710@19g2000hsx.googlegroups.com> <1190530682.420121.31520@y42g2000hsy.googlegroups.com> Message-ID: <1190668960.766658.235070@g4g2000hsf.googlegroups.com> On Sep 23, 2:58 am, Karthik Gurusamy wrote: > On Sep 22, 8:28 pm, "gregpin... at gmail.com" > wrote: > > > Let's say I have this Python file called loop.py: > > > import sys > > print 'hi' > > sys.stdout.flush() > > Add sys.stdout.close() > Adding sys.stdout.close() and removing sys.stdout.flush() seems to make it work. But can the while loop still use sys.stdout later on? Do I have to reopen it? Thanks, Greg From sergio.correia at gmail.com Fri Sep 7 02:30:00 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Fri, 7 Sep 2007 01:30:00 -0500 Subject: Why 'class spam(object)' instead of class spam(Object)' ? Message-ID: Hi, I'm kinda new to Python (that means, I'm a total noob here), but have one doubt which is more about consistency that anything else. Why if PEP 8 says that "Almost without exception, class names use the CapWords convention", does the most basic class, object, is lowercase? I found a thread about this: http://mail.python.org/pipermail/python-list/2007-April/437365.html where its stated that -object- is actually a type, not a class; but the idea still doesn't convince me. If i create a class Spam using -object- as a parent class, I would expect -object- to be a class, not a type as in type(object) (what is the difference between both btw?). But, on the other hand, if I do help(object), I get: >>> help(object) Help on class object in module __builtin__: class object | The most base type So is this a class? No... >>> object My doubts get compounded when strange stuff starts to happen: >>> class Eggs(object): def __init__(self): self.x = 1 >>> type(Eggs) Type 'type'? What is that supposed to mean? Hope this makes any sense ;), Sergio From arkanes at gmail.com Wed Sep 5 10:36:51 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 5 Sep 2007 09:36:51 -0500 Subject: Checking if elements are empty In-Reply-To: References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> Message-ID: <4866bea60709050736t5f9f6759x4a8b685bc9ad4ec@mail.gmail.com> On 9/5/07, Steve Holden wrote: > Doran, Harold wrote: > > > > Is there a way to check if the first element of y is null? > > > > len(y[0]) == 0 > > would be the obvious way, assuming "null" means "the null string". > Better spelled as if y[0]: From ivoras at _fer.hr_ Thu Sep 13 09:53:45 2007 From: ivoras at _fer.hr_ (Ivan Voras) Date: Thu, 13 Sep 2007 15:53:45 +0200 Subject: Parallel/Multiprocessing script design question In-Reply-To: References: Message-ID: Amit N wrote: > About 800+ 10-15MB files are generated daily that need to be processed. The > processing consists of different steps that the files must go through: > > -Uncompress > -FilterA > -FilterB > -Parse > -Possibly compress parsed files for archival You can implement one of two easy straightforward approaches: 1 - Create one program, start N instances of it, where N is the number of CPUs/cores, and let each process one file to completion. You'll probably need an "overseer" program to start them and dispatch jobs to them. The easiest is to start your processes with first N files, then monitor them for completion and when any of them finishes, start another with the next file in queue, etc. 2 - Create a program / process for each of these steps and let the steps operate independently, but feed output from one step to the input of the next. You'll probably need some buffering and more control, so that if (for example) "FilterA" is slower then "Uncompress", the "Uncompress" process is signaled to wait a little until "FilterA" needs more data. The key is that, as long as all the steps run at approximatly the same speed, they can run in parallel. Note that both approaches are in principle independent on whether you use threads or processes, with the exception of communication between the steps/stages, but you can't use threads in python if your goal is parallel execution of threads. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 257 bytes Desc: OpenPGP digital signature URL: From software at ginstrom.com Wed Sep 5 04:44:47 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Wed, 5 Sep 2007 17:44:47 +0900 Subject: Printing lists in columns In-Reply-To: <1188979665.052672.211110@r34g2000hsd.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com><46dbd11e$0$6228$426a74cc@news.free.fr><1188816626.021956.281040@22g2000hsm.googlegroups.com><5k2cjmF1r2aiU1@mid.uni-berlin.de><1188836008.656284.76160@o80g2000hse.googlegroups.com><46dc6f49$0$6207$426a34cc@news.free.fr><1188900397.459760.259580@k79g2000hse.googlegroups.com><1188906767.737741.267350@19g2000hsx.googlegroups.com><1188913394.763871.218660@d55g2000hsg.googlegroups.com><46dd69b1$0$24998$426a74cc@news.free.fr><1188917550.261894.84010@k79g2000hse.googlegroups.com><46ddbb26$0$18672$426a74cc@news.free.fr> <1188979665.052672.211110@r34g2000hsd.googlegroups.com> Message-ID: <011c01c7ef99$0447fd50$0303a8c0@MOUSE> > On Behalf Of cjt22 at bath.ac.uk > bo, daf, da > pres, ppar, xppc > magnjklep, *, dsa > *, *, nbi > > But I want it justified, i.e: > > bo , daf, da > pres , ppar, xppc > magnjklep, *, dsa > * , *, nbi Once you have a nice rectangular list of lists, you might want to take a look at my padnums module. # Usage: import padnums import sys table = [row for row in izip_longest(*d, fillvalue='*')] padnums.pprint_table(sys.stdout, table) Code described here, with link to module: http://ginstrom.com/scribbles/2007/09/04/pretty-printing-a-table-in-python/ Regards, Ryan Ginstrom From sean.pythonlist at gmail.com Fri Sep 28 18:38:40 2007 From: sean.pythonlist at gmail.com (sean tierney) Date: Fri, 28 Sep 2007 15:38:40 -0700 Subject: your opinion on book "Foundations of Python Network Programming"? In-Reply-To: <1191016773.834049.8940@19g2000hsx.googlegroups.com> References: <1191016773.834049.8940@19g2000hsx.googlegroups.com> Message-ID: <8cfa857a0709281538k3df9bd19yf1e54496d03f1319@mail.gmail.com> I just read it (though I bought it half a year ago...don't judge :). Author recommends Python 2.3 and above...and as far as I know the examples are good. And if anything IS outdated -- you'll be able to do some quick research to get you to where you need to be...and he does mention code several areas of change/addition/modification. (ie urllib and urllib2). He uses a couple of 3rd party projects too. I really liked the book. I think Goerzen did a good job. He addresses the code in the context of the problem the code is meant to solve, which I found helpful. That said, it's not a substitute for actually reading the code. ...if you haven't read the most recent edition of Programming Python by Mark Lutz (O'Reilly), I'd recommend that first. Programming Python covers (some) networking and everything else. More bang for the $$. Sean On 9/28/07, kf9150 at gmail.com wrote: > Hello, > > i'm debating if i should buy this book. it received good reviews at > Amazon: http://tinyurl.com/24zvrf. but it was published in 2004 and > i'm afraid quite some materials might be outdated? any input? > > thanks, > > kelie > > -- > http://mail.python.org/mailman/listinfo/python-list > From stefano.esposito87 at gmail.com Mon Sep 17 13:11:16 2007 From: stefano.esposito87 at gmail.com (Stefano Esposito) Date: Mon, 17 Sep 2007 19:11:16 +0200 Subject: How to assign a function to another function In-Reply-To: <87d4whnsnd.fsf@rudin.co.uk> References: <87d4whnsnd.fsf@rudin.co.uk> Message-ID: <20070917191116.603b7ec7.stefano.esposito87@gmail.com> On Mon, 17 Sep 2007 17:49:58 +0100 Paul Rudin wrote: > Stefano Esposito writes: > > > Hi all > > > > what i'm trying to do is this: > > > >>>>def foo (): > > ... return None > > ... > >>>>def bar (): > > ... print "called bar" > > ... > >>>>def assigner (): > > ... foo = bar > > ... > >>>>assigner() > >>>>foo() > > called bar > >>>> > > > > This piece of code is not working and even trying with... > > > > ... How can I achieve my goal? > > > By adding the line: > global foo > at the beginning of the body of assigner. > This worked, thanks a lot :) -- Stefano Esposito From f.guerrieri at gmail.com Sun Sep 30 11:48:56 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Sun, 30 Sep 2007 17:48:56 +0200 Subject: s.split() on multiple separators In-Reply-To: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> Message-ID: <79b79e730709300848l198cccb6r49636e6cba78fede@mail.gmail.com> On 9/30/07, mrkafk at gmail.com wrote: > Hello everyone, > > OK, so I want to split a string c into words using several different > separators from a list (dels). Have a look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303342 which contains several ways to solve the problem. You could both translate all your separators to a single one, and then split over it, or (maybe the simpler solution) going for the list comprehension solution. francesco From paul.hankin at gmail.com Wed Sep 26 09:59:40 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 26 Sep 2007 13:59:40 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <1190805297.182232.116830@50g2000hsm.googlegroups.com> Message-ID: <1190815180.945099.248670@n39g2000hsh.googlegroups.com> On Sep 26, 2:46 pm, Duncan Booth wrote: > Paul Hankin wrote: > > More flexibly, keep a set of inserted keys that haven't yet been > > included in the sorted list, and a set of deleted keys that haven't > > yet been removed from the sorted list. The cache is invalid if either > > of these sets are empty - and to make it valid you can choose what to > > do based on the sizes of the two sets (and the sorted list). For > > instance, if there's just been one insertion you're probably better > > doing an insertion rather than a full resort. Of course, there's a few > > nasty cases here but it's always possible to just throw away the > > sorted list and reconstruct it from the dict keys when things get too > > hairy (eg, the user deletes a key that's in the inserted-but-not-yet- > > sorted set). > > Yes that sounds good. Did you mean 'The cache is invalid if either of > these sets is not empty'? Yes :) > If you delete a key which is in the inserted set you can simply delete > it from the inserted set. No, in case it was already in the sorted list before the insert. You have to remove it from the inserted set AND add it to the deleted set. -- Paul Hankin From bjorn.kempen at gmail.com Sun Sep 16 06:06:23 2007 From: bjorn.kempen at gmail.com (buffi) Date: Sun, 16 Sep 2007 10:06:23 -0000 Subject: generate list of partially accumulated values In-Reply-To: <1189936979.276166.103080@w3g2000hsg.googlegroups.com> References: <1189936564.932553.148800@50g2000hsm.googlegroups.com> <1189936979.276166.103080@w3g2000hsg.googlegroups.com> Message-ID: <1189937183.100462.175070@o80g2000hse.googlegroups.com> Uh... that turned out weird. Anyways, here goes again l = [1, 2, 3, 4] [sum(l[:x+1]) for x in xrange(len(l))] From kennytilton at optonline.net Sun Sep 30 20:22:47 2007 From: kennytilton at optonline.net (Ken Tilton) Date: Sun, 30 Sep 2007 20:22:47 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1191170325.947900.177850@50g2000hsm.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <13frd6vtarbee75@corp.supernews.com> <1191170325.947900.177850@50g2000hsm.googlegroups.com> Message-ID: Matthias Benkard wrote: >>So this has nothing to >>do with freedom in /any/ sense of the word, it has to do with a >>political agenda opposed to the idea of private property. > > > Freedom is inherently political, you know. You're condemning the FSF > for being political, although the FSF's stated purpose is a political > one. Oh, I missed that. I just saw something about software should be shared and programmers should be content with an hourly wage, not sales. kt -- http://www.theoryyalgebra.com/ "We are what we pretend to be." -Kurt Vonnegut From kostaspaxos at yahoo.gr Thu Sep 13 03:56:40 2007 From: kostaspaxos at yahoo.gr (Konstantinos Pachopoulos) Date: Thu, 13 Sep 2007 10:56:40 +0300 Subject: cannot declare global vars! Message-ID: <46E8ED38.6070204@yahoo.gr> Hi, i had posted earlier for not being able to declare global vars. No i followed the suggestions and created a class, but still the vars do not seem to have a global scope. I have tried pretty much everything. Any advice appreciated... Here: ======================================================== #!/usr/bin/env jython #imports ... class SVNLogs2DBParser: #svnLogging_ #dbTable_ #cmterID_ #projID_ #fileIDNumber_ #Commiter_ #Commit_ #StoredProject_ #ProjectVersion_ #entryList_ def __init__(self,svnLogging_=SVNLogging(SVN_REPOS),dbTable_=DBTablesHandler(),cmterID_=0,projID_=0, fileIDNumber_=0,Commiter_={},Commit_={},StoredProject_={},ProjectVersion_={},entryList_={}): pass #svnLogging_=SVNLogging(SVN_REPOS) #print "Connection established to SVN repository..." #dbTable_=DBTablesHandler() #cmterID_=0 #projID_=0 #fileIDNumber_=0 #Commiter_={} #Commit_={} #StoredProject_={} #ProjectVersion_={} #entryList_={} #reads all the revision logs (traversing them PIVOT at a time) and #processes each log entry def getLogsLoop(self): while svnLogging_.getCurrentRevisionNumber()!=svnLogging_.getLatestRevisionNumber(): entryList_=svnLogging_.getNextLogs(PIVOT); #print "Attempting to go over the HEAD revision..." for entry in self.entryList: print "processing new SVN entry..." processLogEntry(entry) entryList_.clear() #processes each log entry # #"entry" is of type SVNLogEntry. See SVNKit API #"changedPaths" is returned as a java.util.HashMap #with key strings (paths) and values SVNLogEntryPath objects #"entry.getDates()" returns a java.util.Date object def processLogEntry(self, entry): revision = int(entry.getRevision()) commiter = str(entry.getAuthor()) datetime = getTimeStamp(entry.getDate()) message = str(entry.getMessage()) changedPaths = entry.getChangedPaths() #array passed for updating the Commiter DB table Commiter_[0] = cmterID_ Commiter_[1] = commiter dbTable_.updateCommiterTable(Commiter_) #array passed for updating the Commit DB table Commit_[0] = projID_ Commit_[1] = datetime Commit_[2] = cmterID_ Commit_[3] = 0.0 Commit_[4] = "" #properties fileStats=getFileTypes(changedPaths) Commit_[5] = fileStats[0] Commit_[6] = fileStats[2] Commit_[7] = fileStats[1] Commit_[8] = fileStats[3] Commit_[9] = fileStats[4] dbTable_.updateCommitTable(self.Commit_) ProjectVersion_[0]=projID_ ProjectVersion_[1]=0.0 dbTable_.updateProjectVersionTable(ProjectVersion_) Project[0]=projID_ Project[1]="" Project[2]="" Project[3]="" Project[4]="" dbTable_.updateProjectTable(Project_) cmterID_+=1 projID_+=1 ##############################HELPER##METHODS############################### .... ##############################HELPER##METHODS############################### From bj_666 at gmx.net Thu Sep 6 04:02:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Sep 2007 08:02:13 GMT Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> Message-ID: <5k9qg5F2mrncU2@mid.uni-berlin.de> On Thu, 06 Sep 2007 15:44:57 +1000, bambam wrote: > def script(self) > def a0010(): global self; self.power_on([self.dev]); > def a0020(): global self; self.dev.addLog([self.name, ' started']); > def a0030(): global self; self.resetMinuteReg([self.dev]); > def a0040(): global self; self.disablePLmessages([self.dev]); > def a0050(): global self; self.dev.testH.writePLram((PL.BCAL12<<8)); What is this ``global self`` meant to do? And the first line is missing a colon at the end. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Mon Sep 10 09:57:14 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2007 13:57:14 GMT Subject: Using a time duration to print out data where every 2 seconds is a pixel References: <1189427545.322679.260970@r29g2000hsg.googlegroups.com> Message-ID: <5kl0pqF3vfqqU7@mid.uni-berlin.de> On Mon, 10 Sep 2007 15:48:44 +0200, A.T.Hofkamp wrote: > (I have seen references to a module called datetime, but I have never used such > a module so no idea what it is or where to get it). It's just an import away -- in the standard library. :-) Ciao, Marc 'BlackJack' Rintsch From rrr at ronadam.com Sat Sep 22 03:02:57 2007 From: rrr at ronadam.com (Ron Adam) Date: Sat, 22 Sep 2007 02:02:57 -0500 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <13f8unjjeqs5p97@corp.supernews.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <13f8unjjeqs5p97@corp.supernews.com> Message-ID: <46F4BE21.2050800@ronadam.com> Scott David Daniels wrote: > Cristian wrote: >> On Sep 21, 3:44 pm, Ron Adam wrote: >> >>> I think key may be to discuss names and name binding with your friend. > > Here's an idea: > > import math > > def sin_integral(start, finish, dx): > total = 0.0 > y0 = math.sin(start) > for n in range(1, 1 + int((finish - start) / float(dx))): > y1 = math.sin(start + n * dx) > total += (y0 + y1) > y0 = y1 > return total / 2. * dx > > > def cos_integral(start, finish, dx): > total = 0.0 > y0 = math.sin(start) > for n in range(1, 1 + int((finish - start) / float(dx))): > y1 = math.cos(start + n * dx) > total += (y0 + y1) > y0 = y1 > return total / 2. * dx > > generalize and separate the integration technique from the > function it integrates. How about this? It's based on the apple basic program example in How to Enjoy Calculus. Ron import math def integrate(fn, x1, x2, n=100): # Calculate area of fn using Simpson's rule. width = float(x2 - x1) / n area = fn(x1) if n % 2 != 0: # make sure its even n += 1 for n in range(1, n): x = x1 + n * width if n % 2 == 0: area += 2.0 * fn(x) else: area += 4.0 * fn(x) area += fn(x2) return area * (width / 3.0) def fn(x): return x**2 print "Area of fn:", integrate(fn, 0, 2) print "Area of cos fn:", integrate(math.cos, 1, 2) print "Area of sin fn:", integrate(math.sin, 1, 2) Area of fn: 2.66666666667 Area of cos fn: 0.0678264420216 Area of sin fn: 0.956449142468 From paul.hankin at gmail.com Tue Sep 25 17:33:23 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 25 Sep 2007 21:33:23 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190753722.026806.254530@d55g2000hsg.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> Message-ID: <1190756003.292096.71130@o80g2000hse.googlegroups.com> On Sep 25, 9:55 pm, Mark Summerfield wrote: > ... > class sorteddict(dict): > > ... > if self.__keys is None: > self.__keys = sorted(dict.keys(self), cmp=self.__cmp, > key=self.__key, > reverse=self.__reverse) You'd be better defining __keys like this: def __getkeys(self): if self.__keycache is None: self.__keycache = dict.keys(self) self.__keycache.sort(cmp=...) return self.__keycache __keys = property(__getkeys) and where you have 'self.__keys = None', either replace with 'self.__keycache = None' or more cleanly with a call to: def __invalidate_key_cache(self): self.__keycache = None to improve the code quality. -- Paul Hankin From deets at nospam.web.de Fri Sep 21 10:44:17 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Sep 2007 16:44:17 +0200 Subject: Remote Command a Python Script References: <1190384953.774277.249350@k79g2000hse.googlegroups.com> Message-ID: <5li3m1F8cdk0U1@mid.uni-berlin.de> Ulysse wrote: > Hello, > > I've installed Python 2.5 on my WRT54G Linksys Router. On this router > a script is executed. This script write a little Pickle database in > the router memory. > > I would like to write another Python script which will be able to : > > 1. Stop and start the remote script from my Windows Computer. At > present I use Putty to connect to the router by the SSL, then I > manually kill the python process. > > 2. Retrieve the little database located in router memory and backup it > on my Window PC. At present I use WinSCP (like FTP) to get the pickle > file. > > Can you help me with that (modules to use, useful code snippets) Check out pyro. Diez From hpepper at gmail.com Tue Sep 11 06:22:24 2007 From: hpepper at gmail.com (HowiPepper) Date: Tue, 11 Sep 2007 03:22:24 -0700 Subject: why should I learn python In-Reply-To: <1189506021.315340.108490@y42g2000hsy.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <1189506021.315340.108490@y42g2000hsy.googlegroups.com> Message-ID: <1189506144.628422.93260@w3g2000hsg.googlegroups.com> Sorry Nicolaas, I didn't mean to misspell your name! Regards, Howard From chaelon at gmail.com Sat Sep 22 21:09:01 2007 From: chaelon at gmail.com (chaelon at gmail.com) Date: Sun, 23 Sep 2007 01:09:01 -0000 Subject: find difference in days from YYYYMMDD to YYYYMMDD In-Reply-To: References: Message-ID: <1190509741.062389.232920@d55g2000hsg.googlegroups.com> On Sep 22, 5:37 am, Konstantinos Pachopoulos wrote: > Hi, > does any body now any such algorith? to find difference in days from > YYYYMMDD to YYYYMMDD? > Or just an algorithm, that converts YYYYMMDD to seconds since the epoch? > > Thanks Seen some complex answers here. Let's keep it dead simple. Use the datetime module to do the heavy lifting. Go to IDLE, write this. import datetime. Then start to write this: difference = datetime.date( and at that point IDLE will tell you to put in year,month,day. That's convenient. Do as IDLE asks, obey IDLE! Wind up with this (put date later in history first, here are two I've used): difference = datetime.date(2007,9,25) - datetime.date(1970,12,25) print difference 13419 days, 0:00:00 Hey now! Date math! Yeah! From gherzig at fmed.uba.ar Mon Sep 24 08:45:45 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 24 Sep 2007 09:45:45 -0300 Subject: database persistence with mysql, sqlite In-Reply-To: <1190502677.970811.181100@22g2000hsm.googlegroups.com> References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> Message-ID: <46F7B179.9050100@fmed.uba.ar> coldpizza wrote: >Hi, > >I want to run a database query and then display the first 10 records >on a web page. Then I want to be able to click the 'Next' link on the >page to show the next 10 records, and so on. > >My question is how to implement paging, i.e. the 'Next/Prev' NN >records without reestablishing a database connection every time I >click Next/Prev? Is it at all possible with cgi/mod_python? > >For example, in a NON-web environment, with sqlite3 and most other >modules, I can establish a database connection once, get a cursor >object on which I run a single 'SELECT * FROM TABLE' statement and >then use cursor.fetchmany(NN) as many times as there are still results >left from the initial query. > >How do I do the same for the web? I am not using any high-level >framework. I am looking for a solution at the level of cgi or >mod_python (Python Server Pages under Apache). To call >cursor.fetchmany(NN) over and over I need to pass a handle to the >database connection but how do I keep a reference to the cursor object >across pages? I use mysql and sqlite3 as databases, and I am looking >for an approach that would work with both database types (one at a >time). So far I have successfully used the following modules for >database access: sqlite3, mysqld, and pyodbc. > > Apache/cgi just dont work this way. When apache receives a new request (a cgi being called), it starts a new thread, it execute him, and gives the client some result. AND THEN KILL THE THREAD. Altough i never used it, what i think you need is fast cgi (fcgi), wich takes care of persistent connections to a web server. Cheers. Gerardo From whamil1 at entergy.com Wed Sep 12 10:39:41 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 12 Sep 2007 09:39:41 -0500 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189605843.866907.117370@w3g2000hsg.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB41@LITEXETSP001.etrsouth.corp.entergy.com> > From: Michele Simionato > > On Sep 12, 3:54 pm, Mark Summerfield > wrote: > > On 12 Sep, 13:46, Michele Simionato > > > > Actually I meant by key order, so insertion order doesn't matter at > > all. If you need a dictionary-like data structure that respects > > insertion order you could use a list of (key, value) tuples. > > > > Another respondent asked about use cases. > > > > I have found time and again that I needed (key, value) pairs where the > > key is some string that provides a representation for human readers > > and the value is some internal key (e.g., database ID) that the system > > uses internally. In these cases I often need to present the user with > > a list of items from which to choose and want to present them in > > sorted order. Naturally, I could use an ordinary dict and then do > > this: > > > > for string in sorted(d.keys()): > > process(string) > > > > But what happens when I need to do this a *lot* and when the number of > > items is hundreds or a few thousands? I'm having to sort again and > > again, since it is often the case that the items in the list changes > > during the runtime of the application. So my solution in C++ is to use > > an ordered dictionary (a map in C++ jargon), which in Python means I > > can simply write: > > > > for string in od.keys(): > > process(string) > > > > For your use case I would wrap a list [(key, value)] with a dict-like > object and I would use the bisect module in the standard library to > keep > the inner list ordered. Or subclass dict to carry along a sorted list of keys with it and return that when dict.keys() is called. Even better, only have .keys() sort the keys list when a key has been added to it since the last call. -- -Bill Hamilton From jcd at sdf.lonestar.org Tue Sep 11 06:41:51 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 11 Sep 2007 06:41:51 -0400 Subject: Modul (%) in python not like in C? In-Reply-To: References: <13ec37dri08s7a3@corp.supernews.com> Message-ID: <46E670EF.7020207@sdf.lonestar.org> Bryan Olson wrote: > Scott David Daniels wrote: > >> C, which was designed as a "high level assembly language," does not >> tightly define the results of / and % for negative numbers. Instead >> it defines the result for positive over positive, and constrains the >> result for the others. >> > > Not true. Here it is again: > > When integers are divided, the result of the / operator is > the algebraic quotient with any fractional part discarded.(87) > If the quotient a/b is representable, the expression > (a/b)*b + a%b shall equal a. > [...] > 87) This is often called ??truncation toward zero??. > > [International Standard ISO/IEC 9899:1999, Section 6.5.5 > Multiplicative operators, Paragraph 6 and footnote 87] > > > But C was around for a long time before the 1999 standard. C89, commonly called ANSI C, is still very commonly used in compilers, and K&R C goes back to 1972. Is truncation toward 0 the standard for K&R C as well? Cheers, Cliff From ldo at geek-central.gen.new_zealand Wed Sep 26 04:31:44 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 26 Sep 2007 20:31:44 +1200 Subject: database persistence with mysql, sqlite References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> <1190650748.590245.221490@n39g2000hsh.googlegroups.com> Message-ID: In message , Bryan Olson wrote: > coldpizza wrote: >> It turned out that the method above ('SELECT * FROM TABLE LIMIT L1, >> L2') works ok both with mysql and sqlite3, therefore I have decided to >> stick with it until I find something better. With Sqlite3 you are >> supposed to use LIMIT 10 OFFSET NN, but it also apparently supports >> the mysql syntax (LIMIT NN, 10) for compatibility reasons. > > A more reliable form is along the lines: > > SELECT keyfield, stuff > FROM table > WHERE keyfield > ? > ORDER BY keyfield > LIMIT 10 > > With the right index, it's efficient. But that involves keeping track of the right starting keyfield value for the next batch of records, which is complicated and nontrivial. Simpler to let the DBMS do the work for you. From oviedolilliam at gmail.com Mon Sep 17 14:59:40 2007 From: oviedolilliam at gmail.com (lilly) Date: Mon, 17 Sep 2007 18:59:40 -0000 Subject: Free trips around the globe!!!!!!!!!! In-Reply-To: <1190054010.350444.11150@19g2000hsx.googlegroups.com> References: <1190054010.350444.11150@19g2000hsx.googlegroups.com> Message-ID: <1190055580.004195.87900@k79g2000hse.googlegroups.com> On Sep 17, 2:33 pm, nutsbreak... at gmail.com wrote: > http://world-traveling-destinations.blogspot.com/ this is good From jUrner at arcor.de Thu Sep 13 21:35:08 2007 From: jUrner at arcor.de (=?iso-8859-1?q?J=FCrgen_Urner?=) Date: Thu, 13 Sep 2007 18:35:08 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: <7xps0mmig9.fsf@ruckus.brouhaha.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> Message-ID: <1189733708.659317.83950@y42g2000hsy.googlegroups.com> Puh, what a discussion... most common use case I can think of is >> d = {'a': 1, 'b': 2, 'c': 3} >> for key in d: >> # do something that relies on order of keys as specified in the constructor It's a bit tireing having to type >> for key in sorted(d.keys()): >> do_somethig_with(d[key]) instead of a trustfully >> for value in d.values(): >> do_somethig_with(value) As far as I can see much cleaner. No black magic needed ++ sort the dict to another order and rely on the sort order being stable would be a really a nice thing to have. My 2 cents, J?rgen From timaranz at gmail.com Tue Sep 18 21:23:48 2007 From: timaranz at gmail.com (timaranz at gmail.com) Date: Tue, 18 Sep 2007 18:23:48 -0700 Subject: no more reload() in py3k Message-ID: <1190165028.837799.220300@q3g2000prf.googlegroups.com> Hi all, this is possibly a python-dev question but I'll ask here first. Situation: I work on an application that takes 10-20 seconds to startup plus opening a document. To avoid having to restart the entire application each edit-debug cycle we rely heavily on the reload command. A typical method in our command dispatcher looks like this: def edit_something(self, something): reload(meshDialogModule) dlg = meshDialogModule.MeshDialog(self.app, something) dlg.run() when the application is built into an exe the reload function is redefined to lambda x: x. The advantage of this is that every time I open a dialog my latest changes are applied and the debug cycle is: edit code -> open dialog - > test -> close dialog -> edit code, which is many times faster than restarting the app and opening a project each time. Question: I am told to use the exec() statement instead. I don't see how I can use exec to reload a module. Cheers Tim From kyosohma at gmail.com Mon Sep 17 09:06:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 17 Sep 2007 06:06:15 -0700 Subject: (wxPython) icon on panel In-Reply-To: <1189932153.859201.222370@o80g2000hse.googlegroups.com> References: <1189932153.859201.222370@o80g2000hse.googlegroups.com> Message-ID: <1190034375.284403.95150@n39g2000hsh.googlegroups.com> On Sep 16, 3:42 am, Jimmy wrote: > hi,all! > have you used 'dictionary' of linux, the program that rests on the > panel as an icon, and when you click on the icon, it will display a > window and do something. So i'm wondering how to achieve this. I guess > it's a dialog window, right? but the crucial part is how to minimize > the program to an icon on the panel and make it responsive to the > click event. > thanks in advance! I've never used this "dictionary" program you're talking about, but I think I know what you mean. I would recommend that you download the wxPython Demo and open the main.py file in the "wxPython2.8 Docs and Demos\demo" subdirectory. There's a class in there called "DemoTaskBarIcon" which you can use to figure out how to do the whole iconizing thing. As for how to minimize to an icon, this is how I do it: # bind the frame/app to wx.EVT_ICONIZE self.Bind(wx.EVT_ICONIZE, self.onMinimize) # hide the frame def onMinimize(self, event): self.frame.Hide() If you can't get it to work, please ask for help on the wxPython mailing list: http://www.wxpython.org/maillist.php They're quite helpful. Mike From Michael.J.Fromberger at Clothing.Dartmouth.EDU Fri Sep 21 08:54:20 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Fri, 21 Sep 2007 08:54:20 -0400 Subject: frange() question References: Message-ID: In article , George Trojan wrote: > A while ago I found somewhere the following implementation of frange(): > > def frange(limit1, limit2 = None, increment = 1.): > """ > Range function that accepts floats (and integers). > Usage: > frange(-2, 2, 0.1) > frange(10) > frange(10, increment = 0.5) > The returned value is an iterator. Use list(frange) for a list. > """ > if limit2 is None: > limit2, limit1 = limit1, 0. > else: > limit1 = float(limit1) > count = int(math.ceil(limit2 - limit1)/increment) > return (limit1 + n*increment for n in range(count)) > > I am puzzled by the parentheses in the last line. Somehow they make > frange to be a generator: > >> print type(frange(1.0, increment=0.5)) > > But I always thought that generators need a keyword "yield". What is > going on here? Hi, George, The expression returned is a "generator expression", return (limit1 + n*increment for n in range(count)) Thus, although frange itself is not written as a generator, it does return a generator as its result. The syntax is like that of list comprehensions; see: Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From michael at jedimindworks.com Tue Sep 18 15:29:21 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 18 Sep 2007 12:29:21 -0700 Subject: Wait For Application Start In-Reply-To: <79b79e730709180540q2045a086rc6a049f16bd7e7ad@mail.gmail.com> References: <120025966304300060@unknownmsgid> <79b79e730709180540q2045a086rc6a049f16bd7e7ad@mail.gmail.com> Message-ID: <5AF03B37-0D8A-457E-8995-8C4E578C9550@jedimindworks.com> On Sep 18, 2007, at 5:40 AM, Francesco Guerrieri wrote: > On 9/18/07, Robert Rawlins - Think Blue > wrote: >> This seems like a very logical method, but I'm not sure how to >> implement it >> into my python code? Is there a simple way to make it wait for >> that file? >> Without the need to build my own conditional loop? > > I'm not sure why how you could avoid a conditional loop. Could > something like this work? > > import os.path > import time > > while True: > if os.path.exists(YOUR_FILE): > break > time.sleep(30) or while not os.path.exists(YOUR_FILE): time.sleep(1) From fd.calabrese at gmail.com Sun Sep 16 04:26:57 2007 From: fd.calabrese at gmail.com (cesco) Date: Sun, 16 Sep 2007 08:26:57 -0000 Subject: generating list of sub lists Message-ID: <1189931217.415065.102820@w3g2000hsg.googlegroups.com> Hi, is there a one-liner to accomplish the following task? >From the list l = ['string1', 'string2', 'string3'] generate the list of lists l = [['string1'], ['string1', 'string2'], ['string1', 'string2', 'string3']] Any help would be appreciated. Thanks Francesco From koutoo at hotmail.com Mon Sep 24 16:52:52 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Mon, 24 Sep 2007 13:52:52 -0700 Subject: Nested For and While Statements In-Reply-To: <1190666647.199890.174670@o80g2000hse.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190666647.199890.174670@o80g2000hse.googlegroups.com> Message-ID: <1190667172.491315.209110@y42g2000hsy.googlegroups.com> On Sep 24, 3:44 pm, Roberto Bonvallet wrote: > On Sep 24, 3:28 pm, kou... at hotmail.com wrote: > > > [...] where I start getting some errors. > > I'm hoping I won't have to post my code > > "Doctor, I'm feeling bad. I hope I won't have to tell you my > symptoms. What do I have?" > > Please provide the actual errors and the actual code. It is easier, > less error prone and more useful to copy and paste them instead of > writing some pseudocode. Maybe the repeated index i is a typo you > made when writing this post and the original code is correct, but we > don't have any way to know that. > > -- > Roberto Bonvallet Here is my code, in the hopes that there is a reason why it isn't running. Thanks guys. Option Explicit - 'Sorry so use to writing this! import os, string # Get filename to work with workspace = "c:\\temp" filename = "\AVC1030708.14" doc1 = workspace + filename onedoc = open(doc1, "r") rdoc1 = onedoc.read() doclist1 = string.split(rdoc1, "\n") for i in range(8): doclist1.pop(0) length = int(len(newlist1))-2 Nscheme = int(filename[12:14]) numlanes = length/Nscheme site = filename[4:7] year = filename[7:9] month = filename[9:11] Sscheme = str(Nscheme) # Get Master AVC Table for Lanes & Direction fileavc = "\AVCMaster" doc2 = workspace + fileavc twodoc = open(doc2, "r") rdoc2 = twodoc.read() doclist2 = string.split(rdoc2, "\n") doclist2.pop(0) # Dictionary of Zeros to add to Class Fields addzeros = {1:"0", 2:"00", 3:"000", 4:"0000"} while doclist1: list1 = doclist1[0] doclist1.pop(0) newlist1 = list1.split(",") date1 = newlist1[0] if len(newlist1[0])== 8: day = date1[2:3] else: day = date1[2:4] if len(day)>1: day = "0" +1 hour = newlist1[1] lanex = [] # Find number of Lanes & Fields if numlanes == 2: lane1 = newlist1[2:2+Nscheme] lanex.append(lane1) lane2 = newlist1[2+Nscheme:2+Nscheme*2] lanex.append(lane2) else: lane1 = newlist1[2:2+Nscheme] lanex.append(lane1) lane2 = newlist1[2+Nscheme:2+Nscheme*2] lanex.append(lane2) lane3 = newlist1[2+Nscheme*2:2+Nscheme*3] lanex.append(lane3) lane4 = newlist1[2+Nscheme*3:2+Nscheme*4] lanex.append(lane4) doctemp = doclist2 listtemp = doctemp[0] avclist = listtemp.split(",") while site <> avclist[0]: doctemp.pop(0) listtemp = doctemp[0] avclist = listtemp.split(",") dirx = [] fhlanex = [] dirx.append(avclist[2]) fhlanex.append(avclist[3]) dirx.append(avclist[5]) fhlanex.append(avclist[6]) if avclist[8] <> "0": dirx.append(avclist[8]) fhlanex.append(avclist[9]) dirx.append(avclist [11]) fhlanex.append(avclist[12]) for x in range(1, numlanes+1): avcclass = [] Nlanex = [] for i in range(1,Nscheme+1): numzeros = 5 - int(len(lanex[i-1])) avcclass.append(addzeros[numzeros] + lanex[i-1]) Nlanex.append(int(lanex[i-1]) lanex.pop(0) totalclass = sum(Nlanex) Stotalclass = str(totalclass) #Create 90 Character File for SAS Job classsum = avcclass[0] + avcclass[1] + avcclass[2] + avcclass[3] + avcclass[4] + avcclass[5] \ + avcclass[6] + avcclass[7] + avcclass[8] + avcclass[9] + avcclass[10] \ + avcclass[11] + avcclass[12] + avcclass[13] classmn = "C27" + site + dirx[x] + lanex[x] + year + month + day + hour + Stotalclass + classsum break avcsasdoc = workspace + "\avcsas.txt" fdoc = open(avcsasdoc, "w") fdoc.write(classmn) From nagle at animats.com Fri Sep 28 01:51:19 2007 From: nagle at animats.com (John Nagle) Date: Thu, 27 Sep 2007 22:51:19 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> Message-ID: <%q0Li.725$ih1.539@nlpi068.nbdc.sbc.com> TheFlyingDutchman wrote: > It seems that Python 3 is more significant for what it removes than > what it adds. > > What are the additions that people find the most compelling? I'd rather see Python 2.5 finished, so it just works. All the major third-party libraries working and available with working builds for all major platforms. That working set of components in all the major distros used on servers. The major hosting companies having that up and running on their servers. Windows installers that install a collection of components that all play well together. That's what I mean by "working". John Nagle From steve at holdenweb.com Sat Sep 15 21:16:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 15 Sep 2007 21:16:30 -0400 Subject: Python statements not forcing whitespace is messy? In-Reply-To: <46ec6826$1@news.eftel.com.au> References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> <1189890755.870694.29790@r29g2000hsg.googlegroups.com> <46ec6826$1@news.eftel.com.au> Message-ID: John Machin wrote: > On 16/09/2007 8:11 AM, James Stroud wrote: >> Steve Holden wrote: >>> I don't know why you have a bug up your ass about it, as the >>> Americans say. >> I think most Americans say "wild hare up your ass". > > The essence of Steve's point appears to be that the OP has ridden into > town to preach a misguided crusade against the heretofore-unknown > non-spacing heretics. It also seems to be alleged that at some stage, > the OP's donkey has been severely molested by some malevolent fauna; I > am having difficulty understanding the connection between the two > themes, and which is cause and which is effect. Enlightenment, please. > I guess I got the metaphor wrong? Eradicate the ten fetters of Buddhism and you will attain enlightenment. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From exarkun at divmod.com Fri Sep 28 14:16:20 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 28 Sep 2007 14:16:20 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191002679.569709.16870@22g2000hsm.googlegroups.com> Message-ID: <20070928181620.8162.1410141668.divmod.quotient.15562@ohm> On Fri, 28 Sep 2007 11:04:39 -0700, TheFlyingDutchman wrote: > [snip] > >In this case I asked it as part of the original question and it was >ignored. I have programmed in C and C++ and a little Pascal many years >ago. I don't remember anything about Higher Order Functions and would >like to see exactly how you do it and to verify the contention. > Perhaps you could do a bit of independent research. Then your messages to the group could contain more thoughtful questions and responses. Jean-Paul From sreeraj22283 at gmail.com Thu Sep 6 01:00:05 2007 From: sreeraj22283 at gmail.com (Sreeraj) Date: Wed, 05 Sep 2007 22:00:05 -0700 Subject: Using wild character Message-ID: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> hi, I am a beginner in Python. I wish to know how can i filter a list of strings using wild characters.ie Lets say i have list countries = ["india","africa","atlanta","artica","nigeria"]. I need only the list of string starting with 'a'. thank you Sreeraj From steve at REMOVE-THIS-cybersource.com.au Sun Sep 16 09:31:57 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 13:31:57 -0000 Subject: Needless copying in iterations? References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> <13epv3fnb6bak15@corp.supernews.com> <5l4ghuF655kfU2@mid.uni-berlin.de> Message-ID: <13eqc2daojgho03@corp.supernews.com> On Sun, 16 Sep 2007 10:58:07 +0000, Marc 'BlackJack' Rintsch wrote: > On Sun, 16 Sep 2007 09:50:39 +0000, Steven D'Aprano wrote: > >> The point is rather moot, since CPython (and probably other Pythons) do >> almost no optimizations. But just because Python is a dynamic language >> doesn't mean there are no optimizations possible: Haskell is a dynamic >> language, and there are optimizing compilers for it. Of course, it is >> much simpler for Haskell, because of the type system it uses. > > What do you mean by Haskell is a dynamic language? It is statically and > strict typed and the compiler usually knows all the functions. No > "surprises", no side effects, no duck typing. Haskell's IO monad (and possibly the do monad?) allows side effects. It would be a pretty poor programming language that didn't allow input or output! See also http://homepages.cwi.nl/~ralf/OOHaskell/ showing that Haskell can do object-oriented programming, complete with mutable objects and side-effects. Although "duck typing" is listed as a keyword, I couldn't see any reference to it in the paper. Haskell uses type inference, and has a "maybe" type for those cases where it can't tell what the type will be. If you still don't accept that Haskell is a dynamic language, for whatever definition of dynamic language you use, I'll withdraw the claim for the sake of not getting bogged down in long arguments over something that was really just a minor point. -- Steven. From mkent at acm.org Sat Sep 8 22:53:10 2007 From: mkent at acm.org (Mike Kent) Date: Sat, 08 Sep 2007 22:53:10 -0400 Subject: APL2007 reminder: early (cheaper) registration ends Thursday 9/13 Message-ID: <46E36016.1020803@acm.org> On-line registration is through the OOPSLA registrar http://www.regmaster.com/conf/oopsla2007.html APL 2007 home page http://www.sigapl.org/apl2007.html From zzbbaadd at aol.com Tue Sep 11 23:27:08 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 11 Sep 2007 20:27:08 -0700 Subject: Python 3K or Python 2.9? Message-ID: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> Python user and advocate Bruce Eckel is disappointed with the additions (or lack of additions) in Python 3: http://www.artima.com/weblogs/viewpost.jsp?thread=214112 From stefan.behnel-n05pAM at web.de Wed Sep 26 07:25:32 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 26 Sep 2007 13:25:32 +0200 Subject: elementtree question In-Reply-To: References: <46F76F86.6010307@web.de> Message-ID: <46FA41AC.4070604@web.de> Fredrik Lundh wrote: > (this recent lxml habit of using lxml-specific versions of things that > are trivial to do with the standard API is a bit disappointing. kind of > defeats the purpose of having a standard API...) ElementTree is not the only standard API that lxml is following. Another one is the standard API of the "list" builtin type, which has an extend() method. ah-you're-just-jealous-we-had-it-first-ly, Stefan :) From gatti at dsdata.it Thu Sep 27 08:50:45 2007 From: gatti at dsdata.it (gatti at dsdata.it) Date: Thu, 27 Sep 2007 05:50:45 -0700 Subject: sorteddict [was a PEP proposal, but isn't anymore!] In-Reply-To: <1190881576.186259.313720@57g2000hsv.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190829592.800804.242260@50g2000hsm.googlegroups.com> <1190881576.186259.313720@57g2000hsv.googlegroups.com> Message-ID: <1190897445.179828.291720@y42g2000hsy.googlegroups.com> I don't see a focused discussion of computational complexity of a sorted dict; its API cannot be simpler than sorting a dictionary and it has issues and complications that have already been discussed without completely satisfactory solutions, so the only possible reason to adopt a sorted dict is that some important use case for mapping types becomes significantly cheaper. With n entries, the size of a non-sorted hashtable, of a hashtable plus lists or sets of keys, and of reasonable sorted dict implementations with trees are all O(n). No substantial space advantage can be obtained by sorting dictionaries. Iterating through all n entries of a mapping, once, in sorted order, is O(n) time and O(1) space with an unsorted hash table, a hash table with a sorted list of the keys and all types of tree that I know of. If there is a performance gain, it must come from amortizing insertions, deletions and index-building. (The other operation, value updates for an existing key, doesn't matter: updates cause no structural changes and they must not invalidate any iterator.) Let's consider a very simple use case: n insertions followed by x iterations through all entries and n*y lookups by key. Cost for a hashtable and an ad hoc sorted list of the keys, fundamentally equivalent to sorting a Python dict: O(n) for insertions O(n log n) for indexing O(nx) for iterations O(ny) for lookups Cost for a tree: O(n log n) for insertions no indexing O(nx) for iterations O(ny log n) for lookups The hashtable comes out ahead because of cheaper lookups, for any x and y; note that without lookups there is no reason to use a mapping instead of a list of (key,value) tuples. With an equal number k of insertions and deletions between the iterations, the hashtable must be reindexed x times: O(n) for insertions O(kx) for updates and deletions O(nx log n) for indexing and reindexing O(nx) for iterations O(ny) for lookups The tree might be cheaper: O(n log n) for insertions O(kx log n) for updates and deletions no indexing and reindexing O(nx) for iterations O(ny log n) for lookups For a fixed small k, or with k proportional to n, reindexing the hashtable and lookups in the tree are equally mediocre. Maybe we could make k changes in the middle of each iteration. For a naively reindexed hashtable: O(n) for insertions O(kx) for updates and deletions O(knx log n) for indexing and reindexing O(nx) for iterations O(ny) for lookups For a tree, the costs remain as above: the new factor of n for the hashtable is fatal. Clever updates of the existing index or use of a heap would lower the cost, but they would need to be encapsulated as a sorteddict implementation. Is this a practical use case? When are sequential visits of all elements in order frequently suspended to make insertions and deletions, with a need for efficient lookup by key? - Priority queues; but given the peculiar pattern of insertions and deletions there are more suitable specialized data structures. - A* and similar best-first algorithms. It's a small but important niche; maybe it isn't important enough for the standard library. Other absent datatypes like heaps, an immutable mapping type similar to frozenset and tuple, or disjoint sets with would be more fundamental and general, and a mapping that remembers the order of insertion regardless of keys would be equally useful. In the Java collections framework all these kinds of mapping and others coexist peacefully, but Python doesn't have the same kitchen sink approach to basic libraries. Regarding the API, a sorted dict should not expose random access by an entry's position in the sequence: it is a gratuitous difficulty for the implementor and, more importantly, a perversion of the mapping data type. For that purpose there are lists and tuples, or explicit indices like those of the Boost multi-index containers (http:// www.boost.org/libs/multi_index). The only differences with dict should be the constraint that items(), keys(), values(), iteritems(), iterkeys(), itervalues() return entries sorted by key. Regards, Lorenzo Gatti From jgodoy at gmail.com Sat Sep 1 07:38:38 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 01 Sep 2007 08:38:38 -0300 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <7xwsvcc9yz.fsf@ruckus.brouhaha.com> <1i3p8lm.19738kn1q0gkouN%aleax@mac.com> <1188587846.687895.69240@q5g2000prf.googlegroups.com> <38rmq4-cq.ln1@strongwill.g2ctech> <46d903db$0$19580$4c368faf@roadrunner.com> Message-ID: Carl Banks wrote: > This is starting to sound silly, people. Critical is a relative term, > and one project's critical may be anothers mundane. Sure a flaw in your > flagship product is a critical problem *for your company*, but are you > really trying to say that the criticalness of a bad web search is even > comparable to the most important systems on airplanes, nuclear reactors, > dams, and so on? Come on. Who said they were the same? I said that just because it doesn't take lives it doesn't mean it isn't important. I wasn't going to reply to not extend this, but this misunderstanding of your was bugging me. I use Python on systems that deal with human health and wrong calculations may have severe impact on a good sized population. Using Python. As with nuclear reactors, dams, airplanes and so on we have a lot of redundancy and a lot of checkpoints. No one is crazy to take them out or even to remove some kind of dispositive to allow manual intervention at critical points. From richardjones at optushome.com.au Sat Sep 8 22:06:04 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sun, 09 Sep 2007 12:06:04 +1000 Subject: include myVar References: Message-ID: <46e3550c$0$22253$afc38c87@news.optusnet.com.au> Ricardo Ar?oz wrote: > Is there a way to import a module whose name is in a variable (read from > a configuration file for example)? pydoc __import__ Richard From bj_666 at gmx.net Sat Sep 1 05:11:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Sep 2007 09:11:59 GMT Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <7xwsvcc9yz.fsf@ruckus.brouhaha.com> <1i3p8lm.19738kn1q0gkouN%aleax@mac.com> <1188587846.687895.69240@q5g2000prf.googlegroups.com> <38rmq4-cq.ln1@strongwill.g2ctech> <46d903db$0$19580$4c368faf@roadrunner.com> Message-ID: <5jsomvFu0saU1@mid.uni-berlin.de> On Sat, 01 Sep 2007 10:34:08 +0200, Hendrik van Rooyen wrote: > "Carl Banks" wrote: > >> This is starting to sound silly, people. Critical is a relative term, >> and one project's critical may be anothers mundane. Sure a flaw in your >> flagship product is a critical problem *for your company*, but are you >> really trying to say that the criticalness of a bad web search is even >> comparable to the most important systems on airplanes, nuclear reactors, >> dams, and so on? Come on. > > This really intrigues me - how do you program a dam? - and why is it > critical? > > Most dams just hold water back. And some produce electricity. And most if not all can regulate how many water is let through. If something goes wrong the valley behind the dam gets flooded. If this is controlled by a computer you have the need for reliable software. Ciao, Marc 'BlackJack' Rintsch From llothar at web.de Sun Sep 2 20:21:38 2007 From: llothar at web.de (llothar) Date: Sun, 02 Sep 2007 17:21:38 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) Message-ID: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> I'm afraid that the GIL is killing the usefullness of python for some types of applications now where 4,8 oder 64 threads on a chip are here or comming soon. What is the status about that for the future of python? I know that at the moment allmost nobody in the scripting world has solved this problem, but it bites and it bites hard. Only groovy as a Java Plugin has support but i never tried it. Writing an interpreter that does MT this seems to be extremely difficult to do it right, with lots of advanced stuff like CAS and lock free programming. Even Smalltalk and Common Lisp didn't get it until know (with the exception of certain experiments). From bignose+hates-spam at benfinney.id.au Tue Sep 18 19:14:15 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Sep 2007 09:14:15 +1000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <87abrkhtfp.fsf@mulj.homelinux.net> Message-ID: <871wcvzhvc.fsf@benfinney.id.au> Hrvoje Niksic writes: > class X(Y): > def foo(self): > super(X, self).foo() > > ...there is in fact no guarantee that super() calls a superclass of > X. However, it is certainly guaranteed that it will call a superclass > of type(self). Not even that. It could call *any class in the inheritance hierarchy*, depending on how the MRO has resolved "next class". Even one that is neither an ancestor nor a descendant of X. -- \ "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 buzzard at urubu.freeserve.co.uk Thu Sep 20 10:45:24 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Thu, 20 Sep 2007 15:45:24 +0100 Subject: writing to lists within a dictionary In-Reply-To: <1190291825.337829.34670@19g2000hsx.googlegroups.com> References: <1190291825.337829.34670@19g2000hsx.googlegroups.com> Message-ID: cokofreedom at gmail.com wrote: > I am trying to write a basic anagram system, that takes a text file > line by line and by sorting the string into its alphabetical form > compares it to keys within a dictionary. > > If it matches a key I want to add it (in its unordered form) to a list > for that key. > > So far this is what I have > > import sys, string, fileinput > > # takes an item (string) and converts it to its basic alphabetical > form > def getChar( item ): > item_chars = [] > for i in range(len(item)): > item_chars.append(item[i]) > item_chars.sort() > return string.join(item_chars, "") > > anagramDict = {} > > for line in fileinput.input("fakelist.txt"): > myLine = line.replace("\n", "") #remove the carriage returns > myString = getChar(myLine) #get the alphabetical form > for k in anagramDict.items(): #iterator through the keys in the > dictionary > if k[0] == myString: #if the key matches our string > anagramDict[k].append([myLine])#append that k and add the value > this line > else: > anagramDict[myString] = [myLine] #else there is no key the same so > make a new one > > print anagramDict > A few suggestions. Use string methods, rather than the string module. Replace getChar with a simple one-liner (check out the builtin 'sorted' function). Consider whether it's really necessary to iterate over all the dictionary keys. Check out the setdefault method of dictionaries. Duncan From hat at se-162.se.wtb.tue.nl Thu Sep 20 02:51:28 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 20 Sep 2007 08:51:28 +0200 Subject: cannot create my own dict References: <46f17c26$0$26298$426a74cc@news.free.fr> Message-ID: On 2007-09-19, Bruno Desthuilliers wrote: > A.T.Hofkamp a ?crit : >> So if copying all methods of a native dictionary is not enough, what should I >> do to make my class work as a dictionary WITHOUT deriving from dict (which will >> obviously work). >> Hello all, Thanks for all the suggestions, the cause of the problem seems to be that I assumed that I can export magic methods from a member. Apparently, that is not true :-( > Sorry, I missed this last requirement. BTW, why don't you want to > subclass dict ? The reason for this problem is that we are busy re-structuring a large Python program, and we want to ensure nobody is messing up our data structures (at least not until we are finished). Most data types have a nice frozen variant (set -> frozenset, list -> tuple, __setattr__ override), but dictionaries do not. As a result I wanted to have a read-only dictionary. There is one in the Cook book, but it uses property's that I don't understand and they are also not in de Python language reference (at least I couldn't find them in the index and not in the table of contents). I don't like code that I don't understand (in particular when bugs in that code will be nasty to debug), so I decided to write my own, not in the last place, because I expected it to be simple in Python. I can derive from dict, but the problem with that is that I start with a read/write dictionary, and I can only hope to plug all holes to prevent my data from leaking out. By starting from 'object', I certainly don't have that problem, I start with a closed bucket and punch holes in it in a controlled way. (I rather have the program drop dead due to not having enough access than have it continue with too much access causing havoc 500 statements later in a totally unrelated area.) Rather than write a bunch of code like def __contains__(self, val): return val in self.mydict I thought I'd simply do self.__contains__ == self.d.__contains__ which is exactly the same but less work (or so I thought), and possibly slightly faster. Well, no such luck thus :-( Tnx for clearing up the problem, Albert From dimitri.pater at gmail.com Wed Sep 5 17:26:51 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Wed, 5 Sep 2007 23:26:51 +0200 Subject: StringIO MySQL data blob Image problem In-Reply-To: References: <46DEAAAB.8040008@timgolden.me.uk> Message-ID: Hi, the following code works when inserting images in reportlab tables: (result4 is a query result) a=0 for i in result4: cfoto = StringIO() cfoto.write(result4[a][9].tostring()) dfoto = cfoto.getvalue() fileFoto = open(str(a)+'temp.jpg','wb') fileFoto.write(dfoto) fileFoto.close() foto = Image(str(a)+'temp.jpg') a+=1 Do stuff here (insert the Image) The problem with this code is that I need to create a unique file (str(a)+'temp.jpg'), I tried to use a single temp.jpg but it kept using the data from the first record. Tried flush(), truncate(0), but it didn't work. (My mistake probably ;-) But the images show in the PDF so that's fine for now. On 9/5/07, dimitri pater wrote: > ---------- Forwarded message ---------- > From: dimitri pater > Date: Sep 5, 2007 9:13 PM > Subject: Re: StringIO MySQL data blob Image problem > To: Tim Golden > > > > Well, I'm mystified. Not by your results: that exactly what I > > expected to get, but because you're doing everything *except* > > manipulating an image and putting it into a PDF via ReportLab. > > > Dear Tim, > you are right of course, I have been trying to put the StringIO in a temp file: > cfoto=StringIO > cfoto.write(result[0][1].tostring()) > dfoto=cfoto.getvalue() > fileFoto=open('temp.jpg','wb') > fileFoto.write(dfoto) > > and indeed, the blob from MySQL is saved as an image! > however, > foto= Image('temp.jpg') > and inserting foto into a table results in: > x = struct.unpack('B', image.read(1)) > error: unpack str size does not match format > oh, well... still needs some work > BTW: I used 'local' images before (I mean they did not originate from > a DB), that worked well in Reportlab's tables. > Thanks, I am getting there (I think) > > > -- > --- > You can't have everything. Where would you put it? -- Steven Wright > --- > please visit www.serpia.org > -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org From steve at holdenweb.com Wed Sep 26 11:17:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 26 Sep 2007 11:17:33 -0400 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190814263.104358.158090@n39g2000hsh.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> <1190799759.367001.106400@r29g2000hsg.googlegroups.com> <87fy11lo22.fsf@mulj.homelinux.net> <1190804538.469582.96950@22g2000hsm.googlegroups.com> <1190814263.104358.158090@n39g2000hsh.googlegroups.com> Message-ID: Mark Summerfield wrote: > On 26 Sep, 13:22, Antoon Pardon wrote: [...] >> So it seems the API needs some more sorting out. > > I think you missed some of the previous postings. > > The sorteddict API that has emerged so far is (1) apart from the > constructor, everything is identical to dict, (2) the constructor > takes the same args as sorted(), so if you want to seed with a dict or > with keywords you write sorteddict(dict(a=1,b=2), ...), (or you could > create a sorteddict and use update() since that takes the same args as > dict's constructor). > > Could your AVLTree support cmp and keys and reverse? > I don't see how you can guarantee ordering of the seeded components, since you are creating an inherently unpredictable dict as the component to specify the initial contents of the sorteddict. Or is an arbitrary initial ordering acceptable? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From tim.arnold at sas.com Mon Sep 24 12:38:32 2007 From: tim.arnold at sas.com (Tim Arnold) Date: Mon, 24 Sep 2007 12:38:32 -0400 Subject: elementtree question References: <46F76F86.6010307@web.de> Message-ID: Thanks for the great answers--I learned a lot. I'm looking forward to the ET 1.3 version. I'm currently working on some older HP10.20ux machines and haven't been able to compile lxml all the way through yet. thanks again, --Tim Arnold From daniel.j.larsson at gmail.com Thu Sep 6 14:42:43 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Thu, 6 Sep 2007 20:42:43 +0200 Subject: library to launch program in linux In-Reply-To: <1189103678.484278.321650@r34g2000hsd.googlegroups.com> References: <1189103678.484278.321650@r34g2000hsd.googlegroups.com> Message-ID: <2bfa72fa0709061142j65cad924ybce436701dd64bd1@mail.gmail.com> On 9/6/07, idzwan.nizam at gmail.com wrote: > > Hi there, > > I'm a new user. What library should I use so that I can launch program > in linux using python? Thank you in advance. os.system or the commands library. -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jergosh at wp.pl Thu Sep 6 05:50:37 2007 From: jergosh at wp.pl (=?UTF-8?B?R3J6ZWdvcnogU8WCb2Rrb3dpY3o=?=) Date: Thu, 06 Sep 2007 11:50:37 +0200 Subject: So what exactly is a complex number? In-Reply-To: <5k86hqF2if1hU1@mid.individual.net> References: <451mq4-les.ln1@ozzie.tundraware.com> <5k86hqF2if1hU1@mid.individual.net> Message-ID: <46DFCD6D.2070002@wp.pl> >> In fact, a proper vector in physics has 4 features: point of >> application, magnitude, direction and sense. >> > > No -- a vector has the properties "magnitude" and direction. > Although not everything that has magnitude and direction is a > vector. > > It's very unusual to have a fixed point of application as a vector's > property (at least I haven't seen it so far). That would complicate > equality tests. > Interesting. It appears that we are ran into a mathematical cultural difference. Were I come from vectors *are* defined as having four properties that I enumerated. After some research I found that English sources (Wikipedia) indeed give the definition you supplied. In my old mechanics textbook (which is in English) vectors are divided into 'fixed' (having a clearly defined point of application), 'sliding' (p.o.a. can be moved along a line) and 'free' (those not associated with a unique line in space). However, given the following problem: (assuming 2-d Cartesian coordinate system and gravity acting 'downwards') "There are 3 point masses: 2 kg at (0, 0), 1 kg at (5, 4) and 4 kg at (2, 2). The acting forces are given as vectors: [2, 2] [1, 1]. Find the trajectories of all point masses." how would you propose to solve it without knowing where the forces are applied? >> In case of a vector in two dimensions (a special case, which you >> also fail to stress not to mention that you were talking about >> space) the magnitude and sense can be described by one number > > Actually, the "magnitude" and "sense" you use here are redundant. > What's the difference between a vector with magnitude "1" and > sense "-", and magnitude "-1" and sense "+"? > Again, I think we were given different definitions. Mine states that direction is 'the line on which the vector lies', sense is the 'arrow' and magnitude is the 'length' (thus non-negative). The definition is separate from mathematical description (which can be '[1 1] applied at (0, 0)' or 'sqrt(2) at 45 deg applied at (0, 0)' or any other that is unambiguous). >> and the direction as another. >> > > Represent the direction as one number? Only in a one-dimensional > space. > No. In one-dimensional 'space' direction is a ? quantity (a 'sense'). In 2-d it can be given as an angle. Regards, Greg From jstroud at mbi.ucla.edu Thu Sep 27 20:54:30 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 27 Sep 2007 17:54:30 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: Message-ID: Steve Holden wrote: > I wondered if a straw poll could get some idea of readers' thoughts > about when they will be migrating to 3.0 on, so I used the new widget on > Blogger to add a poll for that. > > I'd appreciate if if you would go to > > http://holdenweb.blogspot.com/ > > and register your vote on your intended migration timescale. > > Thanks! I'm going to abstain voting until 'public beta + about 1 year' is a choice. James From carsten at uniqsys.com Wed Sep 12 18:56:28 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 12 Sep 2007 18:56:28 -0400 Subject: Error in random module, bad installation? In-Reply-To: <1189635238.655642.233240@g4g2000hsf.googlegroups.com> References: <1189635238.655642.233240@g4g2000hsf.googlegroups.com> Message-ID: <1189637788.3301.3.camel@localhost.localdomain> On Wed, 2007-09-12 at 15:13 -0700, Andrew F wrote: > >>> import random > Unexpected error: > Traceback (most recent call last): > File "", line 1, in > File "random.py", line 10, in > x = random.random() > TypeError: 'module' object is not callable You have a file called random.py in your current directory. It's shadowing the random module from the library. HTH, -- Carsten Haese http://informixdb.sourceforge.net From bjorn.kempen at gmail.com Sat Sep 15 18:02:52 2007 From: bjorn.kempen at gmail.com (buffi) Date: Sat, 15 Sep 2007 22:02:52 -0000 Subject: Python statements not forcing whitespace is messy? In-Reply-To: References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> <1189890755.870694.29790@r29g2000hsg.googlegroups.com> Message-ID: <1189893772.157240.178800@19g2000hsx.googlegroups.com> On Sep 15, 11:49 pm, Steve Holden wrote: > buffi wrote: > > On Sep 15, 10:11 pm, "J. Cliff Dyer" wrote: > >> buffi wrote: > >>> Am I the only one that thinks that python statements should force > >>> whitespace before and after them? > >>> Right now this is not enforced and for an example these statements are > >>> valid > >>> print"hello" > >>> "foo"if"bar"else"foobar" > >>> for(x,y)in[(1,2),(3,4)]:print(x,y) > >>> [(y)for(x,y)in[("foo",2),("bar",4)]if"foo"in(x)] > >>> ...and so on. > >> On the other hand, this is just as bad: > > >> [ ( y ) for ( x , y ) in [ ( "foo" , 2 ) , ( "bar" , 4 ) ] if "foo" in ( > >> x ) ] > > >> And I'd hate to have to remember all of the rules for what can go > >> together and what can't, especially when it comes time to debug. No. > >> I don't think it should be forced, but maybe put it in PEP8 or PEP3008. > > >> Also, the only thing I find thoroughly disagreeable in all of that > >> mess, is the run-ins involving " characters. The rest are at least > >> clear at a glance what belongs where. > > >> Also, would you require the following? > > >> my_function (swallow='European') > > >> Because that is just an awful use of whitespace. > > >> Cheers, > >> Cliff > > > I believe that having whitespace around the builtin statements, and > > having whitespace around everything is pretty different. > > > There would be no downside whatsoever to enforcing this, except for > > backwards incompatibility (which is a rather huge downside but well... > > py3k is gonna break everything anyways). There obviously shouldnt be > > any limit to the maximum amount of whitespace used around statements > > (due to formatting and so on), but allowing stuff like print"hello" is > > just horrible. > > If you don't like it then don't write it. I've been reading this group > on and off for about ten years and I believe your email is the first to > point out that this is possible. Clearly it isn't something that happens > a lot, and I don't know why you have a bug up your ass about it, as the > Americans say. > > The Python philosophy is to be permissive, and to expect individual > users to write readable Python. Since they obviously do (one message in > ten years providing a counter-example) I think you are wasting your time > and energy on this. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline I actually found out about this myself while grading student labs. I myself didn't even know that you could write statements like this until then, but since some students does it that means that there should be other people out there as well that does it. And I can't say that I agree about "The Python philosophy being permissive, and to expect individual users to write readable Python". Python enforces proper indentation which I think is a great idea since I'm used to reading horribly indented code by others. I would love to see this extended to enforce proper whitespacing for statements. "There should be one-and preferably only one-obvious way to do it." is a phrase that is usually considered pythonic, and I think that it should also apply a bit when it comes to coding conventions. - Bj?rn Kemp?n From zzbbaadd at aol.com Mon Sep 3 23:02:46 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 03 Sep 2007 20:02:46 -0700 Subject: Python is overtaking Perl In-Reply-To: <20070904024908.b8aca60c.sulsa@gazeta.pl> References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> <20070904024908.b8aca60c.sulsa@gazeta.pl> Message-ID: <1188874966.963370.223660@r34g2000hsd.googlegroups.com> > This chart is showing that amount of python programers is smaller every > year :( I saw an article maybe a year ago, regarding "best careers" that completely contradicted previous articles I had seen in years gone by. It said that the number of people in programming and related jobs would decline in future decades. From roy at panix.com Sat Sep 1 00:06:13 2007 From: roy at panix.com (Roy Smith) Date: Sat, 01 Sep 2007 00:06:13 -0400 Subject: So what exactly is a complex number? References: <451mq4-les.ln1@ozzie.tundraware.com> <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> Message-ID: In article , Lawrence D'Oliveiro wrote: > In message <46d89ba9$0$30380$9b4e6d93 at newsspool4.arcor-online.net>, Wildemar > Wildenburger wrote: > > > Tim Daneliuk wrote: > >> > >> One of the most common uses for Complex Numbers is in what are > >> called "vectors". In a vector, you have both an amount and > >> a *direction*. For example, I can say, "I threw 23 apples in the air > >> at a 45 degree angle". Complex Numbers let us encode both > >> the magnitude (23) and the direction (45 degrees) as a "number". > >> > > 1. Thats the most creative use for complex numbers I've ever seen. Or > > put differently: That's not what you would normally use complex numbers > > for. > > But that's how they're used in AC circuit theory, as a common example. Well, not really. They're often talked about as vectors, when people are being sloppy, but they really aren't. In the physical world, let's say I take out a compass, mark off a bearing of 045 (north-east), and walk in that direction at a speed of 5 MPH. That's a vector. The "north" and "east" components of the vector are both measuring fundamentally identical quantities, along perpendicular axes. I could pick any arbitrary direction to call 0 (magnetic north, true north, grid north, or for those into air navigation, the 000 VOR radial) and all that happens is I have to rotate my map. But, if I talk about complex impedance in an AC circuit, I'm measuring two fundamentally different things; resistance and reactance. One of these consumes power, the other doesn't. There is a real, physical, difference between these two things. When I talk about having a pole in the left-hand plane, it's critical that I'm talking about negative values for the real component. I can't just pick a different set of axis for my complex plane and expect things to still make sense. From bdesth.quelquechose at free.quelquepart.fr Wed Sep 19 15:43:59 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 21:43:59 +0200 Subject: cannot create my own dict In-Reply-To: References: Message-ID: <46f17c26$0$26298$426a74cc@news.free.fr> A.T.Hofkamp a ?crit : > Hello all, > > This morning I tried to create my own read-only dictionary, and failed > miserably. > I don't understand why, can somebody enlighten me? > (snip) > So if copying all methods of a native dictionary is not enough, what should I > do to make my class work as a dictionary WITHOUT deriving from dict (which will > obviously work). > Sorry, I missed this last requirement. BTW, why don't you want to subclass dict ? Anyway, something like the following should do the trick (NB : Q&D, needs at least some testing): class ReadOnlyDict(object): def __init__(self, *args, **kw): self._dict = dict(*args, **kw) def __getattr__(self, name): if name in ('__setitem__', 'setdefault'): raise AttributeError("%s is read-only" % \ self.__class__.__name__) return getattr(self._dict, name) for name in dir(dict): if name.startswith('__') \ and name not in ('__new__', '__init__', '__setitem__', '__class__', '__dict__'): exec("%s = dict.%s" % (name, name)) From tuomas.vesterinen at pp.inet.fi Wed Sep 12 17:25:27 2007 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Wed, 12 Sep 2007 21:25:27 GMT Subject: An ordered dictionary for the Python library? In-Reply-To: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> Message-ID: <46E85979.4060905@pp.inet.fi> Mark Summerfield wrote: > I feel that Python lacks one useful data structure: an ordered > dictionary. Why it should be a dict. With it you can only maintain the order x1 Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB52@LITEXETSP001.etrsouth.corp.entergy.com> > From: Paul Hankin > > > Here's a first go. Sorting occurs when the keys are iterated over, > making it fast (almost as a dict) for construction, insertion, and > deletion, but slow if you're iterating a lot. You should look at some > use cases to decide if this approach is best, or if a sorted > datastructure should be used instead, but my instinct is that this is > a decent approach. Certainly, you're unlikely to get a simpler > implementation :) > > class sorteddict(dict): > "A sorted dictionary" > def __init__(self, arg=None, cmp=None, key=None, reverse=False): > if arg: > super(sorteddict, self).__init__(arg) > else: > super(sorteddict, self).__init__() > self._cmp = cmp > self._key = key > self._reverse = reverse > def keys(self): > return sorted(super(sorteddict, self).keys(), cmp=self._cmp, > key=self._key, reverse=self._reverse) > def iter_keys(self): > return (s for s in self.keys()) > def items(self): > return [(key, self[key]) for key in self.keys()] > def iter_items(self): > return ((key, self[key]) for key in self.keys()) > def values(self): > return [self[key] for key in self.keys()] > def iter_values(self): > return (self[key] for key in self.keys()) > def __str__(self): > return '{' + ', '.join('%s: %s' % (repr(k), repr(v)) > for k, v in self.iter_items()) + '}' > def __repr__(self): > return str(self) > def __iter__(self): > return self.iter_keys() You could speed up keys() at the cost of memory if you maintained a list of keys in the instance. Doing so would let you use an "unsorted" flag that gets set when a new key is added and checked when keys() is called. If the flag is unset, just return a copy of the list. Otherwise, sort the list in place, return a copy, and unset the flag. (Copies because you don't want the master key list to be modified by code using the class.) The use case for this seems to be when you have a dictionary that you need to often work through in sorted order. Sorting the keys every time keys() is called isn't an improvement over using a regular dict and sorting the keys normally. So the extra memory cost of maintaining an internal keys list looks reasonable to me. -- -Bill Hamilton From mensanator at aol.com Mon Sep 10 01:57:24 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 09 Sep 2007 22:57:24 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: <13e9iqhmgofasfb@corp.supernews.com> References: <13e9iqhmgofasfb@corp.supernews.com> Message-ID: <1189403844.128637.85950@k79g2000hse.googlegroups.com> On Sep 9, 11:43?pm, Dennis Lee Bieber wrote: > On Mon, 10 Sep 2007 01:06:59 GMT, Bryan Olson > declaimed the following in comp.lang.python: > > > They also disagree about integer division. C rounds toward zero; > > Python rounds downward. > > > In C: -111 / 10 evaluates to -11 > > In Python: -111 / 10 evaluates to -12 > > > > Is this a known gotcha? I tried to google the > > > subject however one cannot google the symbol %. > > > I think it's a known gotcha. I cited the refs in another post. > > The best answer is probably to be found from the definition of > divmod() > > > > >>> divmod(70, 6) > (11, 4) > >>> 6*11 + 4 > 70 > >>> divmod(-70, 6) > (-12, 2) > >>> 6 * -12 + 2 > -70 > > Or in general terms > > (a, b) = divmod(x, y) > x = y * a + b But, in general, doesn't (-11,-4) also satisfy x = y * a + b -70 = 6 * -11 + (-4)? Do you overpay your car loans and wait for a refund? Or do you make your last payment the residue of the debt after making 47 (or whatever) equal payments? > > IOWs, the definition of modulo, and the definition of integer division, > are linked... > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ From gtcopeland at gmail.com Sat Sep 1 09:25:59 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: Sat, 01 Sep 2007 06:25:59 -0700 Subject: Shed Skin Python-to-C++ compiler 0.0.23 In-Reply-To: <1187794819.745225.240130@j4g2000prf.googlegroups.com> References: <1187725658.819624.309370@r34g2000hsd.googlegroups.com> <1187794819.745225.240130@j4g2000prf.googlegroups.com> Message-ID: <1188653159.558070.120270@19g2000hsx.googlegroups.com> On Aug 22, 10:00 am, srepmub wrote: > > Adding socket support would certainly open the door for many common > > classes applications. If I had my pick, I say, sockets and then re. > > Thanks. Especially sockets should be not too hard to add, but I > probably won't work on these directly myself. Let me know if you are > interested.. :-) > > > BTW, I gatta say projects like shedskin and pypy are the most exciting > > python projects I'm aware of. Please keep of the good work. I'm so > > excited about the day I can begin using shedskin for the types of > > projects I use python on. > > I'm practically working alone on Shedskin, so the better bet will be > PyPy, unless I start getting more help. > > BTW I usually add a link to the homepage, but somehow I forgot this > time: > > http://mark.dufour.googlepages.com > > Thanks! > Mark Dufour. Mark, I wish I had the time to help with your project. I believe PyPy, Shedskin, and pyvm (which might be dead now), are the most interesting python projects currently going on. In fact, I would place them ahead of python 3000 even. Greg From goodger at python.org Mon Sep 10 19:13:47 2007 From: goodger at python.org (David Goodger) Date: Mon, 10 Sep 2007 19:13:47 -0400 Subject: Next PyCon Organizers' Meeting Tuesday, 11 September Message-ID: <46E5CFAB.8090802@python.org> Next meeting: Tuesday, September 11, at 18:00 UTC (2PM Eastern, 1PM Central, 12PM Mountain, 11AM Pacific). I'll post some agenda items, but feel free to add more: http://wiki.python.org/moin/PyCon2008/OrganizersMeetings Connection details: http://wiki.python.org/moin/PyCon2008/OrganizersMeetingsConnectionDetails PyCon is a community conference. Please join in and help out! David Goodger PyCon 2008 Chair -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 257 bytes Desc: OpenPGP digital signature URL: From joel.hedlund at gmail.com Tue Sep 25 07:08:07 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 25 Sep 2007 13:08:07 +0200 Subject: What is a good way of having several versions of a python module installed in parallell? Message-ID: Hi! I write, use and reuse a lot of small python programs for variuos purposes in my work. These use a growing number of utility modules that I'm continuously developing and adding to as new functionality is needed. Sometimes I discover earlier design mistakes in these modules, and rather than keeping old garbage I often rewrite the parts that are unsatisfactory. This often breaks backwards compatibility, and since I don't feel like updating all the code that relies on the old (functional but flawed) modules, I'm left with a hack library that depends on halting versions of my utility modules. The way I do it now is that I update the programs as needed when I need them, but this approach makes me feel a bit queasy. It seems to me like I'm thinking about this in the wrong way. Does anyone else recognize this situation in general? How do you handle it? I have a feeling it should be possible to have multiple versions of the modules installed simultaneously, and maybe do something like this: mymodule/ + mymodule-1.1.3/ + mymodule-1.1.0/ + mymodule-0.9.5/ - __init__.py and having some kind of magic in __init__.py that let's the programmer choose version after import: import mymodule mymodule.require_version("1.1.3") Is this a good way of thinking about it? What would be an efficient way of implementing it? Cheers! /Joel Hedlund From exhuma at gmail.com Thu Sep 6 12:12:56 2007 From: exhuma at gmail.com (exhuma.twn) Date: Thu, 06 Sep 2007 09:12:56 -0700 Subject: Changing data in an QAbstractListModel Message-ID: <1189095176.973314.227720@r29g2000hsg.googlegroups.com> Hi, I want to create a very simple read-only ListView. As the same data is used on various places in the UI, I decided to create a new ListView with a new Model instead of using the QListWidget. So far, the data displays correctly after setting it with "setModel" on the ListView. But how do I tell the views that the data is updated in the model? I defined a simple "update" method in the model which I call on certain events to fetch the new data in the DB. I tried to "emit" the "dataChanged()" signal of the Model without success. I don't know where I should get the two required "index" parameters from. Any hints? Here's the model: #-------------------------------------------------- class UnitListModel(QtCore.QAbstractListModel): __units = [] def update(self): c = db_con.cursor() # SELECT only the most recent entry for each company c.execute("SELECT DISTINCT ON (unit_id) nom FROM unit ORDER BY unit_id, year DESC") for unit in c.fetchall(): self.__units.append( unit[0] ) c.close() def rowCount(self, parent = QtCore.QModelIndex()): return len(self.__units) def data(self, index, role): if not index.isValid(): return QtCore.QVariant() if index.row() >= len(self.__units): return QtCore.QVariant() if role == QtCore.Qt.DisplayRole: return QtCore.QVariant(self.__units[index.row()]) else: return QtCore.QVariant() #-------------------------------------------------- From orsenthil at gmail.com Wed Sep 5 22:40:41 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Thu, 6 Sep 2007 08:10:41 +0530 Subject: ??????urllib post???????????? In-Reply-To: <1188993813.330662.174660@w3g2000hsg.googlegroups.com> References: <1188993813.330662.174660@w3g2000hsg.googlegroups.com> Message-ID: <20070906024041.GA6599@gmail.com> If possible, please post your query in ASCII. -- Senthil * liangxuliang79 at gmail.com [2007-09-05 05:03:33]: > ????www.mmmppp333.com??????????http://ishare.iask.sina.com.cn/cgi-bin/ > fileid.cgi?fileid=844050 > ??????post fileid=844050???????? > > ????post????????????fileid=844050??????server??????????header??header????local????location???? > ??????????????????????????????????????????????mp3????????????????????????????local????????????mp3?????????????????????????????????? > ?????????????????????????????? > > ??????????????python??urllib????????urllib???????????????????????local????????????????local????????mp3???????? > ????????????????mp3.?? > > ??post????????/download.php?? post????????fileid=844050???????????????????????????????????????????????????? > ????????????????????web?????????????????????? > -- > http://mail.python.org/mailman/listinfo/python-list -- O.R.Senthil Kumaran http://uthcode.sarovar.org From fredrik at pythonware.com Wed Sep 26 07:52:24 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 13:52:24 +0200 Subject: elementtree question In-Reply-To: References: Message-ID: Tim Arnold wrote: > I figure there must be a way to do it by creating a 'div' SubElement to the > 'body' tag and somehow copying the rest of the tree under that SubElement, > but it's beyond my comprehension. > > How can I accomplish this? > (I know I could put the class on the body tag itself, but that won't satisfy > the powers-that-be). for completeness, here's an efficient and fairly straightforward way to do it under plain 2.5 xml.etree: body = doc.find(".//body") # clone and mutate the body element div = copy.copy(body) div.tag = "div" div.set("class", "remapped") # replace the body contents with the new div body.clear() body[:] = [div] From http Sat Sep 22 02:56:58 2007 From: http (Paul Rubin) Date: 21 Sep 2007 23:56:58 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> Message-ID: <7xlkazgpc5.fsf@ruckus.brouhaha.com> Kay Schluehr writes: > If you feel you can transform it into another unambigous grammar > mixing statements and expressions it's up to you. We got rid of the print statement for python 3.0. Why not get rid of the rest of them too? Just use expressions for everything, as works fine for plenty of other languages. From duncan.booth at invalid.invalid Wed Sep 26 16:52:17 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Sep 2007 20:52:17 GMT Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <1190805297.182232.116830@50g2000hsm.googlegroups.com> <1190815180.945099.248670@n39g2000hsh.googlegroups.com> <1190816657.574437.80980@g4g2000hsf.googlegroups.com> <1190820026.299569.110250@n39g2000hsh.googlegroups.com> Message-ID: Paul Hankin wrote: >> So should Duncan's >> >> def __removekey(self, key): >> if key in self.__addkeys: >> del self.__addkeys[key] >> else: >> self.__delkeys.add(key) >> >> be changed to: >> >> def __removekey(self, key): >> if key in self.__addkeys: >> del self.__addkeys[key] >> self.__delkeys.add(key) > > Yes, and the same in __addkey: if it's in __delkeys it should be > removed from there, and added to __addkeys. There's an invariant: any > key is in at most one of __addkeys and __delkeys. > No, don't do that. The code was fine as I had written it, except for the minor point that sets don't support 'del'! Also there need to be some tests which actually exercise those two branches of the code: once you add appropriate tests it will become obvious that you really do need the else. A key which is in dict must be either in __keycache or in __addkeys, but never in both. A key which is not in the dict is either in none of __keycache, __addkeys, and __delkeys, or it is in both __keycache and __delkeys. If you don't have the else in both __removekey and __addkey, then deleting a key leaves the key present in both __keycache and __delkeys (as it should), and re-adding the key then leaves it in both __keycache and __addkeys which breaks the first condition and means iterating will see the key twice. Alternatively adding a key not in the dictionary and then deleting it leaves it only in __delkeys, which isn't as serious. Actually maybe you only need it in __addkey, or maybe I still don't have enough tests. Here's the code with set removal fixed and the extra test added: try removing the else from __addkey and you'll find it gives repeated indexes on iteration. However, what we really need now is some code which actually uses both versions of sorteddict, and an ordinary dict sorted when needed, and demonstrates a real benefit from one or both sorteddict over the ordinary dict. I think my version should be faster, but it is more complicated and often in Python the fastest way is also the simplest. ------------- sorteddict.py ----------------------- #!/usr/bin/env python # Copyright (c) 2007 Qtrac Ltd. All rights reserved. # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # The API and implementation are based on ideas from Paul Hankin writing # on comp.lang.python. """ A dictionary that is sorted by key or by the given cmp or key function. Provides a dictionary with the same methods and behavior as a standard dict and that can be used as a drop-in replacement for a dict (apart from the constructor), but which always returns iterators and lists (whether of keys or values) in sorted order. It does not matter when items are inserted or when removed, the items in the sorteddict are always returned in sorted order. The ordering is implicitly based on the key's __lt__() (or failing that __cmp__()) method if no cmp or key function is given. The main benefit of sorteddicts is that you never have to explicitly sort. One use case is where you have a set of objects that you want to make available in various sorted orders. You could, of course, sort on demand, but if the number of objects is very large (and if you're prepared to sacrifice some memory), it may be faster to use a sorteddict. For example: >>> class PrimeMinister: ... def __init__(self, forename, surname, elected): ... self.forename = forename ... self.surname = surname ... self.elected = elected >>> byForename = sorteddict(key=lambda pm: (pm.forename, pm.surname)) >>> bySurname = sorteddict(key=lambda pm: (pm.surname, pm.forename)) >>> byName = sorteddict(key=lambda pm: (pm.surname, pm.forename, ... pm.elected), reverse=True) >>> byElected = sorteddict(key=lambda pm: pm.elected) >>> for forename, surname, elected in ( ... ("Ramsay", "MacDonald", "1924-01-22"), ... ("Arthur", "Balfour", "1902-07-11"), ... ("Herbert Henry", "Asquith", "1908-04-07"), ... ("Stanley", "Baldwin", "1924-11-04"), ... ("David", "Lloyd George", "1916-12-07"), ... ("Andrew", "Bonar Law", "1922-10-23"), ... ("Henry", "Campbell-Bannerman", "1905-12-05"), ... ("Stanley", "Baldwin", "1923-05-23"), ... ("Ramsay", "MacDonald", "1929-06-05")): ... pm = PrimeMinister(forename, surname, elected) ... byForename[pm] = pm ... bySurname[pm] = pm ... byName[pm] = pm ... byElected[pm] = pm >>> [pm.forename for pm in byForename.values()] ['Andrew', 'Arthur', 'David', 'Henry', 'Herbert Henry', 'Ramsay', \ 'Ramsay', 'Stanley', 'Stanley'] >>> [pm.surname for pm in bySurname.values()] ['Asquith', 'Baldwin', 'Baldwin', 'Balfour', 'Bonar Law', \ 'Campbell-Bannerman', 'Lloyd George', 'MacDonald', 'MacDonald'] >>> ["%s %s %s" % (pm.forename, pm.surname, pm.elected) \ for pm in byName.values()] ['Ramsay MacDonald 1929-06-05', 'Ramsay MacDonald 1924-01-22', \ 'David Lloyd George 1916-12-07', 'Henry Campbell-Bannerman 1905-12-05', \ 'Andrew Bonar Law 1922-10-23', 'Arthur Balfour 1902-07-11', \ 'Stanley Baldwin 1924-11-04', 'Stanley Baldwin 1923-05-23', \ 'Herbert Henry Asquith 1908-04-07'] >>> ["%s %s %s" % (pm.forename, pm.surname, pm.elected) \ for pm in byElected.values()] ['Arthur Balfour 1902-07-11', 'Henry Campbell-Bannerman 1905-12-05', \ 'Herbert Henry Asquith 1908-04-07', 'David Lloyd George 1916-12-07', \ 'Andrew Bonar Law 1922-10-23', 'Stanley Baldwin 1923-05-23', \ 'Ramsay MacDonald 1924-01-22', 'Stanley Baldwin 1924-11-04', \ 'Ramsay MacDonald 1929-06-05'] Thanks to Python's object references, even though there are four sorteddicts referring to the same PrimeMinister objects, only one instance of each object is held in memory. >>> files = ["README.txt", "readme", "MANIFEST", "test.py"] >>> d = sorteddict([(name, name) for name in files], ... cmp=lambda a, b: cmp(a.lower(), b.lower())) >>> d.keys() ['MANIFEST', 'readme', 'README.txt', 'test.py'] Here are a few tests for some of the base class methods that are not reimplemented: >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.get("X", 21) 21 >>> d.get("i") 4 >>> d.has_key("a") True >>> d.has_key("x") False >>> "a" in d True >>> "x" in d False >>> len(d) 6 >>> del d["n"] >>> del d["y"] >>> len(d) 4 >>> d.clear() >>> len(d) 0 >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d["i"] 4 >>> d["y"] 6 >>> d["z"] Traceback (most recent call last): ... KeyError: 'z' Check that a mix of adding and removing keys doesn't cause confusion: >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.keys() ['a', 'i', 'n', 's', 't', 'y'] >>> del d["t"] >>> d["t"]=6 >>> d.keys() ['a', 'i', 'n', 's', 't', 'y'] """ __author__ = "Mark Summerfield" __version__ = "1.1.0" class sorteddict(dict): """A dictionary that is sorted by key or by the given cmp or key function. The sorteddict always returns any list or iterator in sorted order. For best performance prefer a key argument to a cmp one. If neither is given __lt__() (falling back to __cmp__()) will be used for ordering. This particular implementation has reasonable performance if the pattern of use is: lots of edits, lots of lookups, ..., but gives its worst performance if the pattern of use is: edit, lookup, edit, lookup, ..., in which case using a plain dict and sorted() will probably be better. If you want to initialize with a dict, either use sorteddict(dict(...), ...), or create the sorteddict and then call update with the arguments normally passed to a dict constructor. """ def __init__(self, iterable=None, cmp=None, key=None, reverse=False): """Initializes the sorteddict using the same arguments as sorted() >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.items() [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] >>> str(sorteddict()) '{}' >>> e = sorteddict(d) >>> e.items() [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] """ if iterable is None: iterable = [] dict.__init__(self, iterable) self.__cmp = cmp self.__key = key self.__reverse = reverse self.__keycache = None self.__addkeys = set() self.__delkeys = set() @property def __keys(self): if self.__keycache is None: self.__keycache = dict.keys(self) self.__addkeys = set() self.__delkeys = set() self.__keycache.sort(cmp=self.__cmp, key=self.__key, reverse=self.__reverse) else: if self.__delkeys: delkeys = self.__delkeys self.__keycache = [key for key in self.__keycache if key not in delkeys] self.__delkeys = set() if self.__addkeys: self.__keycache += list(self.__addkeys) self.__addkeys = set() self.__keycache.sort(cmp=self.__cmp, key=self.__key, reverse=self.__reverse) return self.__keycache def __invalidate_key_cache(self): self.__keycache = None self.__addkeys = set() self.__delkeys = set() def __addkey(self, key): if key in self.__delkeys: self.__delkeys.remove(key) else: self.__addkeys.add(key) def __removekey(self, key): if key in self.__addkeys: self.__addkeys.remove(key) else: self.__delkeys.add(key) def update(self, *args, **kwargs): """Updates the sorteddict using the same arguments as dict >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5)) >>> d.update(a=4, z=-4) >>> d.items() [('a', 4), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('z', -4)] >>> del d["a"] >>> del d["i"] >>> d.update({'g': 9}, a=1, z=3) >>> d.items() [('a', 1), ('g', 9), ('n', 3), ('s', 1), ('t', 5), ('z', 3)] >>> e = sorteddict(dict(p=4, q=5)) >>> del d["a"] >>> del d["n"] >>> e.update(d) >>> e.items() [('g', 9), ('p', 4), ('q', 5), ('s', 1), ('t', 5), ('z', 3)] """ self.__invalidate_key_cache() dict.update(self, *args, **kwargs) @classmethod def fromkeys(cls, iterable, value=None): """A class method that returns an sorteddict whose keys are from the iterable and each of whose values is value >>> d = sorteddict() >>> e = d.fromkeys("KYLIE", 21) >>> e.items() [('E', 21), ('I', 21), ('K', 21), ('L', 21), ('Y', 21)] >>> e = sorteddict.fromkeys("KYLIE", 21) >>> e.items() [('E', 21), ('I', 21), ('K', 21), ('L', 21), ('Y', 21)] """ dictionary = cls() for key in iterable: dictionary[key] = value return dictionary def copy(self): """Returns a shallow copy of this sorteddict >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> e = d.copy() >>> e.items() [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] >>> d = sorteddict() >>> e = d.copy() >>> e.items() [] """ return sorteddict(dict.copy(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) def clear(self): """Removes every item from this sorteddict >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> len(d) 6 >>> d.clear() >>> len(d) 0 >>> d["m"] = 3 >>> d["a"] = 5 >>> d["z"] = 7 >>> d["e"] = 9 >>> d.keys() ['a', 'e', 'm', 'z'] """ self.__invalidate_key_cache() dict.clear(self) def setdefault(self, key, value): """If key is in the dictionary, returns its value; otherwise adds the key with the given value which is also returned >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.setdefault("n", 99) 3 >>> d.values() [2, 4, 3, 1, 5, 6] >>> d.setdefault("r", -20) -20 >>> d.items()[2:] [('n', 3), ('r', -20), ('s', 1), ('t', 5), ('y', 6)] >>> d.setdefault("@", -11) -11 >>> d.setdefault("z", 99) 99 >>> d.setdefault("m", 50) 50 >>> d.keys() ['@', 'a', 'i', 'm', 'n', 'r', 's', 't', 'y', 'z'] """ if key not in self: self.__addkey(key) return dict.setdefault(self, key, value) def pop(self, key, value=None): """If key is in the dictionary, returns its value and removes it from the dictionary; otherwise returns the given value >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.pop("n") 3 >>> "n" in d False >>> d.pop("q", 41) 41 >>> d.keys() ['a', 'i', 's', 't', 'y'] >>> d.pop("a") 2 >>> d.pop("t") 5 >>> d.keys() ['i', 's', 'y'] """ if key not in self: return value self.__removekey(key) return dict.pop(self, key, value) def popitem(self): """Returns and removes an arbitrary item from the dictionary >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> len(d) 6 >>> item = d.popitem() >>> item = d.popitem() >>> item = d.popitem() >>> len(d) 3 """ item = dict.popitem(self) self.__removekey(item[0]) return item def keys(self): """Returns the dictionary's keys in sorted order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.keys() ['a', 'i', 'n', 's', 't', 'y'] """ return self.__keys[:] def values(self): """Returns the dictionary's values in key order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.values() [2, 4, 3, 1, 5, 6] >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6), ... reverse=True) >>> d.values() [6, 5, 1, 3, 4, 2] >>> d = sorteddict(dict(S=1, a=2, N=3, i=4, T=5, y=6), ... cmp=lambda a, b: cmp(a.lower(), b.lower())) >>> d.keys() ['a', 'i', 'N', 'S', 'T', 'y'] """ return [self[key] for key in self.__keys] def items(self): """Returns the dictionary's items in key order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d.items() [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] """ return [(key, self[key]) for key in self.__keys] def __iter__(self): """Returns an iterator over the dictionary's keys >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d) ['a', 'i', 'n', 's', 't', 'y'] """ return iter(self.__keys) def iterkeys(self): """Returns an iterator over the dictionary's keys >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d) ['a', 'i', 'n', 's', 't', 'y'] """ return iter(self.__keys) def itervalues(self): """Returns an iterator over the dictionary's values in key order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d.itervalues()) [2, 4, 3, 1, 5, 6] """ for key in self.__keys: yield self[key] def iteritems(self): """Returns an iterator over the dictionary's values in key order >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> list(d.iteritems()) [('a', 2), ('i', 4), ('n', 3), ('s', 1), ('t', 5), ('y', 6)] """ for key in self.__keys: yield key, self[key] def __delitem__(self, key): """Deletes the item with the given key from the dictionary >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> del d["s"] >>> del d["y"] >>> del d["a"] >>> d.keys() ['i', 'n', 't'] """ self.__removekey(key) dict.__delitem__(self, key) def __setitem__(self, key, value): """If key is in the dictionary, sets its value to value; otherwise adds the key to the dictionary with the given value >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5, y=6)) >>> d["t"] = -17 >>> d["z"] = 43 >>> d["@"] = -11 >>> d["m"] = 22 >>> d["r"] = 5 >>> d.keys() ['@', 'a', 'i', 'm', 'n', 'r', 's', 't', 'y', 'z'] """ if key not in self: self.__addkey(key) dict.__setitem__(self, key, value) def __repr__(self): """ >>> sorteddict() sorteddict() >>> sorteddict({'a':1}) sorteddict({'a': 1}) >>> def comparison(a,b): return cmp(a,b) >>> def keyfn(a): return a >>> sorteddict({'a':1}, cmp=comparison) #doctest: +ELLIPSIS sorteddict({'a': 1}, cmp=) >>> sorteddict({'a':1}, key=keyfn, reverse=True) #doctest: +ELLIPSIS sorteddict({'a': 1}, key=, reverse=True) """ args = [] if self: args.append(dict.__repr__(self)) if self.__cmp is not None: args.append('cmp=%r' % self.__cmp) if self.__key is not None: args.append('key=%r' % self.__key) if self.__reverse is not False: args.append('reverse=%r' % self.__reverse) return "%s(%s)" % (self.__class__.__name__, ', '.join(args)) def __str__(self): """Returns a human readable string representation of the dictionary The returned string is proportional in size to the number of items so could be very large. >>> d = sorteddict(dict(s=1, a=2, n=3, i=4, t=5)) >>> str(d) "{'a': 2, 'i': 4, 'n': 3, 's': 1, 't': 5}" >>> d = sorteddict({2: 'a', 3: 'm', 1: 'x'}) >>> str(d) "{1: 'x', 2: 'a', 3: 'm'}" """ return "{%s}" % ", ".join( ["%r: %r" % (key, self[key]) for key in self.__keys]) if __name__ == "__main__": import doctest doctest.testmod() ---------------------------------------------------- From arnodel at googlemail.com Sun Sep 9 15:39:48 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 09 Sep 2007 12:39:48 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> Message-ID: <1189366788.800728.209180@19g2000hsx.googlegroups.com> On Sep 9, 8:15 pm, "J. Cliff Dyer" wrote: > Dotan Cohen wrote: > > FIrst of all, how is the % symbol (as in 70%6=4) called in English? > > > Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or > > the other in error? Is this a known gotcha? I tried to google the > > subject however one cannot google the symbol %. Thanks in advance. > > > Dotan Cohen > > The % operator is called "modulo" in English. I don't think the > difference in implementation is an error. It's just a difference of > calculation method. > > Python will always yield a number x = m%n such that 0 <= x < n, but > Turbo C will always yield a number such that if x = m%n -x = -m%n. That > is, since 111 % 10 = 1, -111 % 10 = -1. The two values will always > differ by n (as used above). > > I'm sure there are mathematicians on the list who can give you a more > technical, precise explanation of the reasons for the different results. I don't know if there's a mathematical explanation of the difference, but I prefer the behaviour of the Python modulo operator because for any a, b, n, if a = b (mod n) holds then the Python expression 'a % n == b % n' evaluates to True. -- Arnaud From robin at reportlab.com Wed Sep 19 08:44:54 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 19 Sep 2007 13:44:54 +0100 Subject: super() doesn't get superclass In-Reply-To: <1190178792.662623.164840@o80g2000hse.googlegroups.com> References: <8764281uea.fsf@benfinney.id.au> <1190178792.662623.164840@o80g2000hse.googlegroups.com> Message-ID: <46F119C6.1070405@chamonix.reportlab.co.uk> Michele Simionato wrote: ....... interesting stuff ommitted super seems to return an object of type super, but I cannot seem to find any documention on this type except for 3.4.2.3 "Super Binding If a is an instance of super, then the binding super(B, obj).m() searches obj.__class__.__mro__ for the base class A immediately preceding B and then invokes the descriptor with the call: A.__dict__['m'].__get__(obj, A). " -- Robin Becker From paul.hankin at gmail.com Wed Sep 26 19:22:49 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 26 Sep 2007 23:22:49 -0000 Subject: A question on python performance. In-Reply-To: References: Message-ID: <1190848969.640188.237480@w3g2000hsg.googlegroups.com> On Sep 26, 7:26 pm, "Joe Goldthwaite" wrote: > The code gets kind of wordy so I started trying to figure out how to call > them dynamically since the param type is the same as the method the > retrieves it. I came up with this; > > def getValue(trend, param, per): > return trend.__class__.__dict__[param](trend, per) > > That worked but it seems like the above line would have to do lots more > object look ups at runtime so I didn't think it would be very efficient. I > thought maybe I could add a caller method to the trend class and I came up > with this; > > class trend: > ... > ... > ... > def caller(self, param, *args): > return self.__class__.__dict__[param](self, *args) > > This simplified the getValue function to this; > > def getValue(trend, param, per): > return trend.caller(param, per) You're calling a function (getValue) that just calls a method of trend (caller), that just calls another method of trend (Ptd or Qtd or ...). You can skip all these steps, and just call the method yourself: the code that calls getValue(trend, param, per) replace with trend.(per) if you're calling getValue with a static value for param, or getattr(trend, param)(per) if param is dynamic. -- Paul Hankin From Graham.Dumpleton at gmail.com Thu Sep 20 21:03:36 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Fri, 21 Sep 2007 01:03:36 -0000 Subject: Python,SWIG and libjvm In-Reply-To: <1190329236.398635.226020@y42g2000hsy.googlegroups.com> References: <1190329236.398635.226020@y42g2000hsy.googlegroups.com> Message-ID: <1190336616.212881.171910@i38g2000prf.googlegroups.com> On Sep 21, 9:00 am, sapsi wrote: > Hello, > I'm not sure if this the correct list but here goes (and sorry for the > noise). I've been attempting to wrap python around libhdfs. > So far so good (i've attached the SWIG template at the end). The > compilation works without errors and the shared objects do have > references to all the functions. > > However, when importing into python > > import pyhdfs > > i get the following error: > > Traceback (most recent call last): > File "", line 1, in ? > File "/home/sguha/tmp/b/hdfs.py", line 7, in ? > import _hdfs > ImportError: libjvm.so: cannot open shared object file: No such file > or directory > > However, libjvm.so is located in /home/sguha/mine/jdk1.6.0_02/jre/lib/ > amd64/server which is present in the PYTHONPATH and sys.path. > I can understand it complaining while loading the libjvm.so > but python doesn't locate it even when in the path. > > As an aside, the build command for hdfs.c has " -ljvm " - this > should affect SWIG, right? Meaning if my program (e.g) links to a > library and i want a wrapper around my program (to python) i need SWIG > templates for my headers only and not for the linked library...right? > ( I guess the answer is i dont otherwise that would be quite a > nightmare of work) > > Thank you for your time > Saptarshi > > Attachments: > SWIG template > %module pyhdfs > > %{ > #include "hdfs.h" > %} > > %include "hdfs.h" Your libjvm.so isn't being found because it isn't in a standard system library directory. You have a few choices to solve this: 1. Install libjvm.so into /lib or /usr/lib. You may be able to get away with putting it in /usr/local/lib if your OS is setup to look there. 2. If a Linux/Solaris box, do: LD_LIBRARY_PATH=/home/sguha/mine/jdk1.6.0_02/jre/lib/amd64/server export LD_LIBRARY_PATH then run your application. This will tell you application to look in that directory for the shared library at run time. 3. If on Linux/Solaris, compile that library directory into the Python module .so by setting before you compile your Python module: LD_RUN_PATH=/home/sguha/mine/jdk1.6.0_02/jre/lib/amd64/server export LD_RUN_PATH This only needs to be done at compile time, but means your module will always expect it to be in that location. Graham From kahrny at gmail.com Fri Sep 7 06:02:14 2007 From: kahrny at gmail.com (kahrny at gmail.com) Date: Fri, 07 Sep 2007 10:02:14 -0000 Subject: why should I learn python In-Reply-To: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: <1189159334.533470.17570@r29g2000hsg.googlegroups.com> On Sep 6, 10:32 pm, windandwaves wrote: > Can someone tell me why I should learn python? I am a webdeveloper, > but I often see Python mentioned and I am curious to find out what I > am missing out on. > > Thank you > > Nicolaas - You never really have to reinvent the wheel, and many python modules are included by default. This means that you can accomplish what you wanted to do much faster. Thus You can write a lot less code to get to what you want to do. If a module does not exist yet, you can create it! - It is kinda close to pseudo code, so you can 'think' much easier in python. - It can be used for many many tasks, and you can adapt your application as need be. - It is still quite fast and lightweight! - The community in general is quite helpful - It is quite fun to use - If it's good enough for nasa.. :-P In regards to people claiming it is not 'real', that is a load of poo! Ignore thy c elitists. Eric Raymond wrote a nice 'Why Python?' article. http://www.linuxjournal.com/article/3882 From jcd at sdf.lonestar.org Thu Sep 6 22:57:18 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 06 Sep 2007 22:57:18 -0400 Subject: why should I learn python In-Reply-To: <87zlzzs9by.fsf@wilson.homeunix.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> Message-ID: <46E0BE0E.2040702@sdf.lonestar.org> Torsten Bronger wrote: > Hall?chen! > > Tom Brown writes: > > >> [...] Python has been by far the easiest to develop in. Some >> people might say it is not "real programming" because it is so >> easy. >> > > I can't believe this. Have you really heard such a statement? > > Tsch?, > Torsten. > The catch-phrase such people often use is "scripting language." If you hear python called a "scripting language," the speaker is obliquely implying the superiority of their own "programming language." -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbellon at sbellon.de Thu Sep 13 13:13:41 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Thu, 13 Sep 2007 19:13:41 +0200 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> Message-ID: <20070913191341.69dae855@cube.tz.axivion.com> On Thu, 13 Sep, TheFlyingDutchman wrote: > Bruce said that no other mainstream OO language is explicitly passing > the object as a parameter to class methods. Ada 95 does. And Ada 95 was the first standardized OO language. Now with Ada 2005 you can either pass the the object explicitly as first parameter (like in Ada 95) or you can call the method on the object (like in Java, C++, Python, ...) and the object is passed implicitly. -- Stefan Bellon From steve at REMOVE-THIS-cybersource.com.au Sun Sep 9 09:03:22 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Sep 2007 13:03:22 -0000 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> <7xhcm4pl5m.fsf@ruckus.brouhaha.com> Message-ID: <13e7roq4dbo6043@corp.supernews.com> On Sun, 09 Sep 2007 18:53:32 +1200, Lawrence D'Oliveiro wrote: > In message <7xhcm4pl5m.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >> Lawrence D'Oliveiro writes: >> >>> Except that the NSA's reputation has taken a dent since they failed to >>> anticipate the attacks on MD5 and SHA-1. >> >> NSA had nothing to do with MD5 ... > > Nevertheless, it was their job to anticipate attacks on it. After all, > they call themselves the "National _Security_ Agency", don't they? The NSA has many jobs, and doing public research in crypto is only one of them -- and a particularly small one at that. For all we know, they had an attack on MD5 ten years before anyone else and didn't tell anyone because keeping it secret made it useful for one of their other jobs. >> ... and it's to NSA's credit that SHA-1 held up for as long as it did. > > But they have no convincing proposal for a successor. That means the gap > between the classified and non-classified state of the art has shrunk > down to insignificance. I don't see how that follows. But even if it does... maybe it's because there is nowhere to go from here? You can't make mathematical breakthroughs to order. -- Steven. From hniksic at xemacs.org Wed Sep 19 08:02:55 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 19 Sep 2007 14:02:55 +0200 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <87fy1a6h3b.fsf@mulj.homelinux.net> <1190201811.727402.172330@k79g2000hse.googlegroups.com> Message-ID: <87bqby6exc.fsf@mulj.homelinux.net> Michele Simionato writes: > On Sep 19, 1:16 pm, Hrvoje Niksic wrote: >> Your arguments against the superclass term seem to assume that there >> is only a single superclass to a particular class. > > If you say "the" superclass, then you also assume it is unique. FWIW, Bruno said "a", at least in the section you quoted. > But the big issue is that the order of the methods depends on the > second argument to super, the instance, so there is no useful > concept of the superclass of the first argument of super. No argument here. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 6 08:49:02 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Sep 2007 12:49:02 -0000 Subject: interesting puzzle......try this you will be rewarded... References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> <13dvn2q9qogq484@corp.supernews.com> Message-ID: <13dvtpub9gte735@corp.supernews.com> On Thu, 06 Sep 2007 04:52:11 -0700, Steve Holden wrote: >> In case it wasn't obvious, the site is nothing but adware. Banner ads, >> google ads, text ads, blah blah blah. I stopped at page 1. >> >> > I'm surprised you went even that far. It was pretty obviously going to > be a click trap. Why bother? Stupidity? No, wait, I meant curiosity. I wanted to see if it was at least targeted to the audience (Python developers). It wasn't. -- Steven. From tdwdotnet at gmail.com Fri Sep 28 17:04:07 2007 From: tdwdotnet at gmail.com (Tim Williams) Date: Fri, 28 Sep 2007 22:04:07 +0100 Subject: List search In-Reply-To: References: Message-ID: <9afea2ac0709281404u62072355o5474a83e3cac5b6c@mail.gmail.com> On 28/09/2007, Kevin Walzer wrote: > I'm having a problem with searching a list. Here's my code: > > mylist = ['x11', 'x11-wm', 'x11-system'] > > for line in mylist: > if 'x11' in line: > print line > > This results in the following output: > > x11 > x11-wm > x11-system > That output is correct, you are asking your script to print any list item containing x11 when what you actually wanted was a list item that is the string 'x11' mylist = ['x11', 'x11-wm', 'x11-system'] for item in mylist: if item == 'x11': print line If there is only ever one 'x11' in the list you could also consider print mylist.index('x11') and print mylist[mylist.index('x11')] Also, before iterating the whole list check that 'x11' exists if 'x11' in mylist: do stuff and list comprehesions print [x for x in mylist if x == 'x11'] HTH :) Tim Williams From gagsl-py2 at yahoo.com.ar Sun Sep 9 23:42:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 10 Sep 2007 00:42:37 -0300 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> <13e99756io95p66@corp.supernews.com> Message-ID: > "Lawrence D'Oliveiro" wrote in message > news:fbqo83$8fd$1 at lust.ihug.co.nz... >> >> Why not just build a new list? E.g. >> >> newdevs = [] >> for dev in devs : >> ... >> if not removing_dev : >> newdevs.append(dev) >> #end if >> #end for >> devs = newdevs En Sun, 09 Sep 2007 22:58:54 -0300, bambam escribi?: > I can try that, but I'm not sure that it will work. The problem > is that devList is just a pointer to a list owned by someone else. > Making devList point to a new list won't work: I need to make > the parent list different. I could do this by adding an extra > level of indirection, but I think at the risk making the call > environment more complex. Then use [:] to *replace* all the old list items, do not merely rebind the name. That last statement should be, instead: devs[:] = newdevs (Please don't top-post) -- Gabriel Genellina From Shawn at Milochik.com Mon Sep 17 15:11:02 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Mon, 17 Sep 2007 15:11:02 -0400 Subject: pattern combinations In-Reply-To: References: Message-ID: <2dc0c81b0709171211o58d72f00q8147094a6b01a54d@mail.gmail.com> On 9/17/07, dorje tarap wrote: > Hi all, > > Given some patterns such as "...t...s." I need to make all possible > combinations given a separate list for each position. The length of the > pattern is fixed to 9, so thankfully that reduces a bit of the complexity. > > For example I have the following: > > pos1 = ['a',' t'] > pos2 = ['r', 's'] > pos3 = ['n', 'f'] > > So if the pattern contains a '.' character at position 1 it could be 'a' or > 't'. For the pattern '.s.' (length of 3 as example) all combinations would > be: > > asn > asf > tsn > tsf > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > Sounds like homework to me. From willmaier at ml1.net Fri Sep 7 08:14:34 2007 From: willmaier at ml1.net (Will Maier) Date: Fri, 7 Sep 2007 07:14:34 -0500 Subject: Generating a unique identifier In-Reply-To: <13e2fgbbpsatm39@corp.supernews.com> References: <13e2fgbbpsatm39@corp.supernews.com> Message-ID: <20070907121434.GC26089@lass.lfod.us> On Fri, Sep 07, 2007 at 12:03:23PM -0000, Steven D'Aprano wrote: [...] > which is easy enough, but I thought I'd check if there was an existing > solution in the standard library that I missed. Also, for other > applications, I might want them to be rather less predictable. 2.5 includes the uuid module for RFC 4122 universally-unique IDs: http://docs.python.org/lib/module-uuid.html -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From stefan.behnel-n05pAM at web.de Mon Sep 24 04:04:22 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 24 Sep 2007 10:04:22 +0200 Subject: elementtree question In-Reply-To: References: Message-ID: <46F76F86.6010307@web.de> Tim Arnold wrote: > Hi, I'm using elementtree and elementtidy to work with some HTML files. For > some of these files I need to enclose the body content in a new div tag, > like this: > >

> original contents... >
> Give lxml.etree (or lxml.html) a try: tree = etree.parse("http://url.to/some.html", etree.HTMLParser()) body = tree.find("body") and then: div = etree.Element("div", {"class" : "remapped"}) div.extend(body) body.append(div) or alternatively: children = list(body) div = etree.SubElement(body, "div", {"class" : "remapped"}) div.extend(children) http://codespeak.net/lxml/ and for lxml.html, which is currently in alpha status: http://codespeak.net/lxml/dev/ ET 1.3 will also support the extend() function, BTW. Stefan From bj_666 at gmx.net Mon Sep 10 03:07:12 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2007 07:07:12 GMT Subject: Python syntax wart References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> <5ki2sdF3nr68U1@mid.individual.net> Message-ID: <5kk8p0F3vfqqU1@mid.uni-berlin.de> On Mon, 10 Sep 2007 15:02:58 +1200, Lawrence D'Oliveiro wrote: > In message <5ki2sdF3nr68U1 at mid.individual.net>, Bjoern Schliessmann wrote: > >> Lawrence D'Oliveiro wrote: >>> But then you can no longer use indentation to display the >>> two-dimensional structure of the statement. >> >> How can a statement be two-dimensional? > > Like this (from C++ code, but the idea is the same): > > if > ( > ThisCh >= 'A' and ThisCh <= 'Z' > or > ThisCh >= '0' and ThisCh <= '9' > or > ThisCh == '_' > or > ThisCh == '.' > ) > ... I still down see the second dimension. If you say 2D I think of something like a table with two columns and not a sequential condition spread over several lines. Ciao, Marc 'BlackJack' Rintsch From mauriceling at acm.org Thu Sep 6 21:50:31 2007 From: mauriceling at acm.org (Maurice LING) Date: Fri, 07 Sep 2007 01:50:31 GMT Subject: why should I learn python In-Reply-To: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: <46e0ae64$1@news.unimelb.edu.au> windandwaves wrote: > Can someone tell me why I should learn python? I am a webdeveloper, > but I often see Python mentioned and I am curious to find out what I > am missing out on. > > Thank you > > Nicolaas > The last edition of The Python Papers (volume 2 issue 2, http://archive.pythonpapers.org/ThePythonPapersVolume2Issue2.pdf) has an article on Django, a web framework. It may help you see what you are missing out on. maurice From duncan.booth at invalid.invalid Tue Sep 18 07:44:58 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Sep 2007 11:44:58 GMT Subject: Looking for web software in Python. References: Message-ID: Kevin Ar18 wrote: > > Are any of the following pieces of web software available in Python > (under a non-copyleft license like BSD or MIT or Python license)? > > > Mailing list - with web accessable archive and list maintenance. > Source control > Wiki System > > Again, only non-copyleft licenses like MIT, BSD, or public domain. > > I'm curious why copyleft matters to you. Were you planning on taking the mailing list software and redistributing a modified version? There is nothing in the GPL which prevents you taking something like Mailman, modifying it as much as you like and using the improved version. There is no requirement on you to release your changes provided you don't actually distribute the code to third parties. What do you mean by 'source control' available in Python? Subversion isn't written in Python but you can certainly write Python code which interacts with it either client or server-side. The Subversion license is Apache style so that would suite you although again I doubt whether it matters. From aleax at mac.com Sun Sep 2 12:55:29 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 2 Sep 2007 09:55:29 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188742231.470668.29910@g4g2000hsf.googlegroups.com> Message-ID: <1i3t4ha.1r0xx7414w0taxN%aleax@mac.com> Mark Dickinson wrote: > On Sep 2, 9:45 am, jwrweather... at gmail.com wrote: > > [snip code] > > > > Thanks for that. I realise that improving the algorithm will speed > > things up. I wanted to know why my less than perfect algorithm was so > > much slower in python than exactly the same algorithm in C. Even when > > turning off gcc's optimiser with the -O0 flag, the C version is still > > > > > 100 times quicker. > > Well, for one thing, you're creating half a million xrange objects in > the course of the search. All the C code has > to do is increment a few integers. I don't think the creation of xrange objects is a meaningful part of Python's execution time here. Consider: M = 1000 solutions = [0] * M def f2(): "a*a + b*b precalculated" for a in xrange(1, M): a2 = a*a for b in xrange(1, M - a): s = a2 + b*b for c in xrange(1, M - a - b): if s == c*c: solutions[a+b+c] += 1 def f3(M=M, solutions=solutions): "pull out all the stops" xrs = [xrange(1, k) for k in xrange(0, M+1)] for a in xrs[M]: a2 = a*a for b in xrs[M-a]: s = a2 + b*b for c in xrs[M-a-b]: if s == c*c: solutions[a+b+c] += 1 import time t = time.time() f2() e = time.time() print e-t, max(xrange(M), key=solutions.__getitem__) solutions = [0]*M t = time.time() f3(M, solutions) e = time.time() print e-t, max(xrange(M), key=solutions.__getitem__) f2 is Arnaud's optimization of the OP's algorithm by simple hoisting; f3 further hoists the xrange creation -- it creates only 1000 such objects rather than half a million. And yet...: brain:~/py25 alex$ python puz.py 34.6613101959 840 36.2000119686 840 brain:~/py25 alex$ ...which suggests that creating an xrange object is _cheaper_ than indexing a list... Alex From nagle at animats.com Mon Sep 24 16:48:22 2007 From: nagle at animats.com (John Nagle) Date: Mon, 24 Sep 2007 13:48:22 -0700 Subject: M2Crypto 0.18 - new version, same old build bugs - more details In-Reply-To: References: Message-ID: <46F82296.5010701@animats.com> Heikki Toivonen wrote: > John Nagle wrote: > >>Back in March, I posted this: >> >> >>> Hit that with OpenSSL. Red Hat took elliptical curve cryptography >>>out of Fedora 6 for patent reasons. With that missing, M2Crypto won't >>>build. It ought to; the implementor of M2Crypto thought of that, because >>>it's an optional feature. But M2Crypto uses SWIG. SWIG doesn't normally >>>process nested include files. OpenSSL had changed their configuration >>>approach to use nested include files. So SWIG didn't see the #define >>>that >>>said to turn off elliptical curve crypto support. This resulted in >>>compile errors in the 24,000 lines of code that come out of SWIG. >> >> That was for M2Crypto 0.17. >> >> It's still broken in M2Crypto 0.18. > > > This was reported as > https://bugzilla.osafoundation.org/show_bug.cgi?id=9404 and fixed, at > least according to the person who reported the bug. I'd be curious to > know why the fix does not work for you... > > As an alternative, does it work if you add line 130 to setup.py: > > '-DOPENSSL_NO_EC', # Uncomment if you have > trouble compiling without EC support OK, here's the build failing: python setup.py build running build running build_py running build_ext building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/local/include/python2.5 -I/usr/include -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:27: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 OK, let's check the requirements, from http://chandlerproject.org/bin/view/Projects/MeTooCrypto M2Crypto 0.18: * Python 2.3 or newer o m2urllib2 requires Python 2.4 or newer * OpenSSL 0.9.7 or newer o Some optional new features will require OpenSSL 0.9.8 or newer * SWIG 1.3.24 or newer python --version Python 2.5 [OK here, 2.5 >= 2.4] swig -version SWIG Version 1.3.31 [OK here; 1.3.31 >= 1.3.24] Compiled with i386-redhat-linux-g++ [i386-redhat-linux-gnu] openssl OpenSSL> version OpenSSL 0.9.8a 11 Oct 2005 [OK here; 0.9.8a => 0.9.7.] Tried the suggested patch to "setup.py": diff setup.py.orig setup.py 130c130 < #'-D__i386__', # Uncomment for early OpenSSL 0.9.7 versions --- > '-D__i386__', # Uncomment for early OpenSSL 0.9.7 versions No change in error message. That gets us -bash-3.1$ python setup.py build running build running build_py running build_ext building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/local/include/python2.5 -I/usr/include -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:27: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 But notice that the -D entry didn't appear on the SWIG command line. Neither did the "-includeall". The "swig_opts" values around line 129 aren't actually being used. I think that's left over from the code intended to allow builds with Python 2.3 and earlier. The "self.swig_opts" up at line 53 of "setup.py" seems to be controlling. The patch was to the obsolete code. This is on Fedora Core 5, x86, 32 bit. John Nagle From kyosohma at gmail.com Wed Sep 19 14:17:01 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 19 Sep 2007 11:17:01 -0700 Subject: Finding prime numbers In-Reply-To: References: <1190218927.7991.25.camel@apprentice-laptop> <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> <1190219929.7991.28.camel@apprentice-laptop> <2dc0c81b0709191013k181d1a74m76a08cecadb005c4@mail.gmail.com> Message-ID: <1190225821.182650.227540@k79g2000hse.googlegroups.com> On Sep 19, 12:15 pm, "Shawn Milochik" wrote: > Okay, I caught one bug already myself: > > for y in range(3,(math.sqrt(x) + 1)): > > should be > > for y in range(3,(int(math.sqrt(x)) + 1)): If you'd just search the archives, you would have found this: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b134b2235e9c19a6/34857fb0b0b2a4b5?lnk=gst&q=prime+number&rnum=1#34857fb0b0b2a4b5 And Google has many hits. Here's one example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178 Mike From deets at nospam.web.de Thu Sep 27 12:39:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Sep 2007 18:39:24 +0200 Subject: Implement file download using python References: <1190910556.681518.277220@o80g2000hse.googlegroups.com> Message-ID: <5m24lrFb8ao0U1@mid.uni-berlin.de> skulka3 at gmail.com wrote: > Hello, > > I want to implement file downloads inside an authenticated web page, > such that when a user clicks a link, the server side python code > connects to a ftp server, downloads a relevant file and then streams > the file to the browser for the user to open it with the appropriate > application. In this case it will either be a pdf or a tiff file. > > This function is quite similar to something like writing raw bytes to > a ServletOutputStream in java to be rendered directly to the user. > > It would be nice if someone can provide guidance, examples on how such > a task may be accomplished using python. Fetching using ftplib is easy. But serving depends on what HTTP-server-environment you use. Please elaborate on that. Diez From grante at visi.com Sat Sep 22 08:57:35 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 22 Sep 2007 12:57:35 -0000 Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> <13f99fediasg3ae@corp.supernews.com> <46f4c171$0$26367$4c368faf@roadrunner.com> Message-ID: <13fa49vie86ii1d@corp.supernews.com> On 2007-09-22, Carl Banks wrote: >> If you don't want to use the bitwise operations, then ignore >> them. Presto! Simpler syntax. > > Until people no longer need to read code written by others, this argument > is utter bull. > > It's completely besides the point, anyways. The point is to > make the language core smaller. Since when has the size of Python been a concern? > It would shift code implementing bitwise logic out the core > parts of Python, and localize it in modulespace. It's not > about trying to make the mental footprint of the language > smaller; in fact, wouldn't do that at all. I disagree. Making the mental footprint of the language smaller is far more important. The small size of the mental footprint is what helps readability, maintainability, and productivity. Space in my head is more valuable than space in my computer. >>> Obviously, how widespread their usage is would matter. But >>> keep in mind it would also be easy to convert the code >>> automatically, because the Python parser could reliably find >>> all bitwise operations reliably. >> >> The resulting code wold be fugly. > > Of course it would be. The reason I mention it is that > automatic convertibility is a key factor in whether a change > can make it into Python 3. It matters not whether fugly code is automatically generated or manually generated. It's still hard to read and maintain. -- Grant Edwards grante Yow! I feel... JUGULAR... at visi.com From __peter__ at web.de Thu Sep 13 02:03:44 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Sep 2007 08:03:44 +0200 Subject: File Parsing Question References: <1189634861.631219.143310@57g2000hsv.googlegroups.com> Message-ID: Am Wed, 12 Sep 2007 17:28:08 -0500 schrieb Shankarjee Krishnamoorthi: > I would prefer to use something with seek. Writing Perl in any language? > I am not able to use seek() > with "for line in inp". Use tell and seek does not seem to do anything > with the code. When I try to do > > for line in inp.readlines(): readlines() reads the whole file at once, so inp.tell() will give the position at the end of the file from now on. > # Top of Loop > if not condition in line: > do_something > else: > for lines in inp.readlines(): > if not condition > do_something > else: > break > pos = inp.tell() > inp.seek(pos) ---> This line has not effect in the program > > Not sure if Iam missing something very basic. Also the previous line > needs to be used in the position I call # Top of Loop. If you want to use seek/tell you can't iterate over the file directly because for line in inp: # ... reads ahead to make that iteration highly efficient -- so you will often get a position further ahead than the end of the current line. But you can use readline() (which doesn't read ahead) in conjunction with tell/seek; just replace all occurences of for line in inp: # ... with for line in iter(inp.readline, ""): # ... Peter From lasses_weil at klapptsowieso.net Fri Sep 7 09:45:30 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Fri, 07 Sep 2007 15:45:30 +0200 Subject: Checking if elements are empty In-Reply-To: References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <46e155fb$0$7701$9b4e6d93@newsspool2.arcor-online.net> Steven D'Aprano wrote: > On Fri, 07 Sep 2007 11:12:05 +0200, Wildemar Wildenburger wrote: > >> Lawrence D'Oliveiro wrote: >>> In message , Chris >>> Mellon wrote: >>> >>>> On 9/5/07, Steve Holden wrote: >>>>> Doran, Harold wrote: >>>>>> Is there a way to check if the first element of y is null? >>>>>> >>>>> len(y[0]) == 0 >>>>> >>>> Better spelled as >>>> >>>> if y[0]: >>> Not a good idea. >> Why not? > > > What happens if y is an empty list? > > An exception pops up, of course ;). It all depends on the (intended) semantics of the program; the original question sounds like that list is supposed to have at least one element at that point, so there is no problem. And if it's not then that has to be dealt with, but that is not the problem here. So the usual way to check if the first element of a list y is True in a boolean context is indeed "if y[0]:" (or for False of course "if not y[0]:"). /W From larry.bates at websafe.com Wed Sep 19 15:18:06 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 19 Sep 2007 14:18:06 -0500 Subject: Google and Python In-Reply-To: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> Message-ID: TheFlyingDutchman wrote: > Around 2000 I heard that Google was using Python to some extent. Now I > see that Guido Van Rossum works for them as well as Alex Martellis who > has the title "Uber Technical Lead" which seems to imply some fairly > heavy Python usage there. I was wondering what is done at Google with > Python and which Python "environments/applications" (Zope, TurboGears, > mod_python ...) are in use, and what is done with other languages, and > which other languages are they using. > Have you tried Google "google python". Turns up a lot of links for me. -Larry From mattheww at chiark.greenend.org.uk Tue Sep 11 13:00:52 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 11 Sep 2007 18:00:52 +0100 (BST) Subject: Modul (%) in python not like in C? References: <13ec37dri08s7a3@corp.supernews.com> Message-ID: J. Cliff Dyer wrote: >Bryan Olson wrote: >> Not true. Here it is again: >> >> When integers are divided, the result of the / operator is >> the algebraic quotient with any fractional part discarded.(87) >> If the quotient a/b is representable, the expression >> (a/b)*b + a%b shall equal a. >> [...] >> 87) This is often called 'truncation toward zero' >> >> [International Standard ISO/IEC 9899:1999, Section 6.5.5 >> Multiplicative operators, Paragraph 6 and footnote 87] > But C was around for a long time before the 1999 standard. C89, > commonly called ANSI C, is still very commonly used in compilers, and > K&R C goes back to 1972. Is truncation toward 0 the standard for K&R C > as well? As I remember, the behaviour for negative 'a' wasn't specified in K&R C or in C89; the rule was tightened up for C99. -M- From kyosohma at gmail.com Wed Sep 12 09:20:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 12 Sep 2007 13:20:54 -0000 Subject: Sea-or-land test In-Reply-To: <1189598084.622653.94590@50g2000hsm.googlegroups.com> References: <1189598084.622653.94590@50g2000hsm.googlegroups.com> Message-ID: <1189603254.821828.296380@k79g2000hse.googlegroups.com> On Sep 12, 6:54 am, kpalamartch... at gmail.com wrote: > Could you advise if there exists a simple package, containing function > that would take geographic coordinates and return information on > whether this point belongs to land or sea? No great accuracy is needed > -- I am interested in just major features, like those seen on coarse > world maps. This may be of use to you: http://cheeseshop.python.org/pypi/geopy or http://blog.case.edu/bmb12/2006/09/geocoding_tools_for_python_and_caseclasses Should be helpful anyway. Mike From chris.olekas at gmail.com Tue Sep 11 13:26:43 2007 From: chris.olekas at gmail.com (Chris) Date: Tue, 11 Sep 2007 10:26:43 -0700 Subject: Excel process still running after program completion. In-Reply-To: References: <1189525558.721174.198370@19g2000hsx.googlegroups.com> Message-ID: <1189531603.894247.218710@r29g2000hsg.googlegroups.com> On Sep 11, 12:59 pm, "Hamilton, William " wrote: > > From: Chris > > > I have a python script that is driving Excel and using the win32com > > module. However, upon program completion there's still an Excel.exe > > process running in the background that I must terminate through Task > > Manager. Reading up on other threads indicate that maybe I still have > > some Excel objects referenced within my code. Is this why the process > > doesn't terminate? > > > The related (I hope) parts of my code is here. > > > x1App = Dispatch("Excel.Application") > > Book1 = x1App.Workbooks.Open(ExcelLogPath+"\\outputLog-template.xls") > > x1App.Visible = 1 > > for sheets in Book1.Worksheets: > > if sheets.Name == file_name: > > sheetExists = True > > if sheetExists != True: > > activeSheet = > > Book1.Worksheets.Add(After=Book1.Worksheets(1)) > > activeSheet.Name = file_name > > testNum[file_name] = 0 > > Book1.Worksheets(file_name).Select() > > Book1.ActiveSheet.Cells(1+(testNum[file_name]*20),1).Value = "Original > > File Name" > > Book1.ActiveSheet.Cells(2+(testNum[file_name]*20),1).Value = > > file_name > > Book1.ActiveSheet.Pictures().Insert(output).Select() > > Book1.SaveAs(Filename=path) > > x1App.ActiveWorkbook.Close(SaveChanges=0) > > x1App.Quit() > > del x1App > > del Book1 > > del activeSheet > > > What am I missing? > > In my Excel projects, I terminate it with: > > xlBook.Close() > xlApp.Quit() > > I haven't had a problem with Excel staying open after the program ends. > > (On a tangent, I want to find the person who thought it was a good idea > to use the same symbol in a font for 1, l, and I and do some unpleasant > things.) > > -- > -Bill Hamilton That doesn't really fix the problem as I'm pretty sure its identical code for x1App.ActiveWorkbook.Close(SaveChanges=0) I think where my problem lies is within my for each loop where I search to see if the worksheet with the name already exists for sheets in Book1.Worksheets: if sheets.Name == file_name: sheetExists = True Since I'm assuming that it creates objects for each of the sheets and I don't delete them... From ratchetgrid at googlemail.com Sun Sep 2 13:57:21 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Sun, 2 Sep 2007 18:57:21 +0100 Subject: Adding attributes stored in a list to a class dynamically. Message-ID: <676224240709021057y6dc9a51aie2f9bb553c3a6d19@mail.gmail.com> Hi, Sorry if the subject line of post is wrong, but I think that is what this is called. I want to create objects with class Coconuts(object): def __init__(self, a, b, *args, **kwargs): self.a = a self.b = b def spam( l ) return Coconuts( l.a, l.b, l.attributes ) l in a parse line of a file which is a tuple wrapped with attrcol......with attributes a, b and attributes (which is a list of strings in the format key=value ie... [ "id=bar", "test=1234", "doh=qwerty" ] ). I want to add attributes to Coconuts so that I can do print c.id, c.test, c.doh HOwever I m not sure how to do this: how can i assign args, kwargs within the constructor of coconuts and how can I deconstruct the list to form the correct syntax to be able to be used for args, kwargs. HOpe this makes sense, Thanks in advance, Nathan From aine_canby at yahoo.com Mon Sep 24 07:12:46 2007 From: aine_canby at yahoo.com (aine_canby at yahoo.com) Date: Mon, 24 Sep 2007 04:12:46 -0700 Subject: sorting a list numbers stored as strings Message-ID: <1190632366.863711.100680@y42g2000hsy.googlegroups.com> hi, I have the following list - ["1", "11", "2", "22"] how do I sort it like this - ["1", "2", "11", "22"] thanks, aine From panguohualove at sina.com Sat Sep 29 22:24:07 2007 From: panguohualove at sina.com (panguohua) Date: Sat, 29 Sep 2007 19:24:07 -0700 Subject: earn $26800 a month with google adsense Message-ID: <1191119047.330796.246600@22g2000hsm.googlegroups.com> www.space666.com sport news and make money From blackmh at gmail.com Sun Sep 2 19:40:29 2007 From: blackmh at gmail.com (Kveldulv) Date: Sun, 02 Sep 2007 23:40:29 -0000 Subject: Glade + Python = No GUI In-Reply-To: <1188760969.316987.214410@w3g2000hsg.googlegroups.com> References: <1188750465.530463.271750@22g2000hsm.googlegroups.com> <46db09e1$0$7697$9b4e6d93@newsspool2.arcor-online.net> <1188760969.316987.214410@w3g2000hsg.googlegroups.com> Message-ID: <1188776429.469599.74480@d55g2000hsg.googlegroups.com> Note to myself and python noobs like me: Don't forget to set Visible to yes on main window in Glade :) From andre.ditador9999 at gmail.com Mon Sep 17 17:11:53 2007 From: andre.ditador9999 at gmail.com (Andre P.S Duarte) Date: Mon, 17 Sep 2007 21:11:53 -0000 Subject: =?iso-8859-1?q?Re:_I=B4m_trying_to_desenvolve_a_site_in_python?= In-Reply-To: References: <1190051850.198096.258890@o80g2000hse.googlegroups.com> <5l7uglF6kto9U1@mid.individual.net> <1190053707.193010.159350@n39g2000hsh.googlegroups.com> Message-ID: <1190063513.429061.13970@d55g2000hsg.googlegroups.com> On 17 set, 17:08, "Gabriel Genellina" wrote: > En Mon, 17 Sep 2007 15:28:27 -0300, Arnaud Delobelle > escribi?: > > > On Sep 17, 7:14 pm, Bjoern Schliessmann > mail-0306.20.chr0n... at spamgourmet.com> wrote: > >> Andre P.S Duarte wrote: > >> > I?m trying to desenvolve a site in python. > > >> What does "desenvolve" mean? By "site", do you mean a web site? > > > "desenvolver" is a spanish verb meaning "to develop". > > Yes, but more likely the OP has a Portuguese/Brazilian origin, and the > word exists in that language too. > Going on topic, a good starting point is http://wiki.python.org/moin/WebFrameworks > > -- > Gabriel Genellina txs it?s helped a lot!! Yes i?m brazilian. sorry for the bad english lol From apardon at forel.vub.ac.be Mon Sep 3 06:31:12 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 Sep 2007 10:31:12 GMT Subject: Does shuffle() produce uniform result ? References: Message-ID: On 2007-08-26, tooru honda wrote: > By incorporating Alex's code, I got another performance boost of 20%. > It is mostly due to Alex's more efficient implementation of block random > than my own version. If I understand correctly that you are using urandom as a random generator I wouldn't trust too much on this performance. Urandom uses the systemwide entropy-pool. If other programs need this pool too, your performance can drop spectaculary. If you are using a linux machine just try to execute "od -x /dev/random" at the same time as your program. -- Antoon Pardon From ricaraoz at gmail.com Mon Sep 3 06:28:45 2007 From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=) Date: Mon, 03 Sep 2007 07:28:45 -0300 Subject: advice about `correct' use of decorator In-Reply-To: References: <46C4B097.4080309@fmed.uba.ar> <740c3aec0708170529s6f7e7fe2l8c92771c2d0a51d4@mail.gmail.com> <46C5C9AE.5020508@fmed.uba.ar> <1187792001.935204.42330@e9g2000prf.googlegroups.com> <740c3aec0708230520h6a92a29ar180efed41730f563@mail.gmail.com> <740c3aec0708290332k3c125d9el16250939e22ea8c4@mail.gmail.com> Message-ID: <46DBE1DD.2070405@bigfoot.com> Gabriel Genellina wrote: > En Wed, 29 Aug 2007 07:32:21 -0300, BJ?rn Lindqvist > escribi?: > >> On 8/24/07, Gabriel Genellina wrote: >>> En Thu, 23 Aug 2007 09:20:21 -0300, BJ?rn Lindqvist >>> escribi?: >>> >>>> def check_user_logged_in(func): >>>> def f(*args, **kwargs): >>>> if global_state.the_user.is_logged_in: >>>> return func(*args, **kwargs) >>>> return show_login_page() >>>> return f >>> I think there is a semantic problem, perhaps we are not talking >>> about the same thing. I'm considering the software complexity AS >>> PERCEIVED BY THE PROGRAMMER, looking at the interactions between a >>> program and a programmer who is working on some task; some people >>> would say "cognitive complexity" to make it clear. >> There is no semantic problem. You are just mistaken in your belief >> that the complexity that the user of the decorator has to deal with is >> different from the complexity in implementing the decorator. > > But they ARE different. That's the whole point of abstractions, code > reuse, layered design... Designing a simple interfase on top of a complex > system is very common. Nobody writes X-Window code, as nobody writes a raw > event loop for Windows anymore: there are very good GUI toolkits, even > portable frameworks, that put an abstract layer on top of that so the > programmer has a much simple and coherent view. The complexity is behind > the scenes. > >>> Which API is more complex: one in which you can play a movie with >>> just a single call like PlayMovie(Title), or one on which you must >>> call a zillion functions to firtly initialize the stream format, >>> configure the display, disable undesired user interfase elements, >>> locate the movie file, load it in chunks, etc.? The first one is >>> certainly much simpler to use (simpler = less complex), and maybe >>> internally it calls the same functions as the second one, but nobody >>> cares. >> "nobody cares" is your guess. I'd bet that the caller of the PlayMovie >> function cares a lot: Is the movie played full screened? Which >> encodings are supported? Can you set the title of the movie window? Is >> streaming supported? Does it even work on windows? Which URI schemes >> does it support? And so on and so on. >> >> That is why no video decoding API:s have a PlayMovie(Title) function >> and why I haven't seen a single 3d engine with a >> MakeReallyCoolDoomCloneFPSGame() function. > > (yet!). What about urlopen? Using a single call one can be authenticated > and retrieve any file in the other side of the planet. I consider it a > simple interfase, altough it does complex things. Would you say it is > better to use plain sockets everywhere? Or, since sockets are abstractions > themselves, would you say it is better to use lower level primitives > instead? Each time you descend a level, you have to use many simpler > functions - but their combination is more complex. > >> "hiding details" only works if the client programmer really doesn't >> care about the details. > > Why should he care? Isn't "hiding implementation details" a good design > principle? > When I use urlopen, I don't even care of the underlying socket > implementation. I don't care which interfase the request is sent thru. I > don't care if the answer got fragmented and some packets had to be > reassembled. urlopen gives me something that looks like a file, and I just > read() from it. > >>> Back to your example, the fact that a decorator builds a higher order >>> function, does NOT make it more complex - because the programmer does >>> not >>> see that. In fact, hiding the details makes it simpler. >> Yes, the programmer does see that. The example decorator I posted >> requires about a zillion preconditions to work correctly and will fail >> in weird ways when those preconditions are not satisfied. The >> programmer is interested in the crazy failures he or she will >> experience. I dare you to try and implementing the code both as a >> decorator and as a function, then write the unit tests and >> documentation. The complexity of those three items together >> (implementation + tests + documentation) will be much higher for the >> decorator choice because the complexity of the decorator >> implementation is a bit higher than using a plain old function. > > Testing the decorator is as hard as testing any other function. Testing > the decorated functions might involve *only* checking if the decorator is > actually used for those functions. > Going to your posted example, I don't see the difference - I should say, I > don't see the advantage. Using a decorator hides some implementation > details and reduces coupling between modules, both good things on "my" > book; your function with no decorator does quite the opposite, and doesn't > look like good coding style (on "my" book, of course). > >> Note also that it is extremely rare to see well-documented or >> well-tested code, which means that the programmer WILL have to analyze >> the implementation which means that implementation complexity matters >> a lot. > > In any case, that would require testing and analyzing ONE function (the > decorator) instead of inspecting a zillion repetitions of the same code > that, when being wrong, have to be located and fixed on all those places. > > Really, I still can't understand how you can defend such silly things - > unless we are talking about different things. > FACADE Intent : Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. GoF Design Patterns. pp.185 From rbonvall at gmail.com Mon Sep 24 16:44:07 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Mon, 24 Sep 2007 13:44:07 -0700 Subject: Nested For and While Statements In-Reply-To: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> Message-ID: <1190666647.199890.174670@o80g2000hse.googlegroups.com> On Sep 24, 3:28 pm, kou... at hotmail.com wrote: > [...] where I start getting some errors. > I'm hoping I won't have to post my code "Doctor, I'm feeling bad. I hope I won't have to tell you my symptoms. What do I have?" Please provide the actual errors and the actual code. It is easier, less error prone and more useful to copy and paste them instead of writing some pseudocode. Maybe the repeated index i is a typo you made when writing this post and the original code is correct, but we don't have any way to know that. -- Roberto Bonvallet From jstroud at mbi.ucla.edu Mon Sep 17 01:35:36 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 16 Sep 2007 22:35:36 -0700 Subject: Python statements not forcing whitespace is messy? In-Reply-To: References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> <1189890755.870694.29790@r29g2000hsg.googlegroups.com> <46ec6826$1@news.eftel.com.au> Message-ID: Peter Decker wrote: > On 9/15/07, Steve Holden wrote: >> John Machin wrote: >>> On 16/09/2007 8:11 AM, James Stroud wrote: >>>> Steve Holden wrote: >>>>> I don't know why you have a bug up your ass about it, as the >>>>> Americans say. >>>> I think most Americans say "wild hare up your ass". > >> I guess I got the metaphor wrong? > > Maybe it's a Southern US thing. I've always heard "bug" used; somehow > it doesn't seem that a wild hare would fit! > We say "wild hare" down in Texas. I think I've heard "bug" before, but I wanted an excuse to vent about the hair v. hare issue in some of these American idioms. I guess I have a about it. James From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 21 06:42:58 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 21 Sep 2007 12:42:58 +0200 Subject: Odd files; just left behind? In-Reply-To: References: <878x725ts7.fsf@pobox.com> <46F191DF.7000908@jessikat.plus.net> <46f2bd9b$0$20143$426a74cc@news.free.fr> Message-ID: <46f3a032$0$26141$426a74cc@news.free.fr> Robin Becker a ?crit : > Bruno Desthuilliers wrote: >> Robin Becker a ?crit : >>> John J. Lee wrote: >>> >>>> Robin Becker writes: >>>> >>>>> I see a folder .python-eggs in my home directory on one of our servers >>>>> with various .so files >>>>> >>>>> ~/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so >>>>> >>>>> >>>>> are these just left behind from some install process? >>>> >>>> Ah, it's about the resource extraction feature of setuptools. It's >>>> possible for zipped eggs to contain resources that have to be >>>> extracted to the filesystem. It puts them in the directory you saw >>>> (or somewhere else -- see the docstring in my other reply). >>>> >>>> http://peak.telecommunity.com/DevCenter/PkgResources#resource-extraction >>>> >>>> http://peak.telecommunity.com/DevCenter/setuptools#automatic-resource-extraction >>>> >>> ..... >>> Thanks John, but why not clean up? >>> >> Does it needs to be "cleaned up" ? .so files (shared libs) *need* to >> be extracted from the egg to be usable. Where they are extracted is >> IIRC configurable... > You're right! These files aren't temporary? > It seems strange that the > python files live with their associated lib/site-packages and the .so > files are somewhere entirely different. IIRC, where .so files are extracted is configurable using PYTHON_EGG_CACHE (cf the first link above). > Python 2.3.6 (#1, Jun 7 2007, 10:44:52) > [GCC 3.4.4 [FreeBSD] 20050518] on freebsd6 > Type "help", "copyright", "credits" or "license" for more information. > >>> import MySQLdb > >>> print MySQLdb.__file__ > /myhome/PYTHON/lib/python2.3/site-packages/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg/MySQLdb/__init__.pyc > > >>> import _mysql > >>> print _mysql.__file__ > /myhome/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so > >>> > > it would seem simpler to have the .so files inside the site-packages and > there's the question of why this folder has to be obfuscated (name > starts with .). Even if these files are "resources" why should they be > assumed to belong to the user? Notice that you did install your lib/python in /myhome, not in /usr[/local] (snip) > Just another nonsense from the eggworld Or just another example of not reading the FineManual(tm) ? From rzantow at gmail.com Sat Sep 8 13:33:20 2007 From: rzantow at gmail.com (rzed) Date: Sat, 08 Sep 2007 17:33:20 +0000 Subject: startswith( prefix[, start[, end]]) Query References: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> <46e00d7e$0$16413$426a74cc@news.free.fr> Message-ID: Duncan Booth wrote in news:Xns99A45CD3825D7duncanbooth at 127.0.0.1: I went through your example to get timings for my machine, and I ran into an issue I didn't expect. My bat file did the following 10 times in a row: (the command line wraps in this post) call timeit -s "s='abracadabra1'*1000;t='abracadabra2'; startswith=s.startswith" startswith(t) ... giving me these times: 1000000 loops, best of 3: 0.483 usec per loop 1000000 loops, best of 3: 0.49 usec per loop 1000000 loops, best of 3: 0.489 usec per loop 1000000 loops, best of 3: 0.491 usec per loop 1000000 loops, best of 3: 0.488 usec per loop 1000000 loops, best of 3: 0.492 usec per loop 1000000 loops, best of 3: 0.49 usec per loop 1000000 loops, best of 3: 0.493 usec per loop 1000000 loops, best of 3: 0.486 usec per loop 1000000 loops, best of 3: 0.489 usec per loop Then I thought that a shorter name for the lookup might affect the timings, so I changed the bat file, which now did the following 10 times in a row: timeit -s "s='abracadabra1'* 1000;t='abracadabra2'; sw=s.startswith" sw(t) ... giving me these times: 1000000 loops, best of 3: 0.516 usec per loop 1000000 loops, best of 3: 0.512 usec per loop 1000000 loops, best of 3: 0.514 usec per loop 1000000 loops, best of 3: 0.517 usec per loop 1000000 loops, best of 3: 0.515 usec per loop 1000000 loops, best of 3: 0.518 usec per loop 1000000 loops, best of 3: 0.523 usec per loop 1000000 loops, best of 3: 0.513 usec per loop 1000000 loops, best of 3: 0.514 usec per loop 1000000 loops, best of 3: 0.515 usec per loop In other words, the shorter name did seem to affect the timings, but in a negative way. Why it would actually change at all is beyond me, but it is consistently this way on my machine. Can anyone explain this? -- rzed From ldo at geek-central.gen.new_zealand Sat Sep 22 17:24:24 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 23 Sep 2007 09:24:24 +1200 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: In message <5lhs4pF8bkunU1 at mid.individual.net>, Bjoern Schliessmann wrote: > Lawrence D'Oliveiro wrote: > >> After two decades of putting up with vi just to ensure >> compatibility with every proprietary *nix system I might come >> across, let me just say ... >> >> USE EMACS! > > Nah. Use vim. Every other text editor I have ever used understands that the current position in a file is _between_ two characters (or before the first character, or after the last character), not _on_ a character. But not vi and its ilk. Try the following in vi/vim: Move to some point in the middle of a line. Press "i" to get into insert mode. Press escape to get out again. You'll end up one position to the left of where you were before. Press "i", and then escape again--you've moved another position left. Why is it incapable of keeping track of such a simple thing as your current position in the file? Why does it need two different insert commands, "i" versus "a"? Because one of them can't insert at the end of a line, and the other can't insert at the beginning. And why have command-versus-insert mode at all? No other text editor still surviving uses such an antiquated concept. From lasses_weil at klapptsowieso.net Sat Sep 8 23:01:07 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 09 Sep 2007 05:01:07 +0200 Subject: Parsing nested constructs In-Reply-To: <1189296638.625012.286250@k79g2000hse.googlegroups.com> References: <46e308d3$0$9153$426a74cc@news.free.fr> <1189296638.625012.286250@k79g2000hse.googlegroups.com> Message-ID: <46e361f3$0$7695$9b4e6d93@newsspool2.arcor-online.net> Paul McGuire wrote: > Well, it is an external module, but pyparsing makes this pretty > straightforward: > > [snip delightful parsing] > Again pyparsing to the rescue :) I have to do a parsing project in Java right now and I dearly miss pyparsing. I explained it to the guy I'm working for, and he was pretty impressed. Thought that might make you smile. /W From f.guerrieri at gmail.com Mon Sep 10 06:06:03 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 10 Sep 2007 12:06:03 +0200 Subject: less obvious "super" In-Reply-To: <1189417830.645749.226120@d55g2000hsg.googlegroups.com> References: <1189417830.645749.226120@d55g2000hsg.googlegroups.com> Message-ID: <79b79e730709100306w2fd7b8cai54550434f92c891c@mail.gmail.com> On 9/10/07, Nagarajan wrote: > > Hi group, > I am confused with "super" usage..It seems to be complicated and less > obvious. > Here is what I need to achieve.. > > class A : > def __init__( self ): > self.x = 0 > > class B ( A ): > def __init__( self, something ): > # Use "super" construct here so that I can "inherit" x of A > self.y = something > > How should I use "super" so that I could access the variable "x" of A > in B? > You don't need to use super in this case. You just have to remember to explicitly initialize the classes you are deriving from. In this case, class B(A): def __init__(self, something): A.__init__(self) self.y = something bye, francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From half.italian at gmail.com Thu Sep 13 04:42:35 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Thu, 13 Sep 2007 08:42:35 -0000 Subject: Python+Expect+Win32 = Not Possible? In-Reply-To: <1189657637.539038.317280@k79g2000hse.googlegroups.com> References: <1189657637.539038.317280@k79g2000hse.googlegroups.com> Message-ID: <1189672955.321701.164050@57g2000hsv.googlegroups.com> On Sep 12, 9:27 pm, gamename wrote: > Hi, > > Is it still the case there is no practical Expect-like module for > win32? I know that cygwin can support pexpect, but that isn't an > option here --- I have to use a native win32 Python version. > > Are there alternatives, or is it simply not an option to replicate > Expect on win32 with python? > > All I'm trying to do is start a couple processes, wait for each to say > "done" on stdout and then quit (or timeout if something went wrong). > > TIA, > -T I had planned on using telnet to do the same thing on windows. I don't think I ever proved it, but I'm pretty sure it will work. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52228 ~Sean From laurent.pointal at limsi.fr Thu Sep 13 04:43:18 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 13 Sep 2007 10:43:18 +0200 Subject: read part of jpeg file by pure python In-Reply-To: <1189671634.712690.154580@o80g2000hse.googlegroups.com> References: <1189671634.712690.154580@o80g2000hse.googlegroups.com> Message-ID: Pacino a ?crit : > Hi, everyone, > > I am wondering whether it's possible to read part (e.g. 1000*1000) of > a huge jpeg file (e.g. 30000*30000) and save it to another jpeg file > by pure python. I failed to read the whole file and split it, because > it would cost 2GB memory. > > Can anyone help me? Any comments would be appreciated. > > Thanks. > > Robert > Just reading parts of the *file* is easy (see tell() seek() and read() methods on files). But to extract a part of the *picture*, you must uncompress the picture in memory, grab the sub-picture, and save it back - generally with compression. I can't see how you can bypass the uncompress/compress phases and the corresponding memory use. A+ Laurent. From bdesth.quelquechose at free.quelquepart.fr Sun Sep 2 13:56:15 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 02 Sep 2007 19:56:15 +0200 Subject: TypeError: 'module object is not callable' In-Reply-To: <1188836008.656284.76160@o80g2000hse.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> Message-ID: <46dc6f49$0$6207$426a34cc@news.free.fr> christophertidy at hotmail.com a ?crit : (snip) > > I have another little question before I finish today: > I am currently struggling to use a global variable in my static > functions. I'll explain further > > Within my main.py file I have > > class Main(object): > stepStore = StepStore() > > @staticmethod > def createDepSteps(): > .... > stepStore.addStep([bol7, pre5]) > ....... > > @staticmethod > def processSteps(): > for step in stepStore.stepList[:]: > ...... > > Main.createDepSteps() > Main.processSteps() > (snip) Marc and Diez already gave you the good answers on this (basically: get rid of useless classes, and use plain functions instead of staticmethods). I'd just add a couple comments: First point: OO is not about classes, it's about objects - FWIW, the mere concept of 'class' is nowhere in the definition of OO, and some OOPLs don't even have that concept (cf Self and Javascript). Second point : in Python, everything (well... almost - at least everything that can be bound to a name) is an object. So Python's modules and functions are objects. Third point : "top-level" (aka 'module level', aka 'globals') names (names defined outside classes or functions) are in fact module attributes. So, to make a long story short, you can consider a module as a kind of a singleton. What I wanted to point out here is that there's much more to OO than what one learns with Java - and, FWIW, much more to Python's object model than what it may seems at first. Ah, and, BTW : welcome here !-) From stefan.arentz at gmail.com Thu Sep 6 04:47:52 2007 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 06 Sep 2007 10:47:52 +0200 Subject: We need PIGs :) References: <46d74472$0$402$426a34cc@news.free.fr> <87hcm81dot.fsf@kip.sateh.com> <5k9qpsF2mrncU3@mid.uni-berlin.de> Message-ID: <877in418p3.fsf@kip.sateh.com> Marc 'BlackJack' Rintsch writes: > On Thu, 06 Sep 2007 09:00:02 +0200, Stefan Arentz wrote: > > > What I find really frustrating in Python (combined with usually bad > > documentation) is that many people have different styles. The most > > frustratinng being getFoo() vs .foo, vs get_foo(). > > `getFoo()` is discouraged by PEP 8. You don't have the choice between > `.foo` and `.get_foo()` in Java because Java has no properties and people > are trained to write getters and setters for everything. I like that > choice in Python because I can write shorter code that is not cluttered > with very simple getters and setters. I like that too, but unfortunately not everybody is doing it. Unpredictable code (apis) is in my opinion the biggest productivity killer. S. From jjl at pobox.com Thu Sep 20 15:13:54 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 20 Sep 2007 19:13:54 GMT Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> Message-ID: <87odfxjgjy.fsf@pobox.com> "W. Watson" writes: > Thanks, but no thanks. The learning curve is way too steep. [...] Eclipse must be able to do this. Eclipse is emacs for stupid people ;-) Seriously for a moment, I read something recently (maybe here?) about an Apple study that claimed to show that people who perceived keyboard bindings as being much faster than mouseing did not, on average, take less time to complete the actions that were studied (they took more time, in fact). The plausible explanation for this was that people's subjective perception of time is affected by the greater mental work involved in typing (as opposed to mousing) for a given action. I suspect the reality is at neither extreme (nor "somewhere in the middle"). John From AnonMail2005 at gmail.com Wed Sep 5 18:05:04 2007 From: AnonMail2005 at gmail.com (AnonMail2005 at gmail.com) Date: Wed, 05 Sep 2007 15:05:04 -0700 Subject: Registering a python function in C In-Reply-To: <1188861109.041382.178950@d55g2000hsg.googlegroups.com> References: <1188508874.879215.319400@i13g2000prf.googlegroups.com> <1188516423.744038.309700@z24g2000prh.googlegroups.com> <1188588784.764658.317570@r34g2000hsd.googlegroups.com> <1188592047.542946.249520@57g2000hsv.googlegroups.com> <1188861109.041382.178950@d55g2000hsg.googlegroups.com> Message-ID: <1189029904.265510.185540@22g2000hsm.googlegroups.com> On Sep 3, 7:11 pm, fernando wrote: > > Is Maya a different python build than what is contained at python.org? > > If so, I suggest you get your C program to work with the latest python > > build > > from python.org. Then see if you can get it to work with the Maya > > version. > > Ok, did that. If I write a normal C++ program and use the python > installed in my system, everything works ok and I can call the python > funtions. From within maya(where the C code is running as a plugin), > nothing happens. I tried removing my python installation so that only > the one that comes with maya is running, but then I have no python.h > or libs to compile against!! I found no help at the maya/python > newsgroup, is there anyone who has done this before??? > > Thanks for all the help! >From what I understand, it seems like maya includes a python build/ download when you download maya. You should be able to get the libs and include files from there. It also looks like maya explicitly says what python build it uses when it is started up interactively. I would bet that your installation of maya and your (different) installation of python are conflicting. From henriklied at gmail.com Thu Sep 27 05:14:07 2007 From: henriklied at gmail.com (Henrik Lied) Date: Thu, 27 Sep 2007 09:14:07 -0000 Subject: "No backend servers available" using httplib Message-ID: <1190884447.792688.107710@g4g2000hsf.googlegroups.com> Hi there! I'm using a recipe found on ASPN [1] to upload some data to an external server. The request fails, and all I get in response is "No backend servers available". So I'm wondering: Is this a known exception-message in httplib, or could it be an error in the requested external resource? [1]: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 ----- Thanks, Henrik From newsuser at stacom-software.de Tue Sep 25 09:23:51 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Tue, 25 Sep 2007 15:23:51 +0200 Subject: PyQt disconnect signal / slot Message-ID: Hello PyQt experts, do i have to disconnect all signal/slots, after the emitting object is deleted, or does it the QObject destructor? Thanks Alexander From pyth0nc0d3r at gmail.com Sat Sep 1 18:03:57 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Sat, 1 Sep 2007 17:03:57 -0500 Subject: Windows Media Player Playlist Message-ID: Is it possible to use python to get the current playlist of the current playing songs from Windows Media Player or Windows Player Classic? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sharinginfo4 at gmail.com Wed Sep 26 09:06:38 2007 From: sharinginfo4 at gmail.com (Laptop secret) Date: Wed, 26 Sep 2007 13:06:38 -0000 Subject: The Big Secret inside your Laptop /Computer Message-ID: <1190811998.697399.223470@k79g2000hse.googlegroups.com> HI, We may not aware that the laptop you bring around has abig secret inside. Some of expert may have known it and keep it as secret. If you are fond of browsing in internet you may probably discover it. Read further thru this site and you may find out : http://sharinginfo4.googlepages.com/home Have a great time then, Steven From steve at holdenweb.com Mon Sep 17 14:20:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Sep 2007 14:20:10 -0400 Subject: Try this In-Reply-To: <1190051875.433350.150820@50g2000hsm.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> <1190008502.986300.286280@22g2000hsm.googlegroups.com> <1190051875.433350.150820@50g2000hsm.googlegroups.com> Message-ID: <46EEC55A.9070602@holdenweb.com> mensanator at aol.com wrote: > On Sep 17, 6:09 am, Steve Holden wrote: >> mensana... at aol.com wrote: >>> On Sep 16, 9:27?pm, "Gabriel Genellina" >>> wrote: >>>> En Sun, 16 Sep 2007 21:58:09 -0300, mensana... at aol.com >> [...] >>>> What about the rest of the world that don't speak >>>> English or even worse, don't use the Latin alpabet? >>> When the rest of the world creates the next >>> generation of computers, THEY can chosse the >>> defaults. >> Right, because of course US companies have no desire to do business with >> the rest of the world. > > I'm merely pointing out that it is the legacy of the history of > information technology that is chauvinistic. That happens to be > the way things are, I did not say that's the way they should be. > You imply that's the way they should be by placing pre-conditions on the adoption of anything but ASCII as a default. >> I'm not given to ad hominem attacks, but this remark really seems to >> indicate that "chauvinistic cretin" might apply to you. > > _I_ didn't invent ASCII or EBCDIC. Why weren't the European > and Chinese languages considered when these were developed > 40-50 years ago? Because they were "chauvinistic cretins"? > Is that what you think? > No. In those days (sixty years ago) less was possible, and achieving anything, however limited, represented progress. Certainly it would have been nice to see the adoption of more internationally-applicable standards, but the codes that were used in the early computes had their roots in even earlier information systems like teletypes and telex machines. It was partly a matter of adapting what already existed. In these more enlightened times we can build systems for larger audiences by making them applicable to a wider range of languages and character sets. The standards and the technology already exist to do so. So, "chauvinistic" because you appear to require the users of the non-ASCII parts of Unicode to contribute something before they get systems that suit their needs, when in fact the boot is on the other foot and it behooves the manufacturers to adapt to market needs if they want to serve those markets. "Cretin" (in the sense of possessing sub-normal intelligence, as I do not know whether or not you have a thyroid deficiency) because you do not seem to be able to think of the needs of the larger community, and respond to argument with non-sequitur and evasion. Plus, you annoyed me. I should have restrained myself. Sorry. >> You'll be gald >> to know you are unlikely to hear from me again. > > Why? Because I tend to act as a gadfly? To point out that > the emperor is, in fact, naked? Because the professional > programming community doesn't like their dirty laundry > aired in public? > No, because everything you discuss appears to be discussed in the most simplistic terms, with limited perspective. So a discussion with you is about as satisfying as a discussion with a twelve year old child. >> Your perception of the development of information technology is so >> skewed you would be better off knowing nothing. > > My perception is skewed? Why then, does Unicode even exist? > To meet real needs which you appear to feel shouldn't be met until the people with those needs have built their own information technologies (or in your words "created the next generation of computers."). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From jjl at pobox.com Sat Sep 22 03:12:49 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 22 Sep 2007 07:12:49 GMT Subject: UTF-8 characters in doctest References: <1190202459.229197.297350@n39g2000hsh.googlegroups.com> <878x71jfwo.fsf@pobox.com> Message-ID: <8764235g26.fsf@pobox.com> Peter Otten <__peter__ at web.de> writes: [...] >> Forgive me if this is a stupid question, but: What purpose does >> function f serve? > > Like the OP's get_inventary_number() it takes a unicode string and > returns a tuple of unicode strings. I'ts pointless otherwise. I hoped I > had stripped down his code to a point where the analogy was still > recognizable. Ah, right. John From steve at REMOVE-THIS-cybersource.com.au Thu Sep 6 09:18:12 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Sep 2007 13:18:12 -0000 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> Message-ID: <13dvvgk96amhhec@corp.supernews.com> On Thu, 06 Sep 2007 15:44:57 +1000, bambam wrote: > First, thank you. > > All of the suggestions match what we want to do much better than what we > are doing. We have a script, written in python, which is doing testing. > But the python script doesn't look anything like the test script, > because the python script is written in python, and the test script is a > series of instrument command macros. > > By putting the script sequence into a collection that is separate from > the python code, we will get script list that general engineering will > find much easier to understand: > > > def script(self) > def a0010(): global self; self.power_on([self.dev]); > def a0020(): global self; self.dev.addLog([self.name, ' started']); > def a0030(): global self; self.resetMinuteReg([self.dev]); > def a0040(): global self; self.disablePLmessages([self.dev]); > def a0050(): global self; self.dev.testH.writePLram((PL.BCAL12<<8)); That's rather hideous code, and I'm not sure I understand what it's supposed to do. As far as I can tell, you have a function called "script" which takes a single argument. It then defines five functions, throws them away, and returns None. "self" is not a reserved word in Python (although perhaps it should be...) but it has a VERY strong convention for when to use it: when defining instance methods, it is used for the automatically-supplied instance argument. The above functions look like they were written by somebody who has just copied some methods from another piece of code without understanding what they were seeing. (Sorry.) > Most of these won't generate exceptions: exceptions are expected only on > the calculations following the reads, but of course the problem is that > the exceptions are unexpected... I don't think so. I think they are expected. You say so yourself. > The semi-colons were already there, Fine. Time to remove them. > I've just stripped out the loops and exception handlers. The original > code is a mixture of functions with internal and external [dev] loops. > > Because of the sequence names, I have a choice of using generated call > names (James), or a static list of some sort. > > Other possibilities might be > 1) Using dir(script) to get a list of line functions 2) Using > frame.f_lineno instead of line functions 3) Use an expression list > instead of line functions 4) Multiple script objects with yield on each > line. My brain hurts. > The devices are in a list, and are removed by using pop(i). This messes > up the loop iteration, so it is actually done by setting a flag on each > device in the exception handler, with ANOTHER loop after each > write/read/calculate sequence. I left that out also because I wanted to > show the intended logic. Try something like this: define a module holding the device functions. Rather than have the functions access a global variable, which is almost always a bad thing to do, have them take a single argument. # module device __all__ = [a0010, a002, a0030, a0040, a0050] def a0010(obj): obj.power_on([obj.dev]) def a0020(obj): obj.dev.addLog([obj.name, ' started']) def a0030(obj): obj.resetMinuteReg([obj.dev]) def a0040(obj): obj.disablePLmessages([obj.dev]) def a0050(obj): obj.dev.testH.writePLram((PL.BCAL12<<8)) Now define a second module to call those functions. # module tester import device passed = device.__all__[:] # a copy of the list some_object = Something() # I have no idea what this should be... for function in device.__all__: try: function(some_object) except Exception, e: print e passed.remove(function) print "The following functions passed:" for function in passed: print function And then I suggest you spend some time reading up about doc tests and unit tests. Hope this helps, -- Steven. From jjl at pobox.com Sat Sep 22 14:21:07 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 22 Sep 2007 18:21:07 GMT Subject: frange() question References: <87tzppjhe4.fsf@pobox.com> <87lkaz40sj.fsf@pobox.com> Message-ID: <87odfuwoh8.fsf@pobox.com> Carsten Haese writes: > On Sat, 2007-09-22 at 07:27 +0000, John J. Lee wrote: >> Carsten Haese writes: >> >> > On Thu, 2007-09-20 at 18:55 +0000, John J. Lee wrote: >> >> Functions are never generators, senso stricto. There are "generator >> >> functions", which *return* (or yield) generators when you call them. >> > >> > Actually, a generator function is a function that returns a generator. >> >> Read what I wrote again. What makes you begin your sentence with >> "Actually", rather than "Putting it another way"? > > I was attempting to correct your interjection "(or yield)." A generator > function doesn't yield a generator; it returns a generator that yields > sequence values. OK. There's an obvious second language issue here (the first being the generator / generator function), which I was trying to draw attention away from, in the interests of explaining the concept, and the first language issue. Probably a bad idea! > The second half of my post illustrates a difference of opinion about > what constitutes a generator function. You state that frange() is not a > generator function because it doesn't use yield, but it behaves like > one. My point is that it *is* a generator function because the generator > expression is merely syntactic sugar for an equivalent for/yield loop. Seems to me that's a definitional thing, with no conceptual content, so "difference of opinion" seems an odd choice of words. It would be nice to nail the definitions down. Do the Python docs do that? > Of course, the distinction of whether frange() *is* a generator function > or merely *behaves* as one is immaterial in practice, and we can both be > right in the absence of a formal definition of what a generator function > is. PEP 255 says "A function that contains a yield statement is called a > generator function," but that was written before generator expressions > were introduced. Ah, they do -- thanks. Though I'm now left puzzled why you express your "difference of opionion" above... John From steve at holdenweb.com Fri Sep 28 18:16:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 18:16:51 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191013033.145194.193040@50g2000hsm.googlegroups.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <%q0Li.725$ih1.539@nlpi068.nbdc.sbc.com> <1i555ag.9ez4uvf4583jN%aleax@mac.com> <1191013033.145194.193040@50g2000hsm.googlegroups.com> Message-ID: <46FD7D53.1060403@holdenweb.com> Kay Schluehr wrote: > On 28 Sep., 17:53, John Nagle wrote: >> Alex Martelli wrote: >>> John Nagle wrote: >>>> TheFlyingDutchman wrote: >>>>> It seems that Python 3 is more significant for what it removes than >>>>> what it adds. >>>>> What are the additions that people find the most compelling? >>>> I'd rather see Python 2.5 finished, so it just works. >>> And I'd rather see peace on Earth and goodwill among men than _either_ >>> Python 3 or your cherished "finished" 2.5 -- the comparison and implied >>> tradeoff make about as much sense as yours. >> Insofar as Python has an organization, it's not adequately managing >> extension modules. Each extension module has its own infrastructure, >> with its own build procedures, its own bug list, and its own maintainers. >> There's not even an archive. Unlike CPAN, Cheese Shop is just a directory of >> URLs. > > John, can't you please piss off? > > Thanks, Kay > Oops! Let's get back to goodwill and peace to all men, can we - including {Flying Dutch,wo}men? crabbi-ly y'rs - steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From justin.mailinglists at gmail.com Sun Sep 9 21:53:56 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Mon, 10 Sep 2007 01:53:56 -0000 Subject: MySQLdb: ValueError Something Stupid In-Reply-To: <1189175986.343368.221520@d55g2000hsg.googlegroups.com> References: <1189163332.990248.134080@d55g2000hsg.googlegroups.com> <1189169527.020589.185120@w3g2000hsg.googlegroups.com> <1189175986.343368.221520@d55g2000hsg.googlegroups.com> Message-ID: <1189389236.503269.14670@g4g2000hsf.googlegroups.com> On Sep 7, 10:39 pm, mcl wrote: > On 7 Sep, 14:11, Carsten Haese wrote: > > > > > On Fri, 2007-09-07 at 05:52 -0700, mcl wrote: > > > > ValueError: invalid literal for int(): 0- > > > > args = ('invalid literal for int(): 0-',) > > > > > ========================================= > > > > Thanks Richard > > > > Sort of solved it. > > > > On that particular table it did not like * for all fields. > > > > Any reason why that would be the case ? > > > None that we can divine without more information. What's the schema for > > the table in question, which column(s) are you excluding to make the > > query work, and what kind of data is in the column(s) you're excluding? > > > -- > > Carsten Haesehttp://informixdb.sourceforge.net > > Thanks for replying. > > I did not exclude any columns and the Schema is: > > CREATE TABLE lstData ( > qlCat varchar(20) NOT NULL default '', > qlTitle varchar(255) NOT NULL default '', > qlSubTitle varchar(255) default NULL, > qlDetails text, > qlPic varchar(20) default NULL, > qlPostCode varchar(16) default NULL, > qlUpd timestamp NOT NULL default '0000-00-00 00:00:00' on update > CURRENT_TIMESTAMP, > KEY `idx-qlCat` (qlCat) > ) ENGINE=MyISAM DEFAULT CHARSET=latin1; > > Thanks again > > Richard saw this before on earlier MySQLdb and timestamp column try upgrading your MySQLdb see https://bugzilla.redhat.com/show_bug.cgi?id=155341 or http://www.ravenbrook.com/project/p4dti/master/code/replicator/mysqldb_support.py From steven.bethard at gmail.com Fri Sep 28 09:51:49 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Sep 2007 07:51:49 -0600 Subject: Numeric command-line options vs. negative-number arguments In-Reply-To: <87wsub2s4w.fsf@benfinney.id.au> References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <0a6dnQmBPIzuqmHbnZ2dnUVZ_vihnZ2d@comcast.com> <87ejgj4lpy.fsf_-_@benfinney.id.au> <87wsub2s4w.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Steven Bethard writes: >> Argparse knows what your option flags look like, so if you specify >> one, it knows it's an option. Argparse will only interpret it as a >> negative number if you specify a negative number that doesn't match >> a known option. > > That's also irritating, and violates the expected behaviour. It leads > to *some* undefined options being flagged as errors, and others > interpreted as arguments. The user shouldn't need to know the complete > set of options to know which leading-hyphen arguments will be treated > as options and which ones won't. > > The correct behaviour would be to *always* interpret an argument that > has a leading hyphen as an option (unless it follows an explicit '--' > option), and complain if the option is unknown. It was decided that practicality beats purity here. Arguments with leading hyphens which look numeric but aren't in the parser are interpreted as negative numbers. Arguments with leading hyphens which don't look numeric and aren't in the parser raise errors. Sure, it's not the pure answer, but it's the practical answer: "-123" is much more likely to be a negative number than an option. STeVe From paul.nospam at rudin.co.uk Wed Sep 19 02:50:41 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 19 Sep 2007 07:50:41 +0100 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <13f196qktorgc88@corp.supernews.com> <873axbxl2f.fsf@benfinney.id.au> Message-ID: <87wsunjghq.fsf@rudin.co.uk> Ben Finney writes: > Possibly the name 'next_in_mro', while ugly, would at least match the > actual behaviour of this function. In common lisp there's (call-next-method ...) From lasses_weil at klapptsowieso.net Sun Sep 9 08:11:06 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 09 Sep 2007 14:11:06 +0200 Subject: Python syntax wart In-Reply-To: <13e7ddd9hgibae6@corp.supernews.com> References: <13e7ddd9hgibae6@corp.supernews.com> Message-ID: <46e3e2db$0$30369$9b4e6d93@newsspool4.arcor-online.net> Steven D'Aprano wrote: > That is quite possibly the ugliest piece of code I've ever seen in > Python. I'm impressed. Did you format it yourself or did you use a > professionally written code-uglifier? > Boy did that make me laugh! The notion of a "code uglifier" just is a pearl. (I hate to call attention to these things, but that was actually a pun. I'm just too proud of it.) /W From bdesth.quelquechose at free.quelquepart.fr Fri Sep 21 20:14:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 22 Sep 2007 02:14:52 +0200 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190454275.282176.90830@k79g2000hse.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> <1190454275.282176.90830@k79g2000hse.googlegroups.com> Message-ID: <46f6e9b0$0$32168$426a74cc@news.free.fr> Kay Schluehr a ?crit : (snip) > > I checked out Io once and I disliked it. I expected Io's prototype OO > being just a more flexible variant of class based OO but Io couples a > prototype very closely to its offspring. When A produces B and A.f is > modified after production of B also B.f is modified. A controls the > state of B during the whole lifetime of B. I think parents shall not > do this, not in real life and also not in programming language > semantics. I may totally miss the point, but how is this different from: class A(object): def dothis(self): print "A.dothis(%s)" % self class B(A): pass b = B() b.dothis() def dothat(self): print "function dothat(%s)" % self A.dothis = dothat b.dothis() From python-url at phaseit.net Mon Sep 10 08:27:08 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 10 Sep 2007 12:27:08 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 10) Message-ID: QOTW: "Python is a revelation to me as a language that grows with the ability of the programmer, which creates a multi-level community not too centered on one-upmanship to nurture new talent." - John K Masters "Python is a well designed language that focuses on a few simple ideas (name semantics, dictionaries, simplicity of expression, trusting the programmer) to make a surprisingly powerful and expressive language." - Steven Rumbalski Why should I learn python? http://groups.google.com/group/comp.lang.python/browse_thread/thread/e0ec3289a995997e/ Examining (the lack of) access specifiers in Python and how "information hiding" is obtained http://groups.google.com/group/comp.lang.python/browse_thread/thread/71ef60e2d3203702/ (FAQ) Two names referencing the same mutable object. Pointers, references, the Java model, and how things are different in C++. http://groups.google.com/group/comp.lang.python/browse_thread/thread/d05183ffe7d473c1/ The module operator (%) differs slightly from its C counterpart http://groups.google.com/group/comp.lang.python/browse_thread/thread/a559c5ab2b8fe45a/ Several ways to generate unique identifiers http://groups.google.com/group/comp.lang.python/browse_thread/thread/3db6fef289d93a9c/ Extending the Borg pattern to support distinct groups of objects http://groups.google.com/group/comp.lang.python/browse_thread/thread/8cc3b3bc924ed0f6/ exec and the local and global namespaces http://groups.google.com/group/comp.lang.python/browse_thread/thread/16eaad6c94c4daed/ Generating "safe" filenames suitable for different platforms. http://groups.google.com/group/comp.lang.python/browse_thread/thread/aae0fbf0a370c761/ ======================================================================== 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 Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. 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 enthusiats": 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/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ 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/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch 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://aspn.activestate.com/ASPN/Cookbook/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 are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php 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/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. 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 *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python 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 bjorn.kempen at gmail.com Sat Sep 15 17:12:35 2007 From: bjorn.kempen at gmail.com (buffi) Date: Sat, 15 Sep 2007 21:12:35 -0000 Subject: Python statements not forcing whitespace is messy? In-Reply-To: References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> Message-ID: <1189890755.870694.29790@r29g2000hsg.googlegroups.com> On Sep 15, 10:11 pm, "J. Cliff Dyer" wrote: > buffi wrote: > > Am I the only one that thinks that python statements should force > > whitespace before and after them? > > > Right now this is not enforced and for an example these statements are > > valid > > > print"hello" > > "foo"if"bar"else"foobar" > > for(x,y)in[(1,2),(3,4)]:print(x,y) > > [(y)for(x,y)in[("foo",2),("bar",4)]if"foo"in(x)] > > > ...and so on. > > On the other hand, this is just as bad: > > [ ( y ) for ( x , y ) in [ ( "foo" , 2 ) , ( "bar" , 4 ) ] if "foo" in ( > x ) ] > > And I'd hate to have to remember all of the rules for what can go > together and what can't, especially when it comes time to debug. No. > I don't think it should be forced, but maybe put it in PEP8 or PEP3008. > > Also, the only thing I find thoroughly disagreeable in all of that > mess, is the run-ins involving " characters. The rest are at least > clear at a glance what belongs where. > > Also, would you require the following? > > my_function (swallow='European') > > Because that is just an awful use of whitespace. > > Cheers, > Cliff I believe that having whitespace around the builtin statements, and having whitespace around everything is pretty different. There would be no downside whatsoever to enforcing this, except for backwards incompatibility (which is a rather huge downside but well... py3k is gonna break everything anyways). There obviously shouldnt be any limit to the maximum amount of whitespace used around statements (due to formatting and so on), but allowing stuff like print"hello" is just horrible. - Bj?rn Kemp?n From perl4hire at softouch.on.ca Thu Sep 13 04:06:50 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Thu, 13 Sep 2007 04:06:50 -0400 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> Message-ID: <2b6Gi.222$372.110@read2.cgocable.net> Amer Neely wrote: > TheFlyingDutchman wrote: >> On Sep 12, 5:30 pm, Amer Neely wrote: >>> I'm a complete newbie with Python, but have several years experience >>> with Perl in a web environment. >>> >>> A question I have, if someone here is familiar with Perl, does Python >>> have something like Perl's 'here document'? I've just searched and read >>> some postings on generating HTML but they all seem to refer to various >>> template utilities. Is this the only way, or am I missing something? I'm >>> used to generating X/HTML by hand, which makes the here document in Perl >>> ideal for me. Also, many times a client already existing HTML code that >>> I can use in a script. >>> >>> -- >>> Amer Neely >>> w:www.webmechanic.softouch.on.ca/ >>> Perl | MySQL programming for all data entry forms. >>> "Others make web sites. We make web sites work!" >> >> I am not sure if this is what you are looking for, but Python has a >> special string with 3 quotes that I believe duplicates part of the >> functionality of a here document: >> >> myHmtlHeader = """ >> >> My Page >> >> """ >> >> print myHtmlHeader >> >> >> outputs: >> >> >> >> My Page >> >> > > Well, I have checked everything I can but I'm getting '500 Internal > Server Error'. The log files aren't helpful: > [Thu Sep 13 03:43:00 2007] [error] [client 24.235.184.39] Premature end > of script headers: /home/softouch/public_html/cgi-bin/scratch/hello.py > > I can't even get it to run on my home PC running Apache + Win2K. Same > error. > > My script: > #!/usr/bin/python > import cgitb; cgitb.enable(display=0, logdir=".") > import sys > sys.stderr = sys.stdout > print "Content-Type: text/html" > print > > print """ > > >
Hello > from Python
>
> Goodbye. > > > """ > I should have added that it runs from the command line OK. -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From tdelaney at avaya.com Wed Sep 5 19:34:44 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 6 Sep 2007 07:34:44 +0800 Subject: creating really big lists In-Reply-To: <874pi92tr4.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > Dr Mephesto writes: > >> I would like to create a pretty big list of lists; a list 3,000,000 >> long, each entry containing 5 empty lists. My application will >> append data each of the 5 sublists, so they will be of varying >> lengths (so no arrays!). >> >> Does anyone know the most efficient way to do this? I have tried: >> >> list = [[[],[],[],[],[]] for _ in xrange(3000000)] > If you're building large data structures and don't need to reclaim > cyclical references, I suggest turning GC off, at least during > construction. This is good advice, but another question is whether you really want such a list. You may well be better off with a database of some kind - they're designed for manipulating large amounts of data. Tim Delaney From rustompmody at gmail.com Sat Sep 15 04:59:45 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 15 Sep 2007 14:29:45 +0530 Subject: c interfacing in 2.5 Message-ID: I used python extensive 3-5 years back. Coming back I find some changes. Trying to understand whats new and would appreciate any help/comments/pointers. Earlier there were basically two options: SWIG: convenient but inefficient Native (Extending/Embedding): an efficient way of getting a headache! (Boost being ignored because not using C++) Now it seems there are more possibilities: -- Sip seems to be more efficient than swig and easier than native but not well documented -- pyrex could be considered -- I know someone who uses pygtk to make wrappings But most interesting is ctype. I wonder if having ctype in the core language changes the ease of use of the native wrapping model and thereby makes sip/swig etc less necessary? Your views and/or experience appreciated. From ricaraoz at gmail.com Tue Sep 4 19:35:39 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 04 Sep 2007 20:35:39 -0300 Subject: REGULAR EXPRESSION In-Reply-To: References: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> Message-ID: <46DDEBCB.3000704@bigfoot.com> Steve Holden wrote: > AniNair wrote: >> hi.. I am trying to match '+ %&/-' etc using regular expression in >> expressions like 879+34343. I tried \W+ but it matches only in the >> beginning of the string Plz help Thanking you in advance... >> > Perhaps you could give a few example of strings that should and > shouldn't match? It isn't clear from your description what pattern you > are trying to find. > > regards > Steve If it's operations between two numbers try : r'([\d.]+?)\s*([-+/*%&])([\d.]+)' It will give you 3 groups, first number, operation and second number (caveat emptor). From steve at holdenweb.com Sat Sep 15 15:44:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 15 Sep 2007 15:44:46 -0400 Subject: find and remove "\" character from string In-Reply-To: <46EC09A5.7050609@yahoo.gr> References: <46EC09A5.7050609@yahoo.gr> Message-ID: Konstantinos Pachopoulos wrote: > Hi, > i have the following string s and the following code, which doesn't > successfully remove the "\", but sucessfully removes the "\\". > > >>> s="Sad\\asd\asd" > >>> newS="" > >>> for i in s: > ... if i!="\\": > ... newS=newS+i > ... > >>> newS > 'Sadasd\x07sd' > In actual fact there was just a single backslash in s to start with. If you read the documentation carefully at http://docs.python.org/ref/strings.html (though it's the language reference manual, and therefore not necessarily suitable reading for beginners) you will see that the "\\" represents a single backslash character and \a represents an ASCII BEL character (whose decimal value is 7, and which the interpreter represents as the hexadecimal escape string \x07). So the characters in s were S a d \ a s d \x07 s d and you shoudl have seen len(s) == 10. As has already been mentioned, the shortest way to do what you want would be newS = s.replace("\\", "") > I have also read the following, but i do not understand the "...and the > remaining characters have been mapped through the given translation > table, which must be a string of length 256". Can some explain? > > *translate*( table[, deletechars]) > > Return a copy of the string where all characters occurring in the > optional argument deletechars are removed, and the remaining > characters have been mapped through the given translation table, > which must be a string of length 256. > > For Unicode objects, the translate() method does not accept the > optional deletechars argument. Instead, it returns a copy of the s > where all characters have been mapped through the given translation > table which must be a mapping of Unicode ordinals to Unicode > ordinals, Unicode strings or |None|. Unmapped characters are left > untouched. Characters mapped to |None| are deleted. Note, a more > flexible approach is to create a custom character mapping codec > using the codecs > module (see encodings.cp1251 for an example). > The translate() string method uses the numeric represetation of each character as an index into the translation table. So a null translation table can be constructed using >>> t = "".join(chr(i) for i in range(256)) >>> t '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\ x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABC DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83 \x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97 \x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab \xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf \xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3 \xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7 \xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb \xfc\xfd\xfe\xff' >>> (the above output will look a little screwy in the mail because of odd line wrapping). So hopefully you could then achieve the same effect (at vastly greater complexity than the first solution) using >>> s="Sad\\asd\asd" >>> len(s) 10 >>> newS = s.translate(t, "\\") >>> newS 'Sadasd\x07sd' >>> You would probably only want to use that method if you were actually translating some of the characters at the same time. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 7 11:33:26 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 07 Sep 2007 17:33:26 +0200 Subject: Class design (information hiding) In-Reply-To: References: <46e1305e$0$18302$426a74cc@news.free.fr> Message-ID: <46e16f3f$0$26262$426a74cc@news.free.fr> Alexander Eisenhuth a ?crit : > Bruno Desthuilliers schrieb: > >> Nope. It's either 'interface' (no leading underscore), >> 'implementation' (single leading underscore), 'implementation with >> some protection against accidental overriding' (two leading underscores). > > What do you mean with 'implementation'? What does it express? The fact that a given attribute (or method - which are just callable attributes FWIW) is an implementation detail, and not a part of the class interface. From tmp-pythonlist at tschreiner.org Wed Sep 26 16:40:18 2007 From: tmp-pythonlist at tschreiner.org (Thomas Schreiner) Date: Wed, 26 Sep 2007 22:40:18 +0200 Subject: stdout and embedding into Windows apps In-Reply-To: <46F1135A.3020301@tschreiner.org> References: <46F1135A.3020301@tschreiner.org> Message-ID: <46FAC3B2.7020802@tschreiner.org> Hi, > I'm extending a windows application (C++) by embedding Python calls. > It seems to be a known problem that windows applications detach > immediately from the calling console, so that all output to stdout > (from both C++ and Python) doesn't get shown anywhere. > > A workaround seems to be the allocation of a windows console and > redirecting stdout to it: > > AllocConsole(); freopen("conin$", "r", stdin); freopen("conout$", > "w", stdout); freopen("conout$", "w", stderr); > > Still, this console only shows the output of my C++ application, not > the output of the embedded python calls. > > The following code Py_Initialize(); std::cout << "start printing..." > << std::endl; PyRun_SimpleString("print('PRINT')\n"); std::cout << > "done printing." << std::endl; > > only prints > > start printing... done printing. > > Does anybody know how to fix this issue? Basically I want to get an > ipython console running in the background of my Windows app, so that > I can process its data. for the files: I got close to what I wanted using WConio: http://newcenturycomputers.net/projects/wconio.html I basically wrote my own class that I used for overwriting stdin and stdout and that internally used WConio. This still doesn't allow readline functionality from windows consoles, but still it's better than nothing. If you have any additional ideas, especially about how I can still use readline despite of overwriting stdin/stdout, please CC me. Cheers, Thomas -- Thomas Schreiner, AGBS Max Planck Institute for Biological Cybernetics 72076 Tuebingen / Germany http://www.isistius.de From gagsl-py2 at yahoo.com.ar Mon Sep 10 05:25:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 10 Sep 2007 02:25:50 -0700 Subject: Setting stdout encoding Message-ID: <1189416350.069995.220250@w3g2000hsg.googlegroups.com> En Sun, 09 Sep 2007 17:49:14 -0300, Fabio Zadrozny escribi?: Does someone know if there's a way to explicitly set the stdout/stderr/ stdin encoding that python should use? The encoding can be set using the C API for file objects - from Python code, use ctypes: py> from ctypes import * py> PyFile_SetEncoding = pythonapi.PyFile_SetEncoding py> PyFile_SetEncoding.argtypes = (py_object, c_char_p) py> if not PyFile_SetEncoding(sys.stdout, "hex"): ... raise ValueError ... py> print "Hello" Hello py> print u"Hello" 48656c6c6f -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Sep 21 04:02:41 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Sep 2007 05:02:41 -0300 Subject: newb: BeautifulSoup References: <1190343890.375836.78630@r29g2000hsg.googlegroups.com> Message-ID: En Fri, 21 Sep 2007 00:04:50 -0300, crybaby escribi?: > I need to traverse a html page with big table that has many row and > columns. For example, how to go 35th td tag and do regex to retireve > the content. After that is done, you move down to 15th td tag from > 35th tag (35+15) and do regex to retrieve the content? See the examples at the BeautifulSoup page http://www.crummy.com/software/BeautifulSoup/ -- Gabriel Genellina From steve at holdenweb.com Tue Sep 25 13:48:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 25 Sep 2007 13:48:45 -0400 Subject: comparing elements of a list with a string In-Reply-To: References: <1190734785.439839.303030@50g2000hsm.googlegroups.com> Message-ID: Larry Bates wrote: > Shriphani wrote: >> Hello all, >> I have a problem here. I have a list named list_of_files which >> contains filenames with their timestamps attached to the name. If I >> have a string "fstab", and I want to list out the files in whose names >> the word fstab appears should I go about like this : >> >> def listAllbackups(file): >> list_of_files = os.listdir("/home/shriphani/backupdir") >> for element in list_of_files: >> if element.find(file) != -1: >> date = ### >> time = #### >> return (date, time) >> >> The major trouble is that the return statement causes it to exit after >> attempt one. How do I use the yield statement here? >> >> Regards, >> Shriphani Palakodety >> > > You should take a quick look at glob(). You may be able to use it to make life > a lot easier. Here is how you would do it if all your backup files begin with > fstab. > > import glob > list_of_backup_files=glob.glob('/home/shriphani/backupdir/glob*') > > If "fstab" can appear anywhere in the filename, this might not work for you. > I don't see why list_of_backup_files=glob.glob('/home/shriphani/backupdir/*fstab*') shouldn't work. However, t answer the OP's question about yield (which nobody seems to have done fully yet): 1. Rewrite the function to become a generator function: def listAllbackups(file): list_of_files = os.listdir("/home/shriphani/backupdir") for element in list_of_files: if file in element: # tidied this up too date = 1 ### time = 2 #### yield (date, time) 2. Create a generator by calling the function: list_of_backup_files = listAllbackups("fstab") 3. Use the generator in an iterative context: for file in list_of_backup_files: # do something regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From uymqlp502 at sneakemail.com Sun Sep 2 04:00:37 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Sun, 02 Sep 2007 01:00:37 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <7xfy1xob5j.fsf@ruckus.brouhaha.com> References: <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <1188585630.539835.242460@i38g2000prf.googlegroups.com> <1188592039.612652.223700@r23g2000prd.googlegroups.com> <1i3ryxd.g2pzgq159lt5sN%aleax@mac.com> <1188711881.370954.175830@o80g2000hse.googlegroups.com> <7xfy1xob5j.fsf@ruckus.brouhaha.com> Message-ID: <1188720037.117228.243240@r34g2000hsd.googlegroups.com> On Sep 1, 11:04 pm, Paul Rubin wrote: > I still don't understand why you don't like the decorator approach, > which can easily implement the above. Well, maybe decorators are the answer. If a function needs only one decorator for all the conditions and invariants (pre and post- conditions), and if it can just point to functions defined elsewhere (rather than defining everything inline), then perhaps they make sense. I guess I need to read up more on decorators to see if this is possible. In fact, the ideal would be to have just a single decorator type, say "contract" or "self_test", that takes an argument that points to the relevant functions to use for the function that the decorator applies to. Then the actual self-test functions could be pushed off somewhere else, and the "footprint" on the primary code would be minimal From quentel.pierre at wanadoo.fr Fri Sep 21 11:03:02 2007 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Fri, 21 Sep 2007 15:03:02 -0000 Subject: Processing drag & drop on the desktop In-Reply-To: References: <1189961614.510561.194610@w3g2000hsg.googlegroups.com> <1uSdnaNGwMvgBXPbnZ2dnUVZ_tjinZ2d@comcast.com> <1190181749.502414.195730@r29g2000hsg.googlegroups.com> Message-ID: <1190386982.714606.70820@n39g2000hsh.googlegroups.com> On 21 sep, 08:58, "Gabriel Genellina" wrote: > The shortcut must point to a *program*, not a *document*. > Change the "shortcut destination" to point to: > c:\path\to\python c:\path\to\your\script.py > > -- > Gabriel Genellina Thanks for the explanation Gabriel, it works fine now Pierre From prudek at bvx.cz Tue Sep 11 11:57:27 2007 From: prudek at bvx.cz (Milos Prudek) Date: Tue, 11 Sep 2007 17:57:27 +0200 Subject: Why zlib not included in Python tarball? In-Reply-To: <46E5B84D.5020803@v.loewis.de> References: <46E5B84D.5020803@v.loewis.de> Message-ID: <200709111757.27597.prudek@bvx.cz> > Depends on the operating system and the Python version. On Unix, you > need to install zlib first; if you install a precompiled zlib package, > make sure you install the header files as well. You were right. Thank you. -- Milos Prudek From kw at codebykevin.com Mon Sep 17 16:11:03 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 17 Sep 2007 16:11:03 -0400 Subject: Class for custom Tkinter widget--difficulty Message-ID: <5786d$46eedf63$4275d90a$16155@FUSE.NET> I'm trying to create a custom Tkinter widget class, and I'm having some difficulty getting it set up properly. The class is called MacToolbar, saved in its own module MacToolbar.py, and imported with this statement: import MacToolbar Here is the relevant portion of the class: ###relevant class code class MacToolbar: def __init__(self, master): self.tk.call("package", "require", "macsearchfield") self.tk.call('package', 'require', 'tile') def create(self): self.baseframe = Tile.Frame(self, master) self.baseframe.pack(side='top', fill='both', expand='no') def toolbar(self): self.create() self.newframe = Tile.Frame(self.baseframe) self.newframe.pack(fill='both', expand='yes') self.buttonframe = Tile.Frame(self.newframe) self.buttonframe.pack(side='top', fill='both', expand = 'yes') I'm a bit confused on how to call a class that is imported via a module. Both approaches I try produce errors: The first approach: self.topframe = MacToolbar.toolbar(self.mainframe) yields this error: AttributeError: 'module' object has no attribute 'toolbar' The second approach: self.topframe = MacToolbar.MacToolbar.toolbar(self.mainframe) yields this error: TypeError: unbound method toolbar() must be called with MacToolbar instance as first argument (got Frame instance instead) I was expecting to be able to use the standard Class.Method notation in calling MacToolbar class methods, but it appears that this does not work at all: that's what I see in the first error above. Instead I have to use Module.Class.Method notation? I've never seen this before. Can someone point out what I am doing wrong, either in the construction of the class, the way it's imported, or in how I'm calling methods? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bdesth.quelquechose at free.quelquepart.fr Mon Sep 3 23:31:36 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 04 Sep 2007 05:31:36 +0200 Subject: Printing lists in columns In-Reply-To: <1188979665.052672.211110@r34g2000hsd.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> <1188913394.763871.218660@d55g2000hsg.googlegroups.com> <46dd69b1$0$24998$426a74cc@news.free.fr> <1188917550.261894.84010@k79g2000hse.googlegroups.com> <46ddbb26$0$18672$426a74cc@news.free.fr> <1188979665.052672.211110@r34g2000hsd.googlegroups.com> Message-ID: <46de8982$0$10567$426a74cc@news.free.fr> cjt22 at bath.ac.uk a ?crit : > Thanks guys, I really appreciate it. I have never used google groups > before Actually, comp.lang.python is a usenet newsgroup, not a google group. Google only gives you a web fronted (and archives...) for that group. I personnaly access it with my MUA. > and am so impressed with how helpful you all are. It is also lovely > that > none of you mock my little knowledge of Python but just want to > improve it. Well... Why should we mock ? We've all been beginners, and we're still all beginners in a domain or another. But welcome to c.l.py and thanks for appreciating this group anyway !-) > I have another question in relation to the izip_longest function (I > persume > this should be within the same topic). > Using this funciton, is there a way to manipulate it so that the > columns can be formated > tabular i.e. perhaps using something such as str(list).rjust(15) > because currently the columns > overlap depending on the strings lengths within each column/list of > lists. i.e. my output is > currently like: > > bo, daf, da > pres, ppar, xppc > magnjklep, *, dsa > *, *, nbi > > But I want it justified, i.e: > > bo , daf, da > pres , ppar, xppc > magnjklep, *, dsa > * , *, nbi > > I am struggling to understand how the izip_longest function works What's bothering you ?-) Sorry, just joking. This code uses some 'advanced' stuffs like closures, HOFs and generators/iterators, so it's obviously not that simple to grok - FWIW, I myself had to read it at least thrice to understand it. > and thus don't really know how it could be manipulated to do the > above. FWIW, you don't have - and IMHO should not try - to do this within izip_longest, which is a generic function. > It would be much apprecited if somoene could also explain how > izip_function > works as I don't like adding code into my programs which I struggle to > understand. > Or perhaps I have to pad out the lists when storing the Strings? I'd personnaly do the formatting just before printing. From phil at riverbankcomputing.co.uk Tue Sep 25 09:35:32 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Tue, 25 Sep 2007 14:35:32 +0100 Subject: PyQt disconnect signal / slot In-Reply-To: References: Message-ID: <200709251435.32863.phil@riverbankcomputing.co.uk> On Tuesday 25 September 2007, Alexander Eisenhuth wrote: > Hello PyQt experts, > > do i have to disconnect all signal/slots, after the emitting object is > deleted, or does it the QObject destructor? It's done for you - same as Qt. Phil From tgrav at mac.com Sat Sep 1 20:45:37 2007 From: tgrav at mac.com (Tommy Grav) Date: Sat, 1 Sep 2007 20:45:37 -0400 Subject: A big problem with _name_ == '_main_' In-Reply-To: References: Message-ID: On Sep 1, 2007, at 8:35 PM, onurays wrote: > I have begun to teach me Python today. The problem is : > > NameError: name 'name' is not defined. > > I am using winXP and i used that: > > if _name_ == '_main_' : > MyClass() > gtk.main() > > Onuray. I believe that should be a double underscore if __name__ == '__main__': MyClass() gtk.main() Cheers Tommy From bj_666 at gmx.net Mon Sep 10 04:34:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2007 08:34:36 GMT Subject: Python syntax wart References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> <5ki2sdF3nr68U1@mid.individual.net> <5kk8p0F3vfqqU1@mid.uni-berlin.de> <5kkcmvF3vfqqU3@mid.uni-berlin.de> Message-ID: <5kkdsrF3vfqqU5@mid.uni-berlin.de> On Mon, 10 Sep 2007 20:19:08 +1200, Lawrence D'Oliveiro wrote: > In message <5kkcmvF3vfqqU3 at mid.uni-berlin.de>, Marc 'BlackJack' Rintsch > wrote: > >> I see a tree structure here ... > > Good, you're improving. Thanks. >> ... but still no table. > > Who said anything about a table? Me. If that statement is 2D I expected to see a table structure. And I don't mean that the source code itself is arranged in lines and columns but that the so called *2D statement* can be seen as table. >> And this is also easily written that way in Python if you don't insist on >> the line break after the ``if`` or can live with backslashes. > > Which is precisely the point. Then is the lack of curly braces also a syntax wart. Maybe you should switch to a different language or write a preprocessor. Ciao, Marc 'BlackJack' Rintsch From paul.nospam at rudin.co.uk Mon Sep 10 04:26:54 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 10 Sep 2007 09:26:54 +0100 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> <13e99756io95p66@corp.supernews.com> <13e9taoa44icgb4@corp.supernews.com> <5kkd0oF3vfqqU4@mid.uni-berlin.de> Message-ID: <87veajq629.fsf@rudin.co.uk> Marc 'BlackJack' Rintsch writes: > On Mon, 10 Sep 2007 17:42:16 +1000, bambam wrote: > >> "Lawrence D'Oliveiro" wrote in >> message news:fc2c86$i1l$4 at lust.ihug.co.nz... >>> In message <13e99756io95p66 at corp.supernews.com>, bambam wrote: >>> >>>> Thank you, >>> >>> Don't top-post. >> >> I have a number of news readers here, but all of them work >> better with top-posting, and in none of them is top posting >> a problem. > > This is not about *you* having any problems but all the people who must > read your top postings. Most of them, at least in this news group, expect > that a text read from top to bottom follows time from earliest to latest. > And as most here don't top post, a conversation with a top poster starts > to get mixed and even harder to follow. >From A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing in e-mail? :) From carsten at uniqsys.com Fri Sep 7 23:01:37 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 07 Sep 2007 23:01:37 -0400 Subject: Python Problem In-Reply-To: References: Message-ID: <1189220497.3262.24.camel@localhost.localdomain> On Fri, 2007-09-07 at 21:58 -0400, Wiseman wrote: > Hi, > > The line: > > import enchant > > works perfectly OK when I call a Python progrma (sp.py) from IDLE > (WInXP). When I try to run it ftom the command line (python sp.py) the > response is: > > Traceback (most recent call last): > File "sp.py", line 3, in > import enchant > ImportError: No module named enchant Enchant is a third-party package that must have been installed separately. The most likely cause for the problem you're seeing is that you have two Python versions on your computer, one with Enchant installed, one without, and you're running the GUI of the one that does have Enchant and the command line of the one that doesn't. It's possible that the cause is something else, but to eliminate the most obvious solution, run "import sys; print sys.version" in each Python and check if they differ. > Searching my computer (the whole of drive c:\) I could not find ANY > file called enchant.*. It is not necessary to have a file called enchant-dot-anything anywhere on your disk to successfully import enchant as a module. The module could also be built-in, stored inside a zip-file, or it could be a package. In enchant's case, it's a package, i.e. somewhere on your disk you'll find a folder called "enchant" with a file "__init__.py" inside it. To find out quickly where "enchant" is, simply issue "print enchant" after importing enchant in IDLE. It'll tell you from where the module was loaded. HTH, -- Carsten Haese http://informixdb.sourceforge.net From deets at nospam.web.de Wed Sep 26 05:16:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Sep 2007 11:16:11 +0200 Subject: setuptools without unexpected downloads References: <87ejgmklep.fsf@benfinney.id.au> <878x6ukkvq.fsf@benfinney.id.au> <5luhb0Faal8aU1@mid.uni-berlin.de> <874phhlupi.fsf@benfinney.id.au> Message-ID: <5lumarFae888U1@mid.uni-berlin.de> Ben Finney wrote: > "Diez B. Roggisch" writes: > >> Ben Finney schrieb: >> > To clarify: I want to retain the "assert the specified >> > dependencies are satisfied" behaviour, without the "... and, if >> > not, download and install them the Setuptools Way" behaviour. >> > >> > Instead, I just want the default "dependencies not satisfied" >> > behaviour for my 'setup.py' program to be: complain the >> > dependencies aren't met, and refuse to install. >> >> The problem here is that your favorite OS vendor/distributor not >> necessarily offers the required meta-information - so setuptools >> can't check the dependencies. > > Let's assume it does. How would I modify my 'setup.py' script so that > its default behaviour, when dependencies are not met, is not "download > and install dependencies via setuptools" but instead "exit with error > message"? easy_install has the --no-deps commandline argument. I'm not sure if that is triggerable from inside setup.py - but in the end, you wanted user choice, didn't you? Generally speaking, I think the real problem here is the clash between "cultures" of dependency-handling. But it's certainly beyond setuptools scope to cope with every imaginable package management system out there, and provide means to trigger an installation of say e.g. debian packages that are needed. So - if you really want to go the debian/ubuntu/suse/whatever-way, provide packages in their respective format, with the dependencies met. If you are not willing to do that, the self-contained solution at least offers an option for hassle-free first time installation, especially when there is a mixture of meetable and non-meetable dependencies with the OS system. For example - what if there is no debian package that provides module XY in the required version? Do you rather install it into the global site-packages, or do you rather keep it private to the program requiring it? I'd say the latter is better in mostly all circumstances, as it will not disrupt the workings of other programs/modules. Diez From netguru7575 at gmail.com Sun Sep 30 01:41:48 2007 From: netguru7575 at gmail.com (netguru7575 at gmail.com) Date: Sat, 29 Sep 2007 22:41:48 -0700 Subject: All Quick Test Professional (QTP) FAQs Message-ID: <1191130908.594033.290730@w3g2000hsg.googlegroups.com> All Quick Test Professional (QTP) FAQs QuickTest Professional (QTP) Questions and Answers Part # 1 http://softwareqatestings.com/content/view/188/38/ QuickTest Professional (QTP) Questions and Answers Part # 2 http://softwareqatestings.com/content/view/189/38/ QuickTest Professional (QTP) Questions and Answers Part # 3 http://softwareqatestings.com/content/view/190/38/ QuickTest Professional (QTP) Questions and Answers Part # 4 http://softwareqatestings.com/content/view/191/38/ QuickTest Professional (QTP) Questions and Answers Part # 5 http://softwareqatestings.com/content/view/192/38/ From fakeaddress at nowhere.org Sat Sep 22 11:34:53 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Sep 2007 15:34:53 GMT Subject: Zope review In-Reply-To: References: <1190331847.514475.284200@22g2000hsm.googlegroups.com> <1190403772.862325.113960@y42g2000hsy.googlegroups.com> <1190432460.360614.293400@n39g2000hsh.googlegroups.com> Message-ID: Sean Tierney wrote: >>From Twisted's website "Twisted is a networking engine written in > Python, supporting numerous protocols. It contains a web server, > numerous chat clients, chat servers, mail servers, and more. > > Given that Zope is also a written in python, supports numerous > protocols, contains a webserver, has several chat packages available, > a comparison/contrast would be quite useful. You just got a useful comparison from Istvan Albert: > Istvan Albert wrote: >> Twisted is a networking engine, Zope is a web application framework, >> Plone is a content management system, there is nothing to compare, >> these are different applications altogether, it is not like you'd >> replace one with the other >> >> For applications that can be compared see Zope vs Django vs Pylons vs >> web.py vs CherryPy. Google these and contrast away. -- --Bryan From carsten at uniqsys.com Sat Sep 22 11:53:57 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 22 Sep 2007 11:53:57 -0400 Subject: frange() question In-Reply-To: <87lkaz40sj.fsf@pobox.com> References: <87tzppjhe4.fsf@pobox.com> <87lkaz40sj.fsf@pobox.com> Message-ID: <1190476437.3108.35.camel@localhost.localdomain> On Sat, 2007-09-22 at 07:27 +0000, John J. Lee wrote: > Carsten Haese writes: > > > On Thu, 2007-09-20 at 18:55 +0000, John J. Lee wrote: > >> Functions are never generators, senso stricto. There are "generator > >> functions", which *return* (or yield) generators when you call them. > > > > Actually, a generator function is a function that returns a generator. > > Read what I wrote again. What makes you begin your sentence with > "Actually", rather than "Putting it another way"? I was attempting to correct your interjection "(or yield)." A generator function doesn't yield a generator; it returns a generator that yields sequence values. The second half of my post illustrates a difference of opinion about what constitutes a generator function. You state that frange() is not a generator function because it doesn't use yield, but it behaves like one. My point is that it *is* a generator function because the generator expression is merely syntactic sugar for an equivalent for/yield loop. Of course, the distinction of whether frange() *is* a generator function or merely *behaves* as one is immaterial in practice, and we can both be right in the absence of a formal definition of what a generator function is. PEP 255 says "A function that contains a yield statement is called a generator function," but that was written before generator expressions were introduced. HTH, -- Carsten Haese http://informixdb.sourceforge.net From tenax.raccoon at gmail.com Tue Sep 4 02:14:21 2007 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 03 Sep 2007 23:14:21 -0700 Subject: list index() In-Reply-To: <5jn9qgFdmbcU3@mid.uni-berlin.de> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <5jn9qgFdmbcU3@mid.uni-berlin.de> Message-ID: <1188886461.236237.168230@y42g2000hsy.googlegroups.com> On Aug 30, 1:27 am, Marc 'BlackJack' Rintsch wrote: > On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote: > > zzbba... at aol.com writes: > > >> What's with the index() function of lists throwing an exception on not > >> found? > > > It's letting you know that the item isn't in the list. There's no > > sensible return value from an "index" function in that condition. > > What about -1? C programmers do this all the time. :-) > > Ciao, > Marc 'BlackJack' Rintsch As other people pointed out, C doesn't have exceptions, so a C programmer must make an in/out parameter to indicate an error, or have a special return value. In Python, you're most often searching the list for an object which is in the list, so the lack of the object is an exceptional condition. You can certain check with the "in" operator beforehand to avoid the exception. You may also subclass a list and override the index method, or write a standalone function to catch the exception and change its value. The reason why the exception is more Pythonic is that the return value is always a guaranteed good index into the list. Any errors (including calling .index() on a non-list instance that doesn't have a .index method) are exceptional, and should probably follow a very different code path. Returning -1 is not a good return value to indicate an error. After all, -1 is a valid index in most Python lists. (Negative numbers index from the tail of the list.) --Jason From carsten at uniqsys.com Mon Sep 24 07:49:39 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Sep 2007 07:49:39 -0400 Subject: Almost There - os.kill() In-Reply-To: <003201c7fe9f$a88ff3d0$f9afdb70$@rawlins@thinkbluemedia.co.uk> References: <002601c7fe9d$52ffb9c0$f8ff2d40$@rawlins@thinkbluemedia.co.uk> <003201c7fe9f$a88ff3d0$f9afdb70$@rawlins@thinkbluemedia.co.uk> Message-ID: <1190634579.3385.33.camel@dot.uniqsys.com> On Mon, 2007-09-24 at 12:40 +0100, Robert Rawlins - Think Blue wrote: > Woops, > > > > Spoke too soon, just wrapped them in int() and it works a charm :-D I'm glad that you figured it out for yourself. I'd like to suggest that you adjust your "give up and ask the list for help" threshold upwards. Being stumped is frustrating, but on the other hand, figuring stuff out for yourself is very rewarding, and you retain the acquired knowledge more readily than if someone just gave you the answer. By the way, I hope you only wrapped the pid argument in int(), since 15 is already an int. -- Carsten Haese http://informixdb.sourceforge.net From steve at REMOVE-THIS-cybersource.com.au Fri Sep 14 20:14:47 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 15 Sep 2007 00:14:47 -0000 Subject: How to avoid overflow errors Message-ID: <13em8vnr527rq20@corp.supernews.com> I thought that overflow errors would be a thing of the past now that Python automatically converts ints to longs as needed. Unfortunately, that is not the case. >>> class MyInt(int): ... pass ... >>> MyInt(sys.maxint) 2147483647 >>> MyInt(sys.maxint+1) Traceback (most recent call last): File "", line 1, in OverflowError: long int too large to convert to int How do I subclass int and/or long so that my class also auto-converts only when needed? -- Steven. From arobert at townisp.com Mon Sep 10 19:53:28 2007 From: arobert at townisp.com (Andrew Robert) Date: Mon, 10 Sep 2007 19:53:28 -0400 Subject: question on python syntax In-Reply-To: <1189467581.200075.236120@g4g2000hsf.googlegroups.com> References: <1189467581.200075.236120@g4g2000hsf.googlegroups.com> Message-ID: <46E5D8F8.1060501@townisp.com> a.m. wrote: > If I type this in shell > > $ ./yourfile.py 12:34 PM & > > What does '$', '.', '/' and '& means in this succession? Note: 12:34 > PM is a argument to the yourfile.py. > This not python syntax but Unix shell. $ = shell prompt ./ = look for the program in my current working directory yourfile.py = the program name 12:34 = argument 1 PM = argument 2 & = run in background From modiinfo at gmail.com Mon Sep 10 09:11:47 2007 From: modiinfo at gmail.com (Harshad Modi) Date: Mon, 10 Sep 2007 13:11:47 -0000 Subject: encoding latin1 to utf-8 In-Reply-To: References: <1189427146.723304.270600@22g2000hsm.googlegroups.com> Message-ID: <1189429907.971736.307210@57g2000hsv.googlegroups.com> thx for Reply , but I need some basic knowledge . how to encoding ? which algorithm use for that . bz my data has some special char , i have not confidence this function got proper result. i want to make my own function / script for encoding. From me at rpatterson.net Sun Sep 30 17:14:53 2007 From: me at rpatterson.net (Ross Patterson) Date: Sun, 30 Sep 2007 14:14:53 -0700 Subject: ANN: Generating svn:externals by inspecting a repository - z3c.repoexternals Message-ID: <87r6kfkg8i.fsf@superfluity.lefae.org> z3c.repoexternals recursively retrieves subversion directory listings from the url or path and matches directories against a previous set of svn:externals if provided then against regular expressions and generates qualifying svn:externals lines. The defaults generate a set of svn:externals for all the trunks in a repository and keeps them up to date with the repository as new trunks are added when the previous externals are provided thereafter. http://cheeseshop.python.org/pypi/z3c.repoexternals Ross From michele.simionato at gmail.com Mon Sep 3 03:15:59 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 03 Sep 2007 07:15:59 -0000 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> Message-ID: <1188803759.498517.198900@g4g2000hsf.googlegroups.com> On Sep 3, 2:21 am, llothar wrote: > I'm afraid that the GIL is killing the usefullness of python for some > types of applications now where 4,8 oder 64 threads on a chip are here > or comming soon. > > What is the status about that for the future of python? This is FAQ. You will find thousands of discussion on the net about that. My personal opinion (and I am not the only one in the Python community) is that if you want to scale the way to go is to use processes, not threads, so removing the GIL would be a waste of effort anyway. Look at the 'processing' module in PyPI. Michele Simionato From aahz at pythoncraft.com Sat Sep 1 11:16:40 2007 From: aahz at pythoncraft.com (Aahz) Date: 1 Sep 2007 08:16:40 -0700 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> Message-ID: In article , Roy Smith wrote: > >Anybody remember Scribe? Not directly.... http://groups.google.com/group/comp.os.cpm.amethyst/msg/d12201a697384a6a -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From evan at yelp.com Mon Sep 17 21:30:21 2007 From: evan at yelp.com (Evan Klitzke) Date: Mon, 17 Sep 2007 18:30:21 -0700 Subject: can Python be useful as functional? In-Reply-To: <1190073045.618869.261290@k79g2000hse.googlegroups.com> References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Message-ID: On 9/17/07, Lorenzo Stella wrote: > Hi all, > I haven't experienced functional programming very much, but now I'm > trying to learn Haskell and I've learned that: 1) in functional > programming LISTS are fundmental; 2) any "cycle" in FP become > recursion. > I also know that Python got some useful tool such as map, filter, > reduce... so I told: "let's try some FP-style programming with > Python!". I took a little example of Haskell: > > listprimes :: Integer -> [Integer] > listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)] > where > sieve [] = [] > sieve (p:xs) = p : sieve (filter (\x -> mod x p > 0) xs) > > and I tried to "translate" it in Python: > > def sieve(s): > if s == []: > return [] > else: > return [s[0]] + sieve(filter((lambda x: x % s[0] > 0), > s[1:])) > > def listprimes(n): > return sieve(range(2,n)) > > These should be almost the same: listprimes actually lists prime > integers up to n-1. The result is: Haskell implementation works well, > maybe it's not the better way to do it, but it does what I wanted. > Python implementation gives me > > RuntimeError: maximum recursion depth exceeded in cmp > > My question is: how can we call a language "functional" if it's major > implementation has a limited stack? Or is my code wrong? Python does not optimize tail recursion. You can increase the maximum recursion limit with sys.setrecursionlimit, but the code will still be slow. I am a fan of functional programming languages (including Haskell!), but I wouldn't try to write functional code in Python -- the language isn't optimized for this type of code, and the syntax it provides isn't very elegant, compared to other functional languages. If you want to write functional code, use a real functional language! -- Evan Klitzke From ricaraoz at gmail.com Sun Sep 30 14:54:04 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 30 Sep 2007 15:54:04 -0300 Subject: Can you please give me some advice? In-Reply-To: <1191173228.756531.225860@o80g2000hse.googlegroups.com> References: <13fuv0gh7342r27@corp.supernews.com> <1191173228.756531.225860@o80g2000hse.googlegroups.com> Message-ID: <46FFF0CC.4070106@bigfoot.com> cmpython at gmail.com wrote: >> Hello World in Ruby (and a few other languages):http://www.oreillynet.com/ruby/blog/2005/12/hello_world.html > >> Hello World in Python:http://python.about.com/od/gettingstarted/ss/helloworld.htm > > I know nothing of Ruby, but just the fact that in Ruby the Hello World > program is > > puts 'Hello, World!' > > whereas the Python Hello World program is > > print 'Hello, World!' > > suggests to me that Python is more intuitive because the word "print" > has a meaning in English that makes sense given what you want to do, > but "puts" just doesn't. And, as someone who has been learning Python > from almost no knowledge of programming, I've found it is not too bad > in trying to keep as reasonably close to a natural language like > English > as possible. > > I also think the mandatory indenting of Python is helpful in forcing > new programmers to be neat and see code blocks quickly. Plus I doubt > the Ruby community has such a large group of helpful people and > libraries > and such (but I could be wrong about that, just assuming it based on > the > fact that Python has been around longer). > > On the other hand, perhaps because Ruby is newer it has been able to > freshly start with advantages learned from the difficulties of other > languages. Byung-Hee Hwang ought to go the Ruby group and see what > they are saying. > > As far as English goes, Byung-Hee, you have to admit English grammar > is easy (though spelling is not so easy). That anyone can speak and > write Chinese is impressive to me, as the language looks completely > impossible! Good luck! > > Errhhh..... guys...... I think .kr means Korea.... so he would speak Korean, not Chinese From wizzardx at gmail.com Wed Sep 12 06:34:52 2007 From: wizzardx at gmail.com (David) Date: Wed, 12 Sep 2007 12:34:52 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> Message-ID: <18c1e6480709120334g6f9d7615jaf9826ee9d6951a8@mail.gmail.com> > Please help if I am missing something -- this looks like a great > language but I am going to mad trying to read numerical code full of > 'self.'s breaking up the equations. You could try this in your functions: s = self Then you can use code like this: s.a_dot = s.k(s.a-s.u) Another option, if you use the vars a lot in a given function, is to copy them to local vars. This can also slightly speed up your code (fewer member lookups). From steve at REMOVE-THIS-cybersource.com.au Wed Sep 12 23:09:27 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Sep 2007 03:09:27 -0000 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> Message-ID: <13ehaf7rsbdba60@corp.supernews.com> On Wed, 12 Sep 2007 19:40:04 -0700, TheFlyingDutchman wrote: >> >>> Foo.bar(foo, "spam") >> >>> foo.bar("spam") > > That looks like a case of "There's more than one way to do it". ;) The > first form is definitely consistent with the method declaration, so > there's a lot to be said for using that style when teaching people to > make classes -> send self, receive self. I think it is a horrible thing to teach beginners. Would you teach them to write 1.__add__(1) instead of 1+1? I think that beginners should be taught to write instance.method(arguments) and then only introduced to class.method(instance, arguments) when they progress to needing to know what happens under the hood. >> The latter two statements are equivalent. The 'instance.method(args)' >> syntax is just sugar for 'Class.method(instance, args)'. > > I think I saw where Guido Van Rossum had referred to something as > "syntactic sugar" in some python.org page. I am not familiar with sugar > as related to syntax. Is it being used as a synonym for "easier way of > doing it"? "Syntactic sugar" is not really well defined, it's a fuzzy concept, but in a nutshell it is special syntax made to "sweeten" the language by giving an easier way to write common tasks. It's hard to find examples of syntactic sugar that everybody agrees are syntactic sugar, but I consider the following to be good (in the sense of useful, obvious and well-thought-out) examples: alist[-1] for alist[len(alist)-1] list comprehensions and generator expressions Perhaps less attractive, but still very(?) useful, examples of syntactic sugar are decorators and the "X if C else Y" ternary operator. -- Steven From gagsl-py2 at yahoo.com.ar Sun Sep 16 22:27:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Sep 2007 23:27:25 -0300 Subject: Try this References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> Message-ID: En Sun, 16 Sep 2007 21:58:09 -0300, mensanator at aol.com escribi?: >> I'm eagerly awaiting publication of your professional specification >> for correctly detecting the encoding of an arbitrary stream of >> bytes > > The very presence of an algorithm to detect encoding is a bug. > Files with they .txt extension should always be treated as ANSI > even if they contain binary data. Why ANSI? Because it's convenient to *you*? What about the rest of the world that don't speak English or even worse, don't use the Latin alpabet? What do you mean by "binary data"? Notepad is not interpreting the file as "binary", it's text, but interpreted using the wrong encoding. If you want to understand what happens here: The Unicode block for 'CJK Unified Han' goes from U+4E00 to U+9FFF and is the largest block in the basic plane, with more than 20000 code points. The previous block contains the famous 64 hexagrams, and the previous block is 'CJK Unified Han Extension A' ranging from U+3400 to U+4DBF. Note that ASCII letters go from 0x41-0x5A and 0x61-7A, and the range 0x4100-0x7AFF is totally contained inside the above Unicode blocks. Reading a small phrase containing only ASCII letters as it were in UTF16 would collapse each two letters into a single character, each character being part of 'CJK Unified Han'. (Space and punctuation are allowed in odd positions only, else the character would not belong to the Han blocks). As every character goes into the same code block the heuristics concludes that the text is some Estern language encoded in UTF16. This is the "Well you are speed" phrase interpreted as UTF16: u'\u6557\u6c6c\u7920\u756f\u6120\u6572\u7320\u6570\u6465' > Notepad should never be > allowed to try to decide what the encoding is if the the open > dialog has the encoding set to ANSI. I'm using notepad.exe version 5.1.2600.2180 (XP SP2 fully updated) and that's exactly what happens. I have to explicitely select Unicode in order to see those Han characters. -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Sep 14 05:41:13 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 14 Sep 2007 11:41:13 +0200 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> <5ktfb5F5ctrvU1@mid.individual.net> <46e98e01$0$30383$9b4e6d93@newsspool4.arcor-online.net> <46e9921e$0$26251$426a74cc@news.free.fr> <46e995d1$0$16120$9b4e6d93@newsspool1.arcor-online.net> <46e9b09c$0$7685$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <5kv39pF5mo3hU1@mid.individual.net> stef mientki wrote: > Indeed, so I wondered why there isn't open source alternative (at > least I didn't find one). Have a look at scilab and octave. Not sure if it's GPL though. Regards, Bj?rn -- BOFH excuse #387: Your computer's union contract is set to expire at midnight. From darien.watkins at gmail.com Wed Sep 12 10:53:34 2007 From: darien.watkins at gmail.com (darien.watkins at gmail.com) Date: Wed, 12 Sep 2007 14:53:34 -0000 Subject: Python Database Apps In-Reply-To: References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> <1189536987.259907.68650@e34g2000pro.googlegroups.com> Message-ID: <1189608814.932322.301950@22g2000hsm.googlegroups.com> On Sep 12, 8:39 am, Ed Leafe wrote: > On Sep 11, 2007, at 2:56 PM, darien.watk... at gmail.com wrote: > > > It's gonna be a desktop app. The > > database engine is going to be the critical component. I like sqlite > > so that I don't need a database server on the client side. It would > > help though if there is a way to sync between multiple clients to a > > central server database. That's the tough part. To give you a better > > idea of what i'm trying to do, I am trying to write an app where > > multiple technicians have an issue tracker that is available both > > offline and online. I was looking to use sqlite as the local side > > that would sync new and updated issues to a central server when > > online. Any technician may work on any issue. Generally they will > > not be working on the same issue at the same time. The technicians > > are geographically diverse (anywhere in the southeast US, not in an > > office.) > > As far as the server goes, you can't go wrong with PostgreSQL, as > others have mentioned. I have more experience with MySQL, but their > recent licensing changes have simply made it easier to go with > Postgres, as I don't have to worry about which clause of which > document I might be violating. > > For the local data store, SQLite is far and away the best choice, > since you don't have to use two types of data access, as you would if > you went with SQL on the server and, say, pickling on the local. > > If you create both data stores with the same structure, you can use > UUIDs as your keys, along with a timestamp flag for records that are > added or modified when disconnected so that you can re-sync later. > You will have to handle conflicts (i.e., someone changed a record > that another also changed while disconnected) on your own, > implementing your own business logic to determine who "wins", and how > the conflicted data is handled. > > I'll close with a plug for our product: Dabo. It is a desktop > application framework with support for SQLite, PostgreSQL, MySQL, > Firebird and Microsoft SQL Server databases. For disconnected data, > you would simply define a local connection (to SQLite) and a remote > connection (to your server database), and switch between the two > depending on whether you are disconnected or not. The framework will > handle the rest, allowing you to focus on the stuff that is unique to > your app, such as the conflict resolution and business logic. > > -- Ed Leafe > --http://leafe.com > --http://dabodev.com Thanks for ideas Ed. I am checking out dabo now. I do have a few questions about it. Packaging. Is it easy to package into a quick install for windows. The users are going to want to get too in depth. Second, data sources. When I'm adding a data source to the window in class designer, it always picks up the one I created (which incidentally was a sample, my form for connection manager isn't working at the moment.) My idea is to have the the local sqlite database as the only viewable data source, and the server side only for syncing. So they logon, sync up, sync down, and view. I'm worried about having to get them to install python, dabo, and the app. Darien From jcd at sdf.lonestar.org Sat Sep 15 20:23:40 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Sat, 15 Sep 2007 20:23:40 -0400 Subject: string questions In-Reply-To: <5l3a09F5v20uU2@mid.uni-berlin.de> References: <5l3a09F5v20uU2@mid.uni-berlin.de> Message-ID: <46EC778C.60809@sdf.lonestar.org> Marc 'BlackJack' Rintsch wrote: > But please don't use the functions in `string` that are also available as > methods on strings. Those functions are deprecated. > > Meaning (for newbie clarification): instead of string.upper(s2), just do s2.upper(). For more detail, see the docs. From bronger at physik.rwth-aachen.de Wed Sep 5 16:15:01 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 05 Sep 2007 22:15:01 +0200 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? References: <46DEFD2E.5050205@sbcglobal.net> Message-ID: <87tzq898e2.fsf@wilson.homeunix.com> Hall?chen! Ferenczi Viktor writes: > [...] > > Class decorators allows clean implementation of properties. > Detailed description: http://www.python.org/dev/peps/pep-3129/ > Lets use a hypothetic library providing properties, for example: > > from property_support import hasProperties, Property > > @hasProperties > class Sphere(object): > def setRadius(self, value): > ... some setter implementation ... > radius=Property(default=1.0, set=setRadius, type=(int, float)) > color=Property(default='black', allowNone=True) > > This is a cleaner syntax if you need automatic default > setter/getter implementations with type checking, default values, > etc. Well, I think @hasProperties is very ugly. Such things always look like a dirty trick. The programmer wonders why the language cannot detect by itself that there are properties in this class. But anyway ... would these properties finally be virtual? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From cjw at sympatico.ca Sun Sep 23 19:30:56 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 23 Sep 2007 19:30:56 -0400 Subject: __contains__() and overload of in : Bug or Feature ??? In-Reply-To: <1190383050.514560.232660@50g2000hsm.googlegroups.com> References: <1190383050.514560.232660@50g2000hsm.googlegroups.com> Message-ID: sebastien.lannez at gmail.com wrote: > Thanks for your quick response. > >>> I need to overload the operator in and let him >>> return an object ... It seems it is not a >>> behavior Python expect : >>> >>>>>> class A: >>> ... def __contains__(self,a): >>> ... return 'yop' >>> ... >>>>>> a=A() >>>>>> print 'toto' in a >>> True >>>>>> print a.__contains__('toto') >>> yop > >> Not sure what you're trying to achieve, > > Using Python as an algebraic parser for > symbolic mathematical equation and I need > that the 'in' operator returns an object based > on its two arguments. > >> but the semantics of the "in" operator >> make it return a boolean value. > > That is why I need to overload it. > >> The string "yop" evaluates to the boolean >> value True, as it is not empty. > > Does it means that when overloading an operator, python just > wrap the call to the method and keep control of the returned > values ??? Is there a way to bypass this wrapping ??? > Can you not achieve what you wish to do with a conditional expression? "yop" if a in b else "nop" Colin W. From pavlovevidence at gmail.com Mon Sep 10 18:30:03 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 10 Sep 2007 15:30:03 -0700 Subject: Python syntax wart In-Reply-To: <1189426067.777376.106470@r34g2000hsd.googlegroups.com> References: <1189405211.875217.176620@57g2000hsv.googlegroups.com> <1189426067.777376.106470@r34g2000hsd.googlegroups.com> Message-ID: <1189463403.282658.266280@g4g2000hsf.googlegroups.com> On Sep 10, 8:07 am, TheFlyingDutchman wrote: > On Sep 9, 11:20 pm, TheFlyingDutchman wrote: > > > It may be that a language that doesn't have a statement terminator > > (which can be end-of-line) needs a statement continuation symbol. > > (Excluding languages like Lisp that have parentheses everywhere). > > Actually I guess Python does have a statement terminator - end-of- > line. > If you use end-of-line as your statement terminator it is difficult > and maybe impossible > to avoid a line-continuation character in those situations where you > don't want > an end-of-line to terminate your statement. Well, a good chunk of line continuations can be done implicitly with parentheses (one of the few places where implicit is better than explicit). Problem is, there are a few places where you might to break line that parentheses aren't legal. Back in the day, import statements were like this, but the designers of Python artifically added the ability to use parentheses there. Nowadays, they're rarely needed. One of their main remaining uses is in opening multiline strings, like so: mls = """\ This is line 1. This is line 2. I like all my lines lined up. """ The OP seems to be complaining that you can't arbitrarily break lines in the middle of a statement, so that he can write ridiculously formatted code. It's not impossible to do what he asks; for example, the following hypothetical code is not ambiguous. for x in range(10) : print x It isn't legal to end the statement anywhere before the colon, so it would be possible to add a rule to Python's parser that says, "there shall be implicit line continuations everywhere between the opening keyword and the colon". To be honest, I've always thought this would be a nice feature to have, but now that I've seen what kind of abominations are possible with it, I'm not so sure. Carl Banks P.S. The "two dimensional structure" can currently be done like this, not that I believe such a travesty should ever be used in real code. for( x )in( range(10) ): print x From michele.simionato at gmail.com Wed Sep 19 06:52:14 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 19 Sep 2007 10:52:14 -0000 Subject: super() doesn't get superclass In-Reply-To: <46f0fba0$0$29605$426a34cc@news.free.fr> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> Message-ID: <1190199134.791808.267110@22g2000hsm.googlegroups.com> On Sep 19, 12:36 pm, Bruno Desthuilliers wrote: > The next class in the MRO *is* a superclass of the *instance*. Else it > wouldn't be in the MRO !-) Bruno, there is no such a thing as a superclass in a multiple inheritance world, and it is a very bad idea to continue to use that terminology. I was convinced of that by Bjorn Pettersen in a thread on comp.lang.python in May 2003 and you may Google for it. You may find there convincing arguments against the superclass concept, some of which I report in http://www.phyast.pitt.edu/~micheles/python/super.html > Well, I understand that you disagree with both the documention and the > name of super. As far as I'm concerned, the mere fact that this > discussion happens is probably a sign that there's something to be fixed > here - at least wrt documentation, possibly wrt/ naming. But the > *feature* by itself is certainly something we do want to keep, whatever > some may argue. Well, I am personally *against* multiple inheritance (i.e. IMO it gives more troubles than advantages) > > The goal is to call the correct "next" method according to MRO. Indeed, > it could have been name "call_next_method". Right. Michele Simionato From gh at gregor-horvath.com Tue Sep 11 10:22:25 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Tue, 11 Sep 2007 16:22:25 +0200 Subject: newbie: stani's python editor if-else In-Reply-To: <1189517164.302630.307850@w3g2000hsg.googlegroups.com> References: <1189484688.520933.25000@22g2000hsm.googlegroups.com> <1189517164.302630.307850@w3g2000hsg.googlegroups.com> Message-ID: <22fd7$46e6a4a2$547078de$31885@news.chello.at> kyosohma at gmail.com schrieb: > I agree with Steve. I have yet to see an IDE for Python (or anything > else) that unindents statements. Even IDLE, the Official IDE for > Python, doesn't do that. emacs in python-mode Just hit TAB and it unindents "else" in the given example. Hit TAB again and it cylces in the possible indentations. Gregor From mal at egenix.com Fri Sep 28 13:37:29 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 28 Sep 2007 19:37:29 +0200 Subject: FW: OCBC connection In-Reply-To: <8FDC0F9BE1F91D44BE964AA54AAA67B629B61E8F@wilmexm3.ad.analog.com> References: <8FDC0F9BE1F91D44BE964AA54AAA67B629B61E8F@wilmexm3.ad.analog.com> Message-ID: <46FD3BD9.6080405@egenix.com> On 2007-09-28 19:22, Sugrue, Sean wrote: > Is this the right email list to be on for asking rather elementary > python questions? > If not do you have a suggestion It's the right place, indeed :-) Here's an example using mxODBC: # mxODBC is available from http://www.egenix.com/products/python/mxODBC/: # On Windows: from mx.ODBC import Windows as Database # On Mac OS X: from mx.ODBC import iODBC as Database # On Linux/BSD/etc.: from mx.ODBC import unixODBC as Database # or from mx.ODBC import iODBC as Database # Open a connection to the database connection = Database.DriverConnect('DSN=;' 'UID=;' 'PWD=;' 'KEYWORD=') # replace the values accordingly, add new keyword-value pairs as # necessary for your data source; data sources are configured # in the ODBC manager # Create a cursor; this is used to execute commands cursor = connection.cursor() # Create a table cursor.execute('CREATE TABLE mxodbcexample1 ' ' (id integer, name varchar(10), data varchar(254))') # this command does not create a result set, so there's nothing # to fetch from the database; however in order to make the # change permanent, we need to commit the change connection.commit() # Prepare some data rows to add to the table, ie. a list of tuples rows = [] for i in range(42): name = 'name-%i' % i data = 'value-%i' % i rows.append((i, name, data)) # Add the data in one go; the values from the tuples get assigned # to the ?-mark parameter markers in the SQL statement based on # their position and the SQL statement is executed once for # each tuple in the list of rows cursor.executemany('INSERT INTO mxodbcexample1 VALUES (?,?,?)', rows) # If you apply changes to the database, be sure to commit or # rollback your changes; a call to .commit() or .rollback() # will implicitly start a new transaction connection.commit() # Now fetch some data rows from_id = 40 to_id = 42 cursor.execute('SELECT * FROM mxodbcexample1' ' WHERE (id >= ?) and (id < ?)', (from_id, to_id)) # Fetch the results for i, row in enumerate(cursor.fetchall()): print 'Row %i: %r' % (i, row) # Remove the table again cursor.execute('DROP TABLE mxodbcexample1') connection.commit() # Close the connection connection.close() Regards, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 28 2007) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 > Sean > > -----Original Message----- > From: python-list-bounces+sean.sugrue=analog.com at python.org > [mailto:python-list-bounces+sean.sugrue=analog.com at python.org] On Behalf > Of Sugrue, Sean > Sent: Friday, September 28, 2007 10:58 AM > To: python-list at python.org > Subject: OCBC connection > > I'm trying to make an odbc connection to postgresql which is on a server > using python. > Does anyone have a code snippet to make a basic connection with a select > query? > > Sean > -- > http://mail.python.org/mailman/listinfo/python-list From Shawn at Milochik.com Tue Sep 25 15:07:59 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 25 Sep 2007 15:07:59 -0400 Subject: [Tutor] Take if offline In-Reply-To: <82b4f5810709251202y4924204bw2f79f97a1f44c09@mail.gmail.com> References: <7941B2693F32294AAF16C26B679A258D0D805E@csomb01.corp.atmel.com> <46F959CA.9080806@tds.net> <82b4f5810709251202y4924204bw2f79f97a1f44c09@mail.gmail.com> Message-ID: <2dc0c81b0709251207g15b6b5e6g64309b155193186@mail.gmail.com> Since everyone else is replying to the list, I'll (top) post this: No, not really. He had to give everyone the rule once. Otherwise, he'd have to do it a hundred times a day, and monitor every single post to find out who he had to inform. He'd end up doing not much else with his life, and would flee to a monastery and give up coding forever. You wouldn't want that to happen, would you? On 9/25/07, Michael Langford wrote: > I agree with Kent... > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > Entertaining: > http://www.ThisIsYourCruiseDirectorSpeaking.com > > > On 9/25/07, Kent Johnson wrote: > > Hansen, Mike wrote: > > > Anytime someone posts in HTML, or posts without a subject, or > > > accidentally > > > hijacks a thread, or top-posts, or writes in caps, a couple of posters > > > pop up > > > and complain. Rather than posting to the entire list, I think it'd be > > > best if > > > you send your complaint directly to the "offending" user. I'd prefer to > > > read > > > about Python not read lessons in net/mail-list etiquette. > > > > Hmmm. So instead, whenever someone complains about netiquette on-list we > > should post on-list complaining about it? I'm not sure that improves the > > situation any, especially if it sparks a discussion. Perhaps you should > > email your suggestion privately to the offending parties. :-) > > > > I definitely think this list is about how to be part of the Python > > community, as well as how to program in Python. Knowing how to > > participate in a mailing list is part of that. Maybe you could just skip > > those posts, there are not that many of them. > > > > Kent > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Please read: http://milocast.com/2007/07/31/this-i-believe/ From steve at holdenweb.com Mon Sep 17 14:38:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Sep 2007 14:38:18 -0400 Subject: how to join array of integers? In-Reply-To: <87hcltnv2z.fsf@rudin.co.uk> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <13eos6ihf2mjg4a@corp.supernews.com> <87lkb6o4bx.fsf@rudin.co.uk> <13erbtbos7ld123@corp.supernews.com> <87hcltnv2z.fsf@rudin.co.uk> Message-ID: Paul Rudin wrote: > Steven D'Aprano writes: > >> On Sun, 16 Sep 2007 19:25:22 +0100, Paul Rudin wrote: >> >>>> The generator expression takes about twice as long to run, and in my >>>> opinion it is no more readable. So what's the advantage? >>> If you do it with a decent size list they take more or less the same >>> time. >> Did you try it, > > Yes. > >> or are you guessing? > > Well - I guessed first, otherwise it wouldn't have been worth trying :) > >> What do you call a decent size? > > I used 10,000. > >> >>> You'd presumably expect the generator to use less memory; which >>> might be an advantage if you have large lists. >> Unfortunately, Python doesn't make it as easy to measure memory use as it >> does to time snippets of code, so that's just a hypothetical. > > Well - as it turns out the list gets made anyway by the join method, > so in this case there's probably little difference. However there > (obviously) are siturations where a generator is going to save you a > significant memory over the similar list comprehension. > >> >>> Isn't it odd that the generator isn't faster, since the comprehension >>> presumably builds a list first and then iterates over it, whereas the >>> generator doesn't need to make a list? >> Who says it doesn't need to make a list? string.join() needs a sequence. >> > > The generator doesn't make a list. The implementation of str.join does > apparently needs a sequence and so makes a list from the generator > passed to it, which is presumably why you get essentially the same > performance once you factor out setup noise for small lists. > > Although it's not clear to me why the join method needs a sequence > rather than just an iterator. I suspect it's to do with making memory allocation easier, though I didn't read the whole gory detail in stringobject.c. Without a pre-existing set of joinable items you have to build the string up using some sort of allocate-and-reallocate strategy, whereas if you have the joinables already in a sequence you can pre-compute how much memory the result will need. Ah, right, it's in the comment: * Do a pre-pass to figure out the total amount of space we'll * need (sz), see whether any argument is absurd, and defer to * the Unicode join if appropriate. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From Shawn at Milochik.com Fri Sep 14 09:59:36 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Fri, 14 Sep 2007 09:59:36 -0400 Subject: [Tutor] list iteration question for writing to a file on disk In-Reply-To: References: <46E563DA.4090106@umn.edu> <46E95D8E.7070801@tds.net> <46E99CEE.3030304@tds.net> Message-ID: <2dc0c81b0709140659j702c997fkbefc412a09cd53c4@mail.gmail.com> When you use "print," it automatically adds a newline (\n). You can avoid this by following the print line with a comma: print j, Or rstrip() the line before printing. Either way. From bvukov at yahoo.com Sat Sep 29 03:34:38 2007 From: bvukov at yahoo.com (bvukov at yahoo.com) Date: Sat, 29 Sep 2007 00:34:38 -0700 Subject: Reentrancy of Python interpreter In-Reply-To: References: Message-ID: <1191051278.075475.128020@o80g2000hse.googlegroups.com> On Sep 28, 11:31 pm, Brad Johnson wrote: > I have embedded a single threaded instance of the Python interpreter in my > application. > > I have a place where I execute a Python command that calls into C++ code which > then in turn calls back into Python using the same interpreter. I get a fatal > error which is "PyThreadStage_Get: no current thread." > > I guess I understand why I can't have two invocations of the same interpreter > thread in one call stack, but how would I go about solving this? Looks like ( from PyThreadStage_Get error ) that you lost the GIL. You probably entered some C++ code and encapsulated you're work in the Py_BEGIN_ALLOW_THREADS Py_END_ALLOW_THREADS but you're is calling back the Python function, and you forgot to acquire back the GIL. From zzbbaadd at aol.com Thu Sep 20 00:42:43 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 19 Sep 2007 21:42:43 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> Message-ID: <1190263363.496695.83300@57g2000hsv.googlegroups.com> On Sep 19, 5:08 pm, "Terry Reedy" wrote: > "Terry Reedy" wrote in message This is a little confusing because google groups does not show your original post (not uncommon for them to lose a post in a thread - but somehow still reflect the fact that it exists in the total-posts number that they display) that you are replying to. > > This assumes that comparing versions of 1.5 is still relevant. As far as I > know, his patch has not been maintained to apply against current Python. > This tells me that no one to date really wants to dump the GIL at the cost > of half Python's speed. Of course not. The point of dumping the GIL is to > use multiprocessors to get more speed! So with two cores and extra > overhead, Stein-patched 1.5 would not even break even. > > Quad (and more) cores are a different matter. Hence, I think, the > resurgence of interest. I am confused about the benefits/disadvantages of the "GIL removal". Is it correct that the GIL is preventing CPython from having threads? Is it correct that the only issue with the GIL is the prevention of being able to do multi-threading? If you only planned on writing single-threaded applications would GIL- removal have no benefit? Can threading have a performance benefit on a single-core machine versus running multiple processes? > So now this question for you: "CPython 2.5 runs too slow in 2007: true or > false?" I guess I gotta go with Steven D'Aprano - both true and false depending on your situation. > If you answer false, then there is no need for GIL removal. OK, I see that. > If you answer true, then cutting its speed for 90+% of people is bad. OK, seems reasonable, assuming that multi-threading cannot be implemented without a performance hit on single-threaded applications. Is that a computer science maxim - giving an interpreted language multi-threading will always negatively impact the performance of single-threaded applications? > > | Most people are not currently bothered by the GIL and would not want its > | speed halved. > > And another question: why should such people spend time they do not have to > make Python worse for themselves? > Saying they don't have time to make a change, any change, is always valid in my book. I cannot argue against that. Ditto for them saying they don't want to make a change with no explanation. But it seems if they make statements about why a change is not good, then it is fair to make a counter-argument. I do agree with the theme of Steven D'Aprano's comments in that it should be a cordial counter-argument and not a demand. From daniel.j.larsson at gmail.com Tue Sep 4 18:29:11 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Wed, 5 Sep 2007 00:29:11 +0200 Subject: doctest and decorators In-Reply-To: <200709050009.46380.python@cx.hu> References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> <200709042316.08263.python@cx.hu> <2bfa72fa0709041452o72d9a98fp939852d061a2cda3@mail.gmail.com> <200709050009.46380.python@cx.hu> Message-ID: <2bfa72fa0709041529g9d5ac22hce3a55d5357b1a1c@mail.gmail.com> On 9/5/07, Ferenczi Viktor wrote: > > > > @functools.wraps(f) > > > Pass the function to be wrapped by the decorator to the wraps > function. > > Ooops, right. That doesn't change the fact that decorated functions get > > hidden from doctest though. I have no issue when the decorator is defined in the same module as the decorated function, my problem is running doctests on functions using an imported decorator. Having to implement the decorator in every source module isn't very practical. Try splitting your module in two, as I did, and run with -v, and you'll see the problem. Run my test script (one file) with the -v (verbose) option. Without the -v > option it does not show output. This fact is documented in the Python > manual > at the doctest module. > > --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- > import functools > > def simplelog(f): > @functools.wraps(f) > def new_f(*args, **kwds): > print "Wrapper calling func" > return f(*args, **kwds) > return new_f > > @simplelog > def test(): > """ > >>> test() > Wrapper calling func > 'works!' > """ > return 'works!' > > def fn(): > """ > >>> fn() > 'ok' > """ > return 'ok' > > if __name__ == '__main__': > import doctest > doctest.testmod() > --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- > > Regard, Viktor > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregpinero at gmail.com Sat Sep 22 23:28:49 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Sun, 23 Sep 2007 03:28:49 -0000 Subject: subprocess -popen - reading stdout from child - hangs Message-ID: <1190518129.356844.242710@19g2000hsx.googlegroups.com> Let's say I have this Python file called loop.py: import sys print 'hi' sys.stdout.flush() while 1: pass And I want to call it from another Python process and read the value 'hi'. How would I do it? So far I have tried this: >>> proc = subprocess.Popen('python /home/chiefinnovator/loop.py',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE) >>> proc.stdout.read() But it just hangs at read() proc.communicate() also just hangs. What am I doing wrong? Please advise. Thanks, Greg From marco_347 at yahoo.it Fri Sep 7 11:18:05 2007 From: marco_347 at yahoo.it (marco_347 at yahoo.it) Date: Fri, 07 Sep 2007 08:18:05 -0700 Subject: debugging program that uses ctypes Message-ID: <1189178285.647177.216320@g4g2000hsf.googlegroups.com> hi all, I have a python program that calls a dll through ctypes (py2.5). In some (reproducible) conditions the program crashes with an error in ctypes module. How can I trace down the problem? I have created a debug build of python but I also use pyodbc and dateutil libraries in my program and I don't know how to make them visible to python_d.exe Am I using the right approach? thanks in advance for hints, Marco From RJNauman at uss.com Wed Sep 5 07:45:06 2007 From: RJNauman at uss.com (Ryan J Nauman) Date: Wed, 5 Sep 2007 07:45:06 -0400 Subject: Help me understand this script Message-ID: Can someone help me understand this script please? I understand everything except for the anagram function. Could you break it down into more than 1 line of code for me or explain it? (I understand WHAT it does but HOW?) Thanks. Script >> ### # SCRABBLE.PY # # purpose: # find usable "bingos" based on your rack # # usage: # python scrabble.py eilsnsy # # output: # Straight anagrams: # linseys # lysines # Possible other words: # + B # sensibly #+ K # skylines #+ V # sylvines ### # Scrabble is a registered trademark of J. W. Spear & Son PLC and # Hasbro Inc. Any and all uses of the word "Scrabble" in this code # refers to this trademark. # # This code is not affiliated with any company. ### import sys WORDS = [ i.rstrip ().lower() for i in file ('c:\python25\TWL06.txt') ] # you can download the current TWL and/or SOWPODS dictionaries from # http://67.19.18.90/twl.zip and http://67.19.18.90/sowpods.zip . # Update the file name above as appropriate if you want to use a "proper" # Scrabble dictionary. def alphabetise(word): x = [i for i in word] x.sort() return "".join(x) def anagram(word): wordLength = len(word) sortedWord = alphabetise(word.lower()) return [i for i in WORDS if len(i) == wordLength and alphabetise(i) == sortedWord] for word in sys.argv[1:]: print "Straight anagrams: " for i in anagram(word): print " " + i print "Possible other words: " for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": a = anagram(i + word) if a: print "+", i for h in a: print " ", h << End script -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Sep 21 11:09:21 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 21 Sep 2007 17:09:21 +0200 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> <46F3BEA3.8080100@web.de> Message-ID: <5li551F87hfcU1@mid.individual.net> Stefan Behnel wrote: > Bjoern Schliessmann wrote: >> Lawrence D'Oliveiro wrote: >>> >> ?id=20070910&mode=classic>. >> >> Esc-Meta-Alt-Ctrl-Shift? :) > > Yep, that's five of them. I'd also have mentioned Caps Lock, Alt Gr, Compose and Sysrq if there was no deeper meaning in what I wrote. Regards, Bj?rn -- BOFH excuse #25: Decreasing electron flux From jstroud at mbi.ucla.edu Fri Sep 14 16:23:51 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 14 Sep 2007 13:23:51 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189800045.642278.313860@o80g2000hse.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> <1189753968.917636.310120@19g2000hsx.googlegroups.com> <1189800045.642278.313860@o80g2000hse.googlegroups.com> Message-ID: Mark Summerfield wrote: > I guess I'll have to rename my module (although unfortunately, my book > has just gone into production and I have a (simpler) example of what I > considered to be an ordered dict, so I will be adding to the > terminology confusion). That notwithstanding, given that it is a > sorteddict, how is the API? I must think the API good because I have been implementing, in parallel with this discussion, my own "OrderedDict" with a very similar API (this is part of a larger project where I recently found the need to have a well-implemented ordered dict). The only real omission I see is to allow instantiating a "sorted dict" with an optional cmp function--to allow the generalization of such features as case-independence, etc. James From carsten at uniqsys.com Wed Sep 5 22:56:23 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 05 Sep 2007 22:56:23 -0400 Subject: Give List to Format String - How To In-Reply-To: <1189046828.313284.235210@o80g2000hse.googlegroups.com> References: <1189046828.313284.235210@o80g2000hse.googlegroups.com> Message-ID: <1189047383.3231.3.camel@localhost.localdomain> On Thu, 2007-09-06 at 02:47 +0000, gregpinero at gmail.com wrote: > I might just be being dumb tonight, but why doesn't this work: > > >>> '%s aaa %s aa %s' % ['test' for i in range(3)] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: not enough arguments for format string To format multiple objects, the right operand must be a tuple. A list is not a tuple, so '%' only sees one argument. You want something like this: >>> '%s aaa %s aa %s' % tuple('test' for i in range(3)) 'test aaa test aa test' HTH, -- Carsten Haese http://informixdb.sourceforge.net From semanticist at gmail.com Thu Sep 13 17:00:59 2007 From: semanticist at gmail.com (Miles) Date: Thu, 13 Sep 2007 17:00:59 -0400 Subject: sys.argv index out of range error In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE33A@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE33A@efmailx> Message-ID: On 9/13/07, Brian McCann wrote: > bootstrap.sh > #!/bin/sh > cd /home/workspaces > export LANG="en_US.UTF-8" > > source init $1 > test.py $2 > ################################# > > what's wrong with the line "source init $1 ? Assuming your /bin/sh is actually the Bourne-again shell, this excerpt from the Bash manual explains what's happening ("source" is a synonym for "."): """ . filename [arguments] Read and execute commands from the filename argument in the current shell context. [...] If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. """ So "source [script] [args]" clobbers the parameters of the *current* shell context. So any of these should work: * use "source init.sh" to use the same shell context; * use "./init.sh $1" to use a new context; or * save the needed parameters in other variables before clobbering them. -Miles From zzbbaadd at aol.com Thu Sep 13 12:43:13 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 13 Sep 2007 09:43:13 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: <5ksoaoF5am8cU1@mid.individual.net> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <5ksoaoF5am8cU1@mid.individual.net> Message-ID: <1189701793.466307.93210@g4g2000hsf.googlegroups.com> > > > Here is a link to a tutorial where Sun is talking about the this > > reference: > >http://java.sun.com/docs/books/tutorial/java/javaOO/thiskey.html > > That's a tutorial for getting you started, no reference > documentation or in-depth course. > Here's a FAQ item where they refer to it as I think Python should have done it - a special predefined variable: http://www.faqs.org/docs/javap/c5/s5.html "Java provides a special, predefined variable named "this" that you can use for such purposes. The variable, this, is used in the source code of an instance method to refer to the object that contains the method. This intent of the name, this, is to refer to "this object," the one right here that this very method is in. If x is an instance variable in the same object, then this.x can be used as a full name for that variable. If otherMethod() is an instance method in the same object, then this.otherMethod() could be used to call that method. Whenever the computer executes an instance method, it automatically sets the variable, this, to refer to the object that contains the method." "this" is hard to query on but I would be interested in seeing some site talking about Java where "this" is mentioned as being "passed in". From gandalf at shopzeus.com Wed Sep 12 16:09:30 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 12 Sep 2007 22:09:30 +0200 Subject: I want py2exe not to create library.zip Message-ID: <46E8477A.6000507@shopzeus.com> Hi, I want py2exe not to create library.zip. My reason is that the installed program will be a self updating program, and it must be able to download changes (newer python source files) from the server. So the files should not be in library.zip. I tried the --bundle option but apparently it can only be used to make the distribution __more__ bundled. Thanks, Laszlo From Scott.Daniels at Acm.Org Wed Sep 26 22:41:48 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 26 Sep 2007 19:41:48 -0700 Subject: Tkinter / Tk 8.5 In-Reply-To: References: Message-ID: <13fm60kbhr28fa8@corp.supernews.com> Michal Bozon wrote: > Today has been released a first beta of Tk 8.5, including a Ttk > (tile) style engine, which makes possible the native look > of widgets on MS platform, without having to install any extension. > > Is there a chance it will be included in 2.5.x, 2.6 or 3.0 ? This is just a guess, but: The beta: no way for anything. 2.5.x: also very unlikely 2.6: unlikely unless release is _soon_ (first alpha of 2.6 is out) 3.0: much more likely, 3.0 won't be out for some time. -Scott David Daniels Scott.Daniels at Acm.Org From see at signature.invalid Mon Sep 17 19:41:44 2007 From: see at signature.invalid (Nigel Rowe) Date: Mon, 17 Sep 2007 23:41:44 GMT Subject: Python "with" References: <13et3kv409e355d@corp.supernews.com> Message-ID: On Tue, 18 Sep 2007 00:26, Grant Edwards wrote in comp.lang.python <<13et3kv409e355d at corp.supernews.com>>: > On 2007-09-17, Laurent Pointal wrote: > >> Note3: Its funny to see how Python users tries to change the language, >> does this occure with C, C++, Java, C# ? > > Yes. I remember somebody I worked with once who write a C > program using a whole pile of macros to make it look like BASIC: > > #define IF if ( > #define THEN ) { > #define ELSE } else { > #define ENDIF } > > and so on... > and latin speaking perl programmers use Lingua::Romana::Perligata Totaly insane. Oh, wait, they're perl programmers. -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) fisheggs (stop) name From fakeaddress at nowhere.org Sun Sep 23 15:28:08 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 23 Sep 2007 19:28:08 GMT Subject: database persistence with mysql, sqlite In-Reply-To: <1190502677.970811.181100@22g2000hsm.googlegroups.com> References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> Message-ID: coldpizza wrote: > I want to run a database query and then display the first 10 records > on a web page. Then I want to be able to click the 'Next' link on the > page to show the next 10 records, and so on. > My question is how to implement paging, i.e. the 'Next/Prev' NN > records without reestablishing a database connection every time I > click Next/Prev? Is it at all possible with cgi/mod_python? Caching database connections works in mod_python; not so much with cgi. > For example, in a NON-web environment, with sqlite3 and most other > modules, I can establish a database connection once, get a cursor > object on which I run a single 'SELECT * FROM TABLE' statement and > then use cursor.fetchmany(NN) as many times as there are still results > left from the initial query. > > How do I do the same for the web? Short answer: you don't. It would mean saving cursors with partial query results, and arranging for incoming requests to go to the right process. Web-apps avoid that kind of thing. Many web toolkits offer session objects, but do not support saving active objects such as cursors. That said, I've never tried what you proposing with the tools you name. Depending on how your database handles transactions, an open cursor can lock-out writers, and even other readers. How long do you keep it around if the user doesn't return? What should happen if the user re-loads a page from a few sets-of-10 back? > I am not using any high-level > framework. I am looking for a solution at the level of cgi or > mod_python (Python Server Pages under Apache). To call > cursor.fetchmany(NN) over and over I need to pass a handle to the > database connection but how do I keep a reference to the cursor object > across pages? I use mysql and sqlite3 as databases, and I am looking > for an approach that would work with both database types (one at a > time). So far I have successfully used the following modules for > database access: sqlite3, mysqld, and pyodbc. > > So far, with mysql I use 'SELECT * FROM TABLE LIMIT L1, L2' where L1 > and L2 define the range for the 'Next' and 'Previous' commands. I > have to run the query every time a click a 'Next/Prev' link. You might want to run that query by a MySQL expert. The basic method is nice in that it needs no server-side state between requests. (It's a little squirrely in that it can show a set of records that was never the contents of the table.) > But I am > not sure that this is the best and most efficient way. I suppose using > CURSOR.FETCHMANY(NN) would probably be faster and nicer but how do I > pass an object reference across pages? Is it possible without any > higher-level libraries? Do you know that you have a performance problem? If so do you know that it is due to too many cursor.execute() calls? Keeping partially-executed queries is way down on the list of optimizations to try. > What would be the proper way to do it on a non-enterprise scale? With mod_python, you can cache connections, which may help. If you use "ORDER BY" with "LIMIT", the right index can make a big difference. Have you considered implementing your 'Next/Prev' commands on the browser side with Javascript? The server could then get all the records in one query, and the user would see point-in-time correct results. Another possibility is to the get all the query results and save them in a session object, then deal them out a few at a time. But as a rule of thumb, the less state on the server the better. > Would SqlAlchemy or SqlObject make things easier with regard to > database persistence? Quite likely, but probably not in the way you propose. The web frameworks that use those toolkits try to do things in robust and portable ways. -- --Bryan From bdesth.quelquechose at free.quelquepart.fr Sat Sep 22 08:33:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 22 Sep 2007 14:33:19 +0200 Subject: Can a base class know if a method has been overridden? In-Reply-To: <1190661185.359967.78610@w3g2000hsg.googlegroups.com> References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> <46f7d897$0$25150$426a74cc@news.free.fr> <1190648887.051630.168520@r29g2000hsg.googlegroups.com> <46f7e8df$0$21052$426a74cc@news.free.fr> <1190661185.359967.78610@w3g2000hsg.googlegroups.com> Message-ID: <46f81e39$0$27759$426a34cc@news.free.fr> Ratko a ?crit : > bruno a ?crit >>Another solution is to compare the functions wrapped by the methods: >> >>class EvtHandler: >> def __init__(self): >> onKey = getattr(self, 'onKey') >> if onKey.im_func is EvtHandler.onKey.im_func: s/is/is not/, of course >> register_for_key_events() >> >> def onKey(self): >> pass >> >>class MyHandler(EvtHandler): >> def onKey(self): >> # do something here.... >> >>HTH > > > The second solution works beautifully! Hem... Almost !-) > Thank you very much. > I was aware that not implementing the onKey method in the first place > is the simplest solution but it's much cleaner to offer the methods in > advance so that the user can see what is possible. Yeps - a placeholder 'abstract' method with only a docstring. It's a common pattern in frameworks, but usually it's just an ordinary template method pattern defaulting to a no-op. FWIW, if you have several such methods to handle, you can use a more generic approach: _handlers = { 'onKey':registerForKeyEvents, 'onClick':registerForMouseEvents, } # etc class EventHandler(object): for _name in _handlers: exec "%s=lambda self, *args, **kw: pass" % _name def __new__(cls, *args, **kw): obj = object.__new__(cls, *args, **kw) for name, register_func in _handlers.items(): meth = getattr(obj, name) dummy = getattr(EventHandler, name) if meth.im_func is not dummy.im_func: register_func(meth) return obj HTH From gagsl-py2 at yahoo.com.ar Thu Sep 6 22:39:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Sep 2007 23:39:59 -0300 Subject: interesting puzzle......try this you will be rewarded... References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> <46e04138$0$16377$88260bb3@free.teranews.com> <1189130241.529344.52950@57g2000hsv.googlegroups.com> Message-ID: En Thu, 06 Sep 2007 22:57:21 -0300, Basilisk96 escribi?: > I got to 14 :) > > It's rather silly. > > I remember seeing a more elaborate puzzle that involved coding, > cryptography knowledge, etc. to get through it. But what was the link, > I forget now... Me too, and I can't find that link either. #15 is a bit difficult for people outside US, and spelling on #21 is questionable, but I liked this woody thing :) -- Gabriel Genellina From naufraghi at develer.com Mon Sep 17 11:22:41 2007 From: naufraghi at develer.com (Matteo Bertini) Date: Mon, 17 Sep 2007 17:22:41 +0200 Subject: ANNOUNCE: PyQt3Support r1 - Python bindings for Qt3Support Message-ID: <46EE9BC1.20500@develer.com> #### PyQt3Support - Python bindings for Qt3Support #### http://www.develer.com/oss/PyQt3Support #### What is this? PyQt3Support is an extension to PyQt4 that adds bindings to Qt's Qt3Support library for usage from the Python language. This is very helpful to migrate existing PyQt3 applications to PyQt4. #### Why? Porting from Qt3 to Qt4 can be tedious and bug-prone. For C++ programmers, Trolltech provides a library, called Qt3Support, that immensely helps. With Qt3Support, a C++ programmer basically only needs mechanical changes to your source code. The library is made of two different parts: * A new family of widgets (Q3*) with the same API of Qt3. * New member functions (or overloads) within standard Qt4 widgets. For Python programmers, the situation is worse: PyQt4 does not bind Qt3Support to Python. Developers of PyQt3 are forced to manually upgrade their code to PyQt4, class by class. This package fills the gap. By providing a new module PyQt4.Qt3Support, it enables PyQt3 developers to access Trolltech's migration library, and thus upgrade their code much easily and faster, with almost only mechanical changes. It's not a panacea of course: you probably still need minor manual adjustments and supervising, but it can still be of great help. #### Where? PyQt3Support has been developed and tested under both Windows (2000, XP, Vista) and Linux (Ubuntu, Fedora). #### License Qt3Support follows whatever license you have for PyQt3 and PyQt4, because its source code is machine-generated from PyQt3's and PyQt4's source code. Thus, Qt3Support can be freely used under both the GPL or the commercial license offered by Qt/PyQt producers. In case you are interested in developing Qt3Support itself, you want to know that the script that generates Qt3Support is released under the GPL license. #### Status PyQt3Support is not complete: it binds about 30% of the Qt3Support, but don't be fooled by this figure: it's the part that is probably used most in existing programs (more common widgets, constructors, ecc.). Moreover, since it is fully machine-generated, it is very easy to extend it to cover more classes and functions. See below as per how to contribute to the development. * PyQt3 ported classes: Q3VBox, Q3HBox, Q3Frame, Q3Grid, Q3Accel, Q3PopupMenu, Q3MenuData, Q3DockWindow, Q3DockArea, Q3ListView, Q3ScrollView, Q3ColorGroup, Q3Header, Q3ListBox, Q3StrList, Q3Table, Q3MemArray, Q3MainWindow, Q3ToolBar, Q3Action, Q3SimpleRichText, Q3StyleSheet, Q3Mime, Q3ComboBox, Q3GroupBox, Q3FileDialog, Q3Url, Q3WidgetStack, Q3HGroupBox, Q3VGroupBox, Q3IconView, Q3DragObject, Q3Picture, Q3ValueList, Q3CString, Q3ButtonGroup, Q3VButtonGroup * PyQt4 qt3supported classes: Gui.QBoxLayout, Core.QNamespace, Gui.QLCDNumber, Gui.QGridLayout, Gui.QApplication, Gui.QPushButton, OpenGL.QGLWidget, Core.QObject, Gui.QLabel, Gui.QPixmap, Core.QTextCodec, Gui.QToolButton, Gui.QTabWidget, Gui.QMenu, Core.QTimer, Gui.QLayout, Gui.QPalette, Gui.QMenuBar, Gui.QLineEdit, Gui.QDialog, Gui.QInputDialog, Gui.QCheckBox, Gui.QWidget, Gui.QTextEdit, Gui.QEvent, Gui.QSlider #### Download http://www.develer.com/oss/PyQt3Support -- Matteo Bertini - naufraghi at develer.com Develer S.r.l. - http://www.develer.com Software Solutions From srikrishnamohan at gmail.com Mon Sep 3 06:39:05 2007 From: srikrishnamohan at gmail.com (km) Date: Mon, 3 Sep 2007 16:09:05 +0530 Subject: metaclasses: timestamping instances In-Reply-To: <1188665051.107414.61200@50g2000hsm.googlegroups.com> References: <1188665051.107414.61200@50g2000hsm.googlegroups.com> Message-ID: Hi, But why does it show varied difference in the time between a and b instance creations when __metaclass__ hook is used and when not used in class Y ? I dont understand that point ! KM On 9/1/07, Michele Simionato wrote: > > On Sep 1, 6:07 pm, Steve Holden wrote: > > > > > Debugging with Wing IDE and examining the classes at a breakpoint shows > > this to be true (even after Y's __metaclass__ assignment is commented > out): > > > > >>> X.__metaclass__ > > > > >>> Y.__metaclass__ > > > > >>> > > For the benefit of the readers I will just point out that in order > to determine the metaclass of a class it is far better NOT to relay on > the > __metaclass__ attribute. The right thing to to is to look at the > __class__ > attribute, or to use type. Here is a (made up) example > where .__metaclass__ gives > the wrong result: > > > In [9]: class M(type): pass > ...: > > In [10]: class B: __metaclass__ = M > ....: > > In [11]: B.__metaclass__ = None # now the hook is set to None, but the > metaclass does not change > > In [12]: B.__class__ > Out[12]: > > Michele Simionato > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rbonvall at gmail.com Fri Sep 7 13:19:02 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Fri, 07 Sep 2007 17:19:02 -0000 Subject: Speed of Python In-Reply-To: References: Message-ID: <1189185542.798286.168880@50g2000hsm.googlegroups.com> On Sep 7, 12:42 pm, "wang frank" wrote: > Here is the bench1.py: > import math > def bench1(n): > for i in range(n): > for j in range(1000): > m=j+1 > z=math.log(m) > z1=math.log(m+1) > z2=math.log(m+2) > z3=math.log(m+3) > z4=math.log(m+4) > z5=math.log(m+5) > z6=math.log(m+6) > z7=math.log(m+7) > z8=math.log(m+8) > z9=math.log(m+9) > return z9 > > Is my conclusion correct that Python is slower than matlab? Show us your Matlab code in order to see if both are equivalent. Your Python code creates n lists of 1000 elements, so you're not actually measuring only the numeric computations. Cheers, -- Roberto Bonvallet From mail at timgolden.me.uk Thu Sep 13 11:52:41 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 13 Sep 2007 16:52:41 +0100 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: <46E95CC9.2000103@timgolden.me.uk> Amer Neely wrote: > Richie Hindle wrote: >>> [Amer] >>> #!/usr/bin/python >>> [...] On my home PC [...] >>> [Thu Sep 13 04:16:03 2007] [error] [client 0.0.0.0] (OS 2)The system >>> cannot find the file specified. >> That's because on your home PC Python is somewhere like >> C:\Python25\python.exe, not /usr/bin/python. >> >> Are you sure /usr/bin/python is correct for your hosting environment? >> > > It's my understanding that the Windows shell doesn't pay much attention > to the shebang line if the file type is associated with the proper > application. > > But I tried your suggestion and got the same results. The Windows shell doesn't, but Apache does. (Haven't followed this thread closely, but I seem to remember it has to do with running CGI scripts). TJG From david at asdf.asdf Tue Sep 11 21:54:51 2007 From: david at asdf.asdf (bambam) Date: Wed, 12 Sep 2007 11:54:51 +1000 Subject: function to do dynamic import? References: <13ecb84p1ghrd64@corp.supernews.com> <1189491152.601490.33880@o80g2000hse.googlegroups.com> Message-ID: <13eehnapt0r0jc2@corp.supernews.com> wrote in message news:1189491152.601490.33880 at o80g2000hse.googlegroups.com... > On Sep 10, 10:52 pm, "bambam" wrote: >> import works in the main section of the module, but does >> not work as I hoped when run inside a function. >> >> That is, the modules import correctly, but are not visible to >> the enclosing (global) scope. >> >> Questions: >> (1) Where can I read an explanation of this? >> (2) Is there a work around? >> >> BTW, sys.modules("filename") shows that the module is >> loaded, I just don't know how to use it when loaded that >> way. Also, if I import again at the global scope, the module >> name becomes available. >> >> Steve. > > > > (snipped) > > This was recently discussed: > > http://groups.google.com/group/comp.lang.python/msg/f6fcdf49710cb833 > > -- > Hope this helps, > Steven > def gim(): exec "global gamel" exec "import gamel" Unfortunately, does not have the desired effect. Steve. From jcd at sdf.lonestar.org Thu Sep 20 23:04:49 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 20 Sep 2007 23:04:49 -0400 Subject: UTF-8 characters in doctest In-Reply-To: <878x71jfwo.fsf@pobox.com> References: <1190202459.229197.297350@n39g2000hsh.googlegroups.com> <878x71jfwo.fsf@pobox.com> Message-ID: <46F334D1.20909@sdf.lonestar.org> John J. Lee wrote: > Peter Otten <__peter__ at web.de> writes: > [...] > >> def f(s): >> return (s,) >> > > Forgive me if this is a stupid question, but: What purpose does > function f serve? > > > John > Well, it has nothing to do with the unicode bit that came before it. It just takes an argument, and wraps it in a 1-tuple. Guessing by the argument of "s", that argument is expected to be a string. One use I can think of is that sometimes you'll find a function that returns a string or a list or tuple of strings. If you want to pass that result on to a for loop, and only loop once on the string (instead of looping on each letter of the string), you might want to wrap it in a tuple or a list before passing it to the loop. Cheers, Cliff From ed at leafe.com Wed Sep 12 08:39:01 2007 From: ed at leafe.com (Ed Leafe) Date: Wed, 12 Sep 2007 08:39:01 -0400 Subject: Python Database Apps In-Reply-To: <1189536987.259907.68650@e34g2000pro.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> <1189536987.259907.68650@e34g2000pro.googlegroups.com> Message-ID: On Sep 11, 2007, at 2:56 PM, darien.watkins at gmail.com wrote: > It's gonna be a desktop app. The > database engine is going to be the critical component. I like sqlite > so that I don't need a database server on the client side. It would > help though if there is a way to sync between multiple clients to a > central server database. That's the tough part. To give you a better > idea of what i'm trying to do, I am trying to write an app where > multiple technicians have an issue tracker that is available both > offline and online. I was looking to use sqlite as the local side > that would sync new and updated issues to a central server when > online. Any technician may work on any issue. Generally they will > not be working on the same issue at the same time. The technicians > are geographically diverse (anywhere in the southeast US, not in an > office.) As far as the server goes, you can't go wrong with PostgreSQL, as others have mentioned. I have more experience with MySQL, but their recent licensing changes have simply made it easier to go with Postgres, as I don't have to worry about which clause of which document I might be violating. For the local data store, SQLite is far and away the best choice, since you don't have to use two types of data access, as you would if you went with SQL on the server and, say, pickling on the local. If you create both data stores with the same structure, you can use UUIDs as your keys, along with a timestamp flag for records that are added or modified when disconnected so that you can re-sync later. You will have to handle conflicts (i.e., someone changed a record that another also changed while disconnected) on your own, implementing your own business logic to determine who "wins", and how the conflicted data is handled. I'll close with a plug for our product: Dabo. It is a desktop application framework with support for SQLite, PostgreSQL, MySQL, Firebird and Microsoft SQL Server databases. For disconnected data, you would simply define a local connection (to SQLite) and a remote connection (to your server database), and switch between the two depending on whether you are disconnected or not. The framework will handle the rest, allowing you to focus on the stuff that is unique to your app, such as the conflict resolution and business logic. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From cyberco at gmail.com Wed Sep 26 16:27:18 2007 From: cyberco at gmail.com (cyberco) Date: Wed, 26 Sep 2007 20:27:18 -0000 Subject: PyS60 In-Reply-To: <1190731662.584011.105500@o80g2000hse.googlegroups.com> References: <1190731662.584011.105500@o80g2000hse.googlegroups.com> Message-ID: <1190838438.101681.60090@d55g2000hsg.googlegroups.com> I have used PyS60 quite a lot a while ago, but what is it you exactly wanted to know? One thing I can tell you is that it's a pity that it only runs on Series 60 phones and that the security restrictions of third edition devices severely limited the options for developers. 2B From sulsa at gazeta.pl Mon Sep 3 20:49:08 2007 From: sulsa at gazeta.pl (Sulsa) Date: Tue, 4 Sep 2007 02:49:08 +0200 Subject: Python is overtaking Perl References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> Message-ID: <20070904024908.b8aca60c.sulsa@gazeta.pl> On Tue, 04 Sep 2007 00:32:23 -0000 Ben wrote: > Here are the statistics from Google Trends: > > http://benyang22a.blogspot.com/2007/09/perl-vs-python.html > This chart is showing that amount of python programers is smaller every year :( From namesagame-usenet at yahoo.com Sat Sep 29 15:53:17 2007 From: namesagame-usenet at yahoo.com (gamename) Date: Sat, 29 Sep 2007 12:53:17 -0700 Subject: C Source Code Generator For Test Cases In-Reply-To: <5m69hrFbre38U1@mid.uni-berlin.de> References: <1191001738.456766.176050@n39g2000hsh.googlegroups.com> <5m51iuFbao07U1@mid.uni-berlin.de> <1191009469.736521.39210@k79g2000hse.googlegroups.com> <5m69hrFbre38U1@mid.uni-berlin.de> Message-ID: <1191095597.287680.298400@50g2000hsm.googlegroups.com> > Instead of reading the testcase tables and generating source for test > routines you simply can do the tests right away. > Can't. :( This is for an embedded system. I need to create source (in C) on one machine and then compile on others. The only thing that I can be certain of is an ANSI compiler on any machine I use. -T From bignose+hates-spam at benfinney.id.au Thu Sep 20 23:39:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 21 Sep 2007 13:39:13 +1000 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> Message-ID: <874phou1pa.fsf@benfinney.id.au> "W. Watson" writes: > Is vim just an editor or is it capable of running and debugging a > program, as well? (Please don't top-post. Instead, reply below each point to which you're responding, removing quoted text irrelevant to your response.) Both Emacs and Vim are highly customisable text editors. They are configurable with complete programming languages specific to the program, and both have a huge community of programmers writing useful extensions. So, neither of them is "just an editor"; they are editors at their core, that can become complete programming environments by taking already-written components for them. Your operating system distribution of either Vim or Emacs will already include many of these components when you install the package, and many more are available. -- \ "The restriction of knowledge to an elite group destroys the | `\ spirit of society and leads to its intellectual | _o__) impoverishment." ?Albert Einstein | Ben Finney From namesagame-usenet at yahoo.com Thu Sep 13 12:23:55 2007 From: namesagame-usenet at yahoo.com (gamename) Date: Thu, 13 Sep 2007 09:23:55 -0700 Subject: Python+Expect+Win32 = Not Possible? In-Reply-To: References: <1189657637.539038.317280@k79g2000hse.googlegroups.com> <1189672955.321701.164050@57g2000hsv.googlegroups.com> <1189681397.349994.126130@57g2000hsv.googlegroups.com> Message-ID: <1189700635.617281.190250@k79g2000hse.googlegroups.com> On Sep 13, 4:18 am, Tim Golden wrote: > gamename wrote: > > On Sep 13, 1:42 am, half.ital... at gmail.com wrote: > >> On Sep 12, 9:27 pm, gamename wrote: > > >>> Hi, > >>> Is it still the case there is no practical Expect-like module for > >>> win32? I know that cygwin can support pexpect, but that isn't an > >>> option here --- I have to use a native win32 Python version. > >>> Are there alternatives, or is it simply not an option to replicate > >>> Expect on win32 with python? > >>> All I'm trying to do is start a couple processes, wait for each to say > >>> "done" on stdout and then quit (or timeout if something went wrong). > >>> TIA, > >>> -T > >> I had planned on using telnet to do the same thing on windows. I > >> don't think I ever proved it, but I'm pretty sure it will work. > > > Thanks, Sean. The problem is that telnet is generally disabled on > > most hosts nowadays. > > I'm not sure whether the need you describe above "start a > couple [of] processes, wait for each to say 'done' and > then quit (or timeout...)" is *all* of your requirements > or just an example. And are these processes running on > remote machines? Or just locally? > Good question. That's part of the requirements. The rest are: The processes need to be async (i.e. the script doesn't stop while waiting for the process to complete). They also need some kind of timeout mechanism so that the processes don't run forever. All processes are local. > Depending on those things, maybe there are other ways > to do what you want under Windows? > > (I've checked back through the archives and I can't find > any earlier posts describing the requirement more clearly). > > TJG From ldo at geek-central.gen.new_zealand Fri Sep 14 02:44:21 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 14 Sep 2007 18:44:21 +1200 Subject: "once" assigment in Python References: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> Message-ID: In message <1189750616.597409.85380 at w3g2000hsg.googlegroups.com>, Lorenzo Di Gregorio wrote: > During coding I find it handy to assign a variable *unless it has been > already assigned*: I've found that this is often referred to as "once" > assigment. Why not just assign to it once at the beginning and be done with it? From fakeaddress at nowhere.org Sat Sep 22 16:30:05 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Sep 2007 20:30:05 GMT Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <7xy7eysfc0.fsf@ruckus.brouhaha.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <7xy7eysfc0.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Bryan Olson writes: >> chris.monsanto at gmail.com wrote: >>> There are already anonymous functions in Python. >>> lambda x, y, z: x + y + z >>> is the same as: >>> def _(x, y, z): return x + y + z >> They are the same only in special cases: >> The special identifier "_" is used in the interactive >> interpreter to store the result of the last evaluation... > > I'm not sure what Chris was really getting at, I was big-time unsure. At first, I thought Chris's latter form to be equivalent to a pass statement. I've long used the Python convention of assigning throw-away values to '_', and I was under the mistaken impression Python defined _ as a discard target. When I looked it up, I was surprised to find that my understanding of the _ variable was wrong, and shocked that there really is an interesting context where Chris's claim has a strong case. > since among other > things lambda:... is an expression while def... is a statement. True fact, but note that one form of statement is an expression. > But Python certainly has anonymous functions without lambda: > > def compose(f,g): > def h(*a, **k): > return f(g(*a, **k)) > return h > > x = compose(math.sin, math.cos)(1.0) > computes sin(cos(1.0)) where a function equivalent to > lambda x: sin(cos(x)) > is constructed and used without being bound to a symbol. How anonymous is that function when we can see that its name is 'h'? import math f = compose(math.sin, math.cos) print f.__name__ Am I making a bogus argument? Kind of. Most authors of "anonymous" works do in fact have real names. The term really means that they entered the context at issue dissociated from their given name. Nevertheless, def is never a real anonymous function constructor. If our concern is Python's suitability for studying principles of programming, I think I'm on stronger ground. Python is great for getting things done. It is easy to learn in the sense of learning to to use if for practical tasks. Python's actual semantics are not as neat and clean as some other languages. -- --Bryan From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Sep 9 06:04:52 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 09 Sep 2007 12:04:52 +0200 Subject: Python syntax wart References: Message-ID: <5khuq4F3ij9eU1@mid.individual.net> Lawrence D'Oliveiro wrote: > Not possible: > > for \ > Link \ > in \ > GetEachRecord \ > ( > "links", > ("from_episode",), > "to_episode = %s", > [EpisodeID], > "order by when_created" > ) \ > : > out.write \ > ( > "

Back to episode %d\n" > % > ( > LinkToMe({"ep" : Link["from_episode"]}), > Link["from_episode"] > ) > ) > #end for IMHO, that's no Python syntax wart, but a coding style wart. What's wrong with this: for Link in GetEachRecord( "links", ("from_episode",), "to_episode = %s", [EpisodeID], "order by when_created" ): out.write("

Back to episode %d\n" % ( LinkToMe({"ep" : Link["from_episode"]}), Link["from_episode"] ) ) It's still quite crammed; I think I'd write it more explicit. (Personally, I've never needed the possibility to tear a "for" apart so it covers more than ten lines, or to waste lines by placing single parentheses or colons in them -- my screen really isn't unlimited in size.) Regards, Bj?rn -- BOFH excuse #247: Due to Federal Budget problems we have been forced to cut back on the number of users able to access the system at one time. (namely none allowed....) From gagsl-py2 at yahoo.com.ar Tue Sep 18 09:19:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Sep 2007 10:19:38 -0300 Subject: string replace shortcut References: <1190115872.824161.115420@w3g2000hsg.googlegroups.com> Message-ID: En Tue, 18 Sep 2007 08:44:32 -0300, escribi?: > Hello, > > I am trying to replace some string with list objects: > >>>> my_text1="function1 function2" >>>> from my_module_with_functions_1 import * >>>> from my_module_with_functions_2 import * > > # functions in module " my_module_with_functions_1 ": > my_func1 it's value "function1" > my_func2 it's value "function2" > > # functions in module " my_module_with_functions_2 ": > my_func100 it's value "bla bla 1" > my_func200 it's value "bla bla 2" > > ........now, we need find and replace functions from module " > my_module_with_functions_1 " and > replace them with functions from module " my_module_with_functions_2 > " > > with: my_text1.replace(items1,items2) > > Result must be: > >>>> print my_text1.replace(items1,items2) > bla bla 1 bla bla 2 I'm unsure what you want. You keep saying "functions" but they are apparently strings. If your problem is how to replace many strings, just do it one at a time (asuuming they're unique so the order is not important). def multi_replace(text, list1, list2): for rep1, rep2 in itertools.izip(list1, list2): text = text.replace(rep1, rep2) return text py> multi_replace("a sentence with a few words", ["sentence","words"], ["man","d ollars"]) 'a man with a few dollars' Now, your problem may be building both lists. They must be syncronized, that is, the first element on one list must correspond to the first element on the other, and so on. The import statement doesn't guarantee any ordering so I think the best way would be to define an __all__ attribute on both modules, and import that: from my_module_with_functions_1 import __all__ as list_of_names_1 from my_module_with_functions_2 import __all__ as list_of_names_2 new_text = multi_replace(my_text1, list_of_names_1, list_of_names_2) -- Gabriel Genellina From aleax at mac.com Sun Sep 30 20:40:27 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 30 Sep 2007 17:40:27 -0700 Subject: Can you please give me some advice? References: Message-ID: <1i59kx9.1rytrz2xyu2w9N%aleax@mac.com> Byung-Hee HWANG wrote: > Hi there, > > What is different between Ruby and Python? Not all that much; Python is more mature, Ruby more fashionable. I am wondering what language > is really mine for work. Somebody tell me Ruby is clean or Python is > really easy! Anyway I will really make decision today what I have to > study from now on. What I make the decision is more difficult than to > know why I have to learn English. Yeah I do not like to learn English > because it is just very painful.. www.python.or.kr/ http://wiki.python.org/moin/KoreanPythonBooks Alex From gagsl-py2 at yahoo.com.ar Tue Sep 4 15:26:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Sep 2007 16:26:53 -0300 Subject: Setting Current Dir in Python References: <000001c7eeec$d9341470$8b9c3d50$@net> Message-ID: En Tue, 04 Sep 2007 09:12:22 -0300, Sandipan Gangopadhyay escribi?: > I have recently installed Python 2.5.1 and Pythonwin (without any > errors) on > Windows Vista Ultimate. > > Now, the programs run fine within Pythonwin IDE when current directory is > set to the program's directory. > > But, when I double click them from Windows Explorer, the program is not > run. First, fix your source code (either removing the non-ascii character or adding an encoding line at the top, see ) (PEP0263 is enforced from Python 2.5 and up; you got a warning on earlier versions). os.getcwd() returns the current directory. os.chdir() changes the current directory. A shortcut on the desktop may use the desktop itself as the initial directory. If you want to run your script from within the same directory as it resides, try this: os.chdir(os.path.dirname(__file__)) -- Gabriel Genellina From mcl.office at googlemail.com Fri Sep 7 07:08:52 2007 From: mcl.office at googlemail.com (mcl) Date: Fri, 07 Sep 2007 04:08:52 -0700 Subject: MySQLdb: ValueError Something Stupid Message-ID: <1189163332.990248.134080@d55g2000hsg.googlegroups.com> I have just started with python and MySQL. I have a simple test for each of my tables. The first two work as expected, but the third 'qlooks', gives a ValueError. If I copy and paste the SQL in the traceback to phpMyAdmin, it works as expected. Can anyone give a clue as to what I am doing wrong Python 2.4 MySQL 4.1.22-standard The tablename qlooks is LOWERCASE Code ======================================================= cursor = gv.conn.cursor() queries = ["%septi%"] fields = ("qlTitle", "qlSubTitle", "qlPostCode", "qlMap", "qlDetails") tblFields = "select * from qlooks " whereTests = 'Where qlTitle like "%septi%"' sql = tblFields + whereTests #cursor.execute(sql) cursor.execute('select * from PERMS') row = cursor.fetchone() print "Row=", row, gv.nl cursor.execute('select * from LISTS') row = cursor.fetchone() print "Row=", row, gv.nl cursor.execute('select * from qlooks') row = cursor.fetchone() print "Row=", row, gv.nl cursor.close() ERROR TRACEBACK ++++++++++++++++++++++++++++++++++++++++ 79 print "Row=", row, gv.nl 80 cursor.execute('select * from qlooks') 81 row = cursor.fetchone() 82 print "Row=", row, gv.nl cursor = , cursor.execute = > /usr/lib/python2.4/site-packages/MySQLdb/cursors.py in execute(self=, query='select * from qlooks', args=None) 93 """ 94 del self.messages[:] 95 return self._execute(query, args) 96 97 def _execute(self, query, args): self = , self._execute = >, query = 'select * from qlooks', args = None /usr/lib/python2.4/site-packages/MySQLdb/cursors.py in _execute(self=, query='select * from qlooks', args=None) 112 exc, value, tb = exc_info() 113 del tb 114 self.errorhandler(self, exc, value) 115 self._executed = query 116 return r self = , self.errorhandler = >, exc = , value = /usr/lib/python2.4/site-packages/MySQLdb/connections.py in defaulterrorhandler(connection=<_mysql.connection open to 'db.sabren.com' at 936cac4>, cursor=, errorclass=, errorvalue=) 31 else: 32 connection.messages.append(error) 33 raise errorclass, errorvalue 34 35 errorclass = , errorvalue = ValueError: invalid literal for int(): 0- args = ('invalid literal for int(): 0-',) ========================================= Thanks Richard From jwrweatherley at gmail.com Sun Sep 2 07:51:42 2007 From: jwrweatherley at gmail.com (jwrweatherley at gmail.com) Date: Sun, 02 Sep 2007 04:51:42 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers Message-ID: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> I'm pretty new to python, but am very happy with it. As well as using it at work I've been using it to solve various puzzles on the Project Euler site - http://projecteuler.net. So far it has not let me down, but it has proved surprisingly slow on one puzzle. The puzzle is: p is the perimeter of a right angle triangle with integral length sides, {a,b,c}. which value of p < 1000, is the number of solutions {a,b,c} maximised? Here's my python code: #!/usr/local/bin/python solutions = [0] * 1001 p = 0 for a in xrange(1, 1000): for b in xrange(1, 1000 - a): for c in xrange(1, 1000 - a - b): p = a + b + c if p < 1000: if a ** 2 + b ** 2 == c ** 2: solutions[p] += 1 max = 0 maxIndex = 0 index = 0 for solution in solutions: if solution > max: max = solution maxIndex = index index += 1 print maxIndex It takes 2 minutes and twelve seconds on a 2.4GHz Core2Duo MacBook Pro. Surprised at how slow it was I implemented the same algorithm in C: #include #include int main() { int* solutions = calloc(1000, sizeof(int)); int p; for(int a = 1; a < 1000; ++a) { for(int b = 1; b < 1000 - a; ++b) { for(int c = 1; c < 1000 - a - b; ++c) { p = a + b + c; if(p < 1000) { if(a * a + b * b == c * c) { solutions[p] += 1; } } } } } int max = 0; int maxIndex = 0; for(int i = 0; i < 1000; ++i) { if(solutions[i] > max) { max = solutions[i]; maxIndex = i; } } printf("%d\n", maxIndex); return 0; } gcc -o 39 -std=c99 -O3 39.c The resulting executable takes 0.24 seconds to run. I'm not expecting a scripting language to run faster than native code, but I was surprised at how much slower it was in this case. Any ideas as to what is causing python so much trouble in the above code? From duncan.booth at invalid.invalid Mon Sep 10 07:23:04 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Sep 2007 11:23:04 GMT Subject: Enum class with ToString functionality References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> Message-ID: bg_ie at yahoo.com wrote: > But it would be much nicer if I had a function to covert to string as > part of the TestOutcomes class. How would I implement this? Perhaps: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 From jjl at pobox.com Sat Sep 22 03:21:31 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 22 Sep 2007 07:21:31 GMT Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87odfxjgjy.fsf@pobox.com> Message-ID: <87sl574138.fsf@pobox.com> Gary Coulbourne writes: > John J. Lee wrote: >> Eclipse must be able to do this. > > Not by default... but I am certain there are plugins that provide python > integration. (And jython integration) Well yes, obviously (?) I meant Eclipse with pydev installed. John From bignose+hates-spam at benfinney.id.au Mon Sep 10 23:02:06 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 11 Sep 2007 13:02:06 +1000 Subject: Enum class with ToString functionality References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <87bqca9hrw.fsf@benfinney.id.au> <1189472591.797327.189180@w3g2000hsg.googlegroups.com> <87sl5m7xxm.fsf@benfinney.id.au> <1189478288.237609.25140@50g2000hsm.googlegroups.com> Message-ID: <87odg99a6p.fsf@benfinney.id.au> TheFlyingDutchman writes: > On Sep 10, 7:12 pm, Ben Finney > wrote: > > TheFlyingDutchman writes: > > > Looking at the documentation it looks excellent. But I don't > > > understand the 0.4.2 version number, > > > > Note the tag that says the "Development Status" is "Beta". > > What is the difference between this version and the 1.0 version? I don't know yet, since my time machine is currently in for repairs. -- \ "If you ever reach total enlightenment while you're drinking a | `\ beer, I bet it makes beer shoot out your nose." -- Jack Handey | _o__) | Ben Finney From max at alcyone.com Sat Sep 1 23:53:33 2007 From: max at alcyone.com (Erik Max Francis) Date: Sat, 01 Sep 2007 20:53:33 -0700 Subject: How best to dynamically define methods (and functions)? In-Reply-To: References: Message-ID: Erik Max Francis wrote: > Something like:: > > method = ['fun', ...] > for method in methods: > setattr(MyClass, method, lambda *x: Node(method, *x)) Err, that first line was supposed to be methods = ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis I like young girls. Their stories are shorter. -- Thomas McGuane From jd at nospam.com Fri Sep 21 14:53:34 2007 From: jd at nospam.com (Jd) Date: Fri, 21 Sep 2007 11:53:34 -0700 Subject: xml-rpc timeout In-Reply-To: References: <2_WdnTQ86eZNY27bnZ2dnUVZ_jCdnZ2d@comcast.com> Message-ID: Steve Holden wrote: > Jd wrote: >> Hi >> I have a multi-threaded application. For certain operations to the >> server, I would like to explicitly set timeout so that I get correct >> status from the call and not timed out exception. >> Does anyone know how to go about doing it ? >> > The easiest way is to use socket.setdefaulttimeout() to establish a > longer timeout period for all sockets, I guess. It's difficult to > establish different timeouts for individual sockets when they aren't > opened directly by your own code (though each socket does also have a > method to set its timeout period). > > regards > Steve Ya.. the problem here is that I donot have acces to the socket. I have written my own transport etc.. but when the socket is getting created, there is no context for the method and where I know what method I am going to call, I do not have access to socket. I would have thought this to be an easy thing to achieve. In order to make xml-rpc easy to use.. it has become difficult to control. Anyone have any other ideas ? /Jd From blackmh at gmail.com Wed Sep 12 12:34:44 2007 From: blackmh at gmail.com (Kveldulv) Date: Wed, 12 Sep 2007 09:34:44 -0700 Subject: PyGTK right-click menu Message-ID: <1189614884.175694.50420@y42g2000hsy.googlegroups.com> HI all, can someone show me how to make simple right-click menu in PyGTK. tia From alexandre.badez at gmail.com Thu Sep 27 09:17:58 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Thu, 27 Sep 2007 13:17:58 -0000 Subject: Launching command on windows Message-ID: <1190899078.141370.116190@57g2000hsv.googlegroups.com> Hy, I'm working on windows and I try to do something like: import os APP = os.path.abspath("C:\\Program Files\\Notepad++\\notepad++.exe") FILE1 = os.path.abspath("D:\\Documents and settings\\test1.py") FILE2 = os.path.abspath("D:\\Documents and settings\\test2.py") command = '"%(app)s" "%(file1)s" "%(file2)s"' % { 'app' : APP, 'file1' : FILE1, 'file2' : FILE2} # === FOR 'DEBUG' === print APP print FILE1 print FILE2 print command print repr(command) # === END FOR 'DEBUG' === os.system(command) This code give in output: C:\Program Files\Notepad++\notepad++.exe D:\Documents and settings\test1.py D:\Documents and settings\test2.py "C:\Program Files\Notepad++\notepad++.exe" "D:\Documents and settings \test1.py" "D:\Documents and settings\test2.py" '"C:\\Program Files\\Notepad++\\notepad++.exe" "D:\\Documents and settings\\test1.py" "D:\\Documents and settings\\test2.py"' 'C:\Program' n'est pas reconnu en tant que commande interne ou externe, un programme ex,cutable ou un fichier de commandes. # <= My windows is a french one # This error message could be translated as: # 'c:\Program' is not an internal nor external command, an executable program nor a command file But if I copy the command in the output, an paste it in a console, it work very well. Does any of you know what I can do ? PS: I think I'm oblige to add " neer every path for spaces in path, but if you know an other way, it could be cool :) From deets at nospam.web.de Wed Sep 12 06:34:59 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Sep 2007 12:34:59 +0200 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> Message-ID: <5kptmjF50dtfU1@mid.uni-berlin.de> > > with self: > .a_dot = -.k(.a-.u) > > It's premature to make language suggestions as I am new to the > language, but I would have though that making a 'with self' explicit > in all methods would have been neat, so I could just write > .a_dot = -.k(.a-.u) > which would still avoid confusion with local function variables, since > '.a' is different from 'a'. > > Please help if I am missing something -- this looks like a great > language but I am going to mad trying to read numerical code full of > 'self.'s breaking up the equations. This is a FAQ - and the short answer is: no, you don't miss anything, and it's not going change. If you want, you can shorten the expressions like this: s = self s.a * s.b Or choose any other valid name, e.g. the underscore. Another (yet rather ugly) alternative would be to push the names into the global namespace. But that could of course create major mayhem! So take this with a huge grain of salt: globals().update(self.__dict__) a * b Diez From mydomdom at gmail.com Fri Sep 14 08:21:43 2007 From: mydomdom at gmail.com (Dominique) Date: Fri, 14 Sep 2007 12:21:43 +0000 (UTC) Subject: Install Mac OS X - Idle doesn't show up Message-ID: Hello, Sorry bothering you with such a trivial problem. I installed python on a new mac at office. It seems everything is fine: in the console, I access to python. But I just can't start Idle. It seems to open but closes immediately (it appears in the dock and closes immediately). It is also impossible to open any .py file. I am sure some of you have a good idea of what to do (path,...). Thanks in advance Dominique From jstroud at mbi.ucla.edu Sat Sep 15 05:45:10 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 15 Sep 2007 02:45:10 -0700 Subject: How to avoid overflow errors In-Reply-To: <13emslk6n80mmf6@corp.supernews.com> References: <13em8vnr527rq20@corp.supernews.com> <13emslk6n80mmf6@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Fri, 14 Sep 2007 18:19:45 -0700, James Stroud wrote: > >>> How do I subclass int and/or long so that my class also auto-converts >>> only when needed? >>> >> Use __new__. > > The disadvantage of that is that your example code requires me to > duplicate my methods in the long version and the int version. It's easy > enough to work around that (class factory function) but it just seems all > rather untidy... The __new__ method is where you implement such decisions. There is no "tidier" way for one class "auto-convert" to another class, which is what you asked for (it says so right up there ^). So, if you don't like the answer, don't ask the question. Despite its unseemly appearance because of all the underscores, it is the natural way in python (to do what you have asked and not something which you didn't ask). The way to avoid duplicating methods (which is what you are asking for, no?) while still allowing your classes to maintain their identities is by using mixins: class MyModulatingMixin(object): def modulate(self, sum): if self.modulus is None: return self.__class__(sum) else: return self.__class__(sum % self.modulus) def __add__(self, other): sum = long.__add__(long(self), long(other)) return self.modulate(sum) def __mul__(self, other): sum = long.__mul__(long(self), long(other)) return self.modulate(sum) class MyLong(long): def __new__(cls, v, m=None): obj = long.__new__(cls, v) obj.modulus = m return obj class MyInt(int): def __new__(cls, v, m=None): try: obj = int.__new__(cls, v) obj.modulus = m except OverflowError: obj = MyLong(v, m) return obj for cls in MyLong, MyInt: cls.__bases__ = (MyModulatingMixin,) + cls.__bases__ py> i = MyInt(51) py> j = MyInt(40, 7) py> k = MyLong(2, 13) py> i + j 91 py> j + k 0 py> k + j 3L py> i * k 102 py> type(i * k) py> k * i 11L py> type(k * i) James From json.barnes at gmail.com Wed Sep 26 12:38:35 2007 From: json.barnes at gmail.com (Jason M Barnes) Date: Wed, 26 Sep 2007 09:38:35 -0700 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: <5lhs4pF8bkunU1@mid.individual.net> Message-ID: <833263a00709260938y5c7bed1cmecd97dcfc111c7e9@mail.gmail.com> On 9/26/07, Neil Cerutti wrote: > On 2007-09-26, Jason M Barnes wrote: > > Off the top of my head, I can think of a few vim commands that > > have come in handy. I can search through a webpage in Firefox > > by using the same '/' search command that vim has. The > > movement keys (h,j,k,l) are the same as in any paging program > > I've ever used. Not to mention that I learned regexes by > > learning 's/regex/replacement' first :-) > > Yup. A huge advantge of learning vi is how much it helps improve > your nethack experience. ;) Ignorance was Emacs was an obstacle I > had to overcome in order to get into the Lisp world, though. Ha! I'm trying to learn Lisp now, too, and I'm having to learn Emacs to be more efficient. I feel like I'm taking my first CS class again. (Now was that C-x C-c or M-c M-x?... Nope, that didn't work... ;-) > > > That's my religion anyway ;-), but I thought this was a python > > mailing list ;-) > > Vim has Python integration if you want to control it with Python > scripts. Cool! Of course, Vim needs such a capability more than > Emacs, which has the very cool elisp scripting language. I'm not > so keen on Vim's built-in scripting language. > > -- > Neil Cerutti > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Sat Sep 29 17:19:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Sep 2007 18:19:14 -0300 Subject: Command-line does work when scheduled References: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> Message-ID: En Sat, 29 Sep 2007 17:34:34 -0300, Jim escribi?: > I want to schedule a Python program that reads the command line for > input. However, when adding an argument to the command line Python > will not pick it up when using Windows scheduled tasks. > > How do I get it to work? Do you write the command line when defining the task? Using double quotes around arguments with spaces? It works fine for me. -- Gabriel Genellina From paul.hankin at gmail.com Mon Sep 24 18:03:05 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 24 Sep 2007 22:03:05 -0000 Subject: Nested For and While Statements In-Reply-To: <1190667172.491315.209110@y42g2000hsy.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190666647.199890.174670@o80g2000hse.googlegroups.com> <1190667172.491315.209110@y42g2000hsy.googlegroups.com> Message-ID: <1190671385.064498.206920@y42g2000hsy.googlegroups.com> First the bugs... On Sep 24, 9:52 pm, kou... at hotmail.com wrote: > ... > avcsasdoc = workspace + "\avcsas.txt" > ... There's quite a few cases like this where you don't escape backslashes, so your filenames are mostly mangled. Here \a produces character code 7, which is definitely wrong. Either escape them like this: '\\avcsas.txt' or use raw strings where backslashes aren't treated specially: r'\avcsas.txt'. You might want to look at the 'os.path' module for help in constructing filenames. You have a 'break' and the end of the last for loop. This has the effect of stopping the for loop at the first iteration. Either it's a bug, or you really didn't want a for loop! There's also quite a few places where your code could be improved: > classsum = avcclass[0] + avcclass[1] + avcclass[2] + > avcclass[3] + avcclass[4] + avcclass[5] \ > + avcclass[6] + avcclass[7] + avcclass[8] + avcclass[9] + > avcclass[10] \ > + avcclass[11] + avcclass[12] + avcclass[13] Is better written classsum = ''.join(avcclass[:14]) > addzeros = {1:"0", 2:"00", 3:"000", 4:"0000"} > ... > ... addzeros[numzeros] + lanex[i-1] Good idea, but in this case python provides an easier alternative: ... '0' * numzeros + lanex[i - 1] Or use the 'rjust' method which right-justifies a string: ... lanex[i - 1].rjust(5, '0') > for i in range(1,Nscheme+1): > numzeros = 5 - int(len(lanex[i-1])) > avcclass.append(addzeros[numzeros] + lanex[i-1]) > Nlanex.append(int(lanex[i-1]) Is better as for i in range(Nscheme): ... use i rather than i - 1 (I assume Visual Basic for loops are off by one). In fact, this loop is even better if you just iterate over lanex itself. Using a loop index rather than iterating directly is a common mistake. for lane in lanex: avcclass.append(lane.rjust(5, '0')) Nlanex.append(int(lane)) Or even better, use list comprehensions to construct your two lists explicitly: avcclass = [lane.rjust(5, '0') for lane in lanex] Nlanex = [int(lane) for lane in lanex] Note, each rewrite makes the intention of the code clearer, as well as being shorter. This makes your code easier to read and understand, and less buggy. Since all you do with avcclass is sum it, combine this with the classsum optimisation above to get classsum = ''.join(lane.rjust(5, '0') for lane in lanex[:14]) Nlanex = [int(lane) for lane in lanex] > lanex = [] > if numlanes == 2: > lane1 = newlist1[2:2+Nscheme] > lanex.append(lane1) > lane2 = newlist1[2+Nscheme:2+Nscheme*2] > lanex.append(lane2) > else: > lane1 = newlist1[2:2+Nscheme] > lanex.append(lane1) > lane2 = newlist1[2+Nscheme:2+Nscheme*2] > lanex.append(lane2) > lane3 = newlist1[2+Nscheme*2:2+Nscheme*3] > lanex.append(lane3) > lane4 = newlist1[2+Nscheme*3:2+Nscheme*4] > lanex.append(lane4) List comprehensions beat copy/paste: total_schemes = 2 if numlanes == 2 else 4 lanex = [newlist1[2 + i * Nscheme:2 + (i + 1) * Nscheme] for i in range(total_schemes)] HTH, and welcome to python! -- Paul Hankin From steve at holdenweb.com Wed Sep 5 02:35:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Sep 2007 23:35:56 -0700 Subject: list index() In-Reply-To: <1188972560.323189.33880@d55g2000hsg.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <5jn9qgFdmbcU3@mid.uni-berlin.de> <1188886461.236237.168230@y42g2000hsy.googlegroups.com> <871wdd92vk.fsf@benfinney.id.au> <1188972560.323189.33880@d55g2000hsg.googlegroups.com> Message-ID: TheFlyingDutchman wrote: >> I explain it by noting that list.index and dict.get serve totally >> different purposes. The former returns the index given a value; the >> latter returns a value given a key. > > And the former raises an exception if the value is not found, while > the latter returns None if the value is not found. > >> There are many areas of poor symmetry in the language and libraries; >> it isn't particularly clever or difficult to find them if one >> looks. Doing so doesn't appear to illustrate any point I see relevant >> in this thread. > > It has been stated in this thread, that in Python, exceptions are used > differently than in other languages. Rather than just use them for > catastrophic errors that can't be dealt with, Python raises exceptions > on routine and survivable situations such as an item not found in a > list. It was mentioned that an exception is more Pythonic than > returning a "not found" value. > > Someone pointed out that find() in str was a contradiction to this > since it doesn't throw an exception but returns a "not found" value, > and the response was that it was believed that find() would be removed > from the language (if so, it does not currently show up on the > "removed list" as has_key() and a few others do - > http://docs.python.org/dev/3.0/whatsnew/3.0.html) and was only there > for "historical reasons". > > I don't believe the poster was trying to illustrate a point already > mentioned in the thread, but to give a contradiction to statements in > the thread. He was asking the question - why doesn't dict.get() throw > an exception on not found if that is the Pythonic way? > > Because it's an explicit short-cut for a frequently-required paradigm. It's effectively an extension to dict indexing - which, you will recall, *does* raise an exception when the key is not found. Does *everything* have to raise such an exception? There's no requirement for Python to be 100% consistent in its application of a principle, but on the whole it is reasonably consistent. For Pete's sake stop wasting your time and go do some programming. Nothing will ever be perfect, not even Python ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From HDoran at air.org Wed Sep 5 09:30:32 2007 From: HDoran at air.org (Doran, Harold) Date: Wed, 5 Sep 2007 09:30:32 -0400 Subject: Checking if elements are empty Message-ID: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> Dear list: Suppose I have a string as follows x = ' \t'ff' I can split this up as y = x.split('\t') Which gives [ ' ', 'ff'] len(y) 2 Is there a way to check if the first element of y is null? -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sat Sep 22 17:09:13 2007 From: http (Paul Rubin) Date: 22 Sep 2007 14:09:13 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <7xy7eysfc0.fsf@ruckus.brouhaha.com> Message-ID: <7xbqbu1k7a.fsf@ruckus.brouhaha.com> Bryan Olson writes: > How anonymous is that function when we can see that its name is 'h'? h is out of scope after compose returns, so the function is anonymous in the sense that there is no symbol bound to the function, through which you can refer to it. > import math > > f = compose(math.sin, math.cos) > print f.__name__ I prefer to think of __name__ as just some debugging info stuck inside the closure, though actually Python is introspective enough to be able to let you locate and call a function whose __name__ is "h". Of course there might be more than one: f = compose(math.sin, math.cos) g = compose(math.sqrt, math.tan) print f.__name__, g.__name__ > Nevertheless, def is never a real anonymous function constructor. Well, def constructs a function with a name, but the function can stay around after the name goes away, after which I'd say the function is nameless. One could otherwise say that (lambda x: x+x) is not anonymous either, since id(lambda ...) is a unique label stuck to it like a __name__. > If our concern is Python's suitability for studying principles of > programming, I think I'm on stronger ground. Python is great for > getting things done. It is easy to learn in the sense of learning > to to use if for practical tasks. Python's actual semantics are not > as neat and clean as some other languages. Fair enough. From bj_666 at gmx.net Wed Sep 19 07:56:19 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Sep 2007 11:56:19 GMT Subject: lambda-funcs problem References: <1190201984.062329.182460@k79g2000hse.googlegroups.com> Message-ID: <5lch33F78tegU2@mid.uni-berlin.de> On Wed, 19 Sep 2007 04:39:44 -0700, dmitrey.kroshko wrote: > I need to create a Python list of lambda-funcs that are dependent on > the number of the ones, for example > > F = [] > for i in xrange(N): > F.append(lambda x: x + i) > > however, the example don't work - since i in end is N-1 it yields x+ > (N-1) for any func. > > So what's the best way to make it valid? The variable is bound to the name `i` when the lambda function is created not to the value that `i` had at that time. The idiomatic way is to use a default value for an argument because those are evaluated at definition time of functions:: F.append(lambda x, i=i: x + i) Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Mon Sep 17 19:20:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Sep 2007 16:20:09 -0700 Subject: qa In-Reply-To: <1190067743.203008.162280@k79g2000hse.googlegroups.com> References: <46EEEE71.80108@gmail.com> <1190067743.203008.162280@k79g2000hse.googlegroups.com> Message-ID: <1190071209.302485.48700@22g2000hsm.googlegroups.com> On 17 sep, 19:22, John Machin wrote: > On Sep 18, 7:59 am, "Gabriel Genellina" > wrote: > > > It doesn't matter how many spaces you put in between, capwords will > > collapse all of them into a single space. > > This is true. However AFAICT the OP doesn't have multiple spaces -- > unless of course his unspecified s1 had trailing space(s) and/or his > unspecified s2 had leading space(s)!! Yes, unfortunately (to the OP) my crystall ball is on repair, and I'm using the spare one, which is not as good and has a narrower range than my large ball :) -- Gabriel Genellina From malibuster at gmail.com Wed Sep 5 12:13:29 2007 From: malibuster at gmail.com (malibuster at gmail.com) Date: Wed, 05 Sep 2007 09:13:29 -0700 Subject: Text processing and file creation Message-ID: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> I have a text source file of about 20.000 lines. >From this file, I like to write the first 5 lines to a new file. Close that file, grab the next 5 lines write these to a new file... grabbing 5 lines and creating new files until processing of all 20.000 lines is done. Is there an efficient way to do this in Python? In advance, thanks for your help. From byte8bits at gmail.com Tue Sep 25 17:42:26 2007 From: byte8bits at gmail.com (byte8bits at gmail.com) Date: Tue, 25 Sep 2007 21:42:26 -0000 Subject: comparing elements of a list with a string In-Reply-To: <1190734785.439839.303030@50g2000hsm.googlegroups.com> References: <1190734785.439839.303030@50g2000hsm.googlegroups.com> Message-ID: <1190756546.077433.257760@57g2000hsv.googlegroups.com> On Sep 25, 11:39 am, Shriphani wrote: > If I have a string "fstab", and I want to list out the files in whose names > the word fstab appears should I go about like this : > > def listAllbackups(file): > list_of_files = os.listdir("/home/shriphani/backupdir") > for element in list_of_files: > if element.find(file) != -1: > date = ### > time = #### > return (date, time) I would do something like this instead: >>> for root, dirs, files in os.walk('.'): ... for f in files: ... if 'text' in f: ... print f ... gimp-text-tool gimp-text-tool.presets text.py~ textwrap.pyc textwrap.py ... You can append the output to a list and return that list if you want to encapsulate this in a function. From dejanews at email.com Sun Sep 9 21:48:45 2007 From: dejanews at email.com (samwyse) Date: Mon, 10 Sep 2007 01:48:45 GMT Subject: Symbolic Link In-Reply-To: <1187879000.370831.118780@j4g2000prf.googlegroups.com> References: <1187475296.173269.263080@k79g2000hse.googlegroups.com> <1187555373.202634.163160@57g2000hsv.googlegroups.com> <1187646982.760523.195750@i38g2000prf.googlegroups.com> <1187879000.370831.118780@j4g2000prf.googlegroups.com> Message-ID: <1o1Fi.33230$RX.26068@newssvr11.news.prodigy.net> mosscliffe wrote: > On 22 Aug, 00:05, Ian Clark wrote: >> >>>On Aug 19, 4:29 pm,mosscliffe wrote: >>> >>>>The source file is in an area which python can see, but not the >>>>browser. I am trying to make a link in a browser friendly area so I >>>>can use it to display an image file. >> >>My question would be why a symbolic link? Why not a hard link? Are the >>two directories on different mount points? After the script finishes >>does python need to see that image file again? Why not just move it? > > I have tested a hard link now and it seems to work fine. I am > deleting the link/s at the end of the session/s. This is a bit late, but the reason the symbolic link won't work is because it's the web-server that's resolving it. The browser can only see things that the web-server, huh, serves, so what was meant in the first paragraph above was that the web server couldn't access the file in its original location. If you create a sym-link, the web server opens the link, finds out the actual location of the file, and tries to open that file, which it still can't do. A hard-link, OTOH, allows direct access to the contents of a file, as long as it is on the same filesystem. No extra steps are required, so the process runs a few microseconds faster, and directory-level permissions can't get in the way. From rbonvall at gmail.com Tue Sep 11 23:08:48 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Wed, 12 Sep 2007 03:08:48 -0000 Subject: "Variable variable name" or "variable lvalue" In-Reply-To: References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> Message-ID: <1189566528.536915.219610@22g2000hsm.googlegroups.com> On Aug 15, 4:19 pm, Peter Otten <__pete... at web.de> wrote: > If you want to simplify things somewhat you can merge the two loops into > one: > > numbers = [12.5, 25, 12.5] > accu = Material(numbers[0]) > for x in numbers[1:]: > accu += Material(x) > period = Slab(accu) Better to use the `sum' builtin and a generator expression: period = Slab(sum(Material(x)) for x in numbers) -- Roberto Bonvallet From srijit at yahoo.com Wed Sep 12 08:06:02 2007 From: srijit at yahoo.com (Srijit Kumar Bhadra) Date: Wed, 12 Sep 2007 05:06:02 -0700 Subject: SIP examples Message-ID: <1189598762.360580.119240@22g2000hsm.googlegroups.com> I am trying to learn SIP (http://www.riverbankcomputing.co.uk/sip/) these days. I do not see any examples similar to SWIG. http://www.swig.org/doc.html has lots of examples. But for SIP, all I see is a reference guide (http://www.riverbankcomputing.com/Docs/sip4/sipref.html). Examples help. Where can I get examples for SIP 4.7? Regards, /Srijit From Blinston_Fernandes at Dell.com Mon Sep 17 22:17:17 2007 From: Blinston_Fernandes at Dell.com (Blinston_Fernandes at Dell.com) Date: Tue, 18 Sep 2007 07:47:17 +0530 Subject: why does Configparser change names to lowercase ? In-Reply-To: References: <46EAED39.9080209@gmail.com> Message-ID: This works ... Cf=ConfigParser.ConfigParser() Cf.optionxform=str ... Blinston. -----Original Message----- From: python-list-bounces+blinston_fernandes=dell.com at python.org [mailto:python-list-bounces+blinston_fernandes=dell.com at python.org] On Behalf Of Joshua J. Kugler Sent: Tuesday, September 18, 2007 3:44 AM To: python-list at python.org Subject: Re: why does Configparser change names to lowercase ? On Friday 14 September 2007 12:21, stef mientki wrote: > Why does Configparser change names to lowercase ? > > As Python is case sensitive (which btw I don't like at all ;-) but now > when really need the casesensitivity, because it handles about names > which should be recognized by human, it changes everything to > lowercase ???? > > thanks, > Stef Mientki According to the ConfigParser docs: "All option names used in interpolation will be passed through the optionxform() method just like any other option name reference. For example, using the default implementation of optionxform() (which converts option names to lower case), the values "foo %(bar)s" and "foo %(BAR)s" are equivalent." So, it seems it would be trivial so sublcass ConfigParser, and reimplement optionxform() Hope that helps. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- http://mail.python.org/mailman/listinfo/python-list From kenneth.m.mcdonald at sbcglobal.net Tue Sep 4 15:15:43 2007 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Tue, 04 Sep 2007 14:15:43 -0500 Subject: Questions on FOX GUI and Python Message-ID: <46DDAEDF.8000500@sbcglobal.net> Would anyone care to offer their opinions as to using Python with the FOX GUI toolkit? Ease of use, stability, power, speed, etc., all thoughts would be appreciated. Thanks, Ken From gagsl-py2 at yahoo.com.ar Thu Sep 27 18:33:20 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Sep 2007 19:33:20 -0300 Subject: making run time changes.. References: <000001c80107$4f9ff120$eedfd360$@iitk.ac.in> <002f01c80126$d08aee10$71a0ca30$@iitk.ac.in> Message-ID: En Thu, 27 Sep 2007 13:52:39 -0300, Piyush Jain escribi?: >> I am new(almost) to python. I wish to making a server in which I can >> make changes at run time. For example , add a method to a >> class/attribute to object etc. by sending it messages. To add a new attribute with a name known only at runtime, use setattr either on the class (will be a class attribute then) or any individual instance. To create a new method, just assign a function to the class. I'd suggest first learning a bit more about Python until you are more fluent with the language. (And consider the risk of executing untrusted code from the outside). -- Gabriel Genellina From bj_666 at gmx.net Tue Sep 11 02:18:08 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Sep 2007 06:18:08 GMT Subject: printing list containing unicode string References: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> <1189477580.214510.212420@22g2000hsm.googlegroups.com> Message-ID: <5kmq90F4b65dU2@mid.uni-berlin.de> On Mon, 10 Sep 2007 19:26:20 -0700, Xah Lee wrote: > ? Many Internet standards are defined in terms of textual data, and > can't handle content with embedded zero bytes. > > Not sure what he mean by "can't handle content with embedded zero > bytes". Overall i think this sentence is silly, and he's probably > thinking in unix/linux. No he's probably thinking of all the text based protocols (HTTP, SMTP, ?) and that one of the most used programming languages, C, can't cope with embedded null bytes in strings. > ? Encodings don't have to handle every possible Unicode > character, .... > > This is inane. A encoding, by definition, turns numbers into binary > numbers (in our context, it means a encoding handles all unicode chars > by definition). How do you encode chinese characters with the ISO-8859-1 encoding? This encoding obviously doesn't handle *all* unicode characters. > ? > UTF-8 has several convenient properties: > 1. It can handle any Unicode code point. > ... > > > As mentioned before, by definition, any Unicode encoding encodes all > unicode char set. The mentioning of above as a "convenient property" > is inane. You are being silly here. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Sun Sep 30 23:32:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 01 Oct 2007 00:32:08 -0300 Subject: s.split() on multiple separators References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> <1191179790.181227.323480@k79g2000hse.googlegroups.com> Message-ID: En Sun, 30 Sep 2007 16:16:30 -0300, escribi?: >> From my POV, if I want sequence from here to there, it should include > both here and there. > > I do understand the consequences of making high bound exclusive, which > is more elegant code: xrange(len(c)). But it does seem a bit > illogical... See this note from E.W.Dijkstra in 1982 where he says that the Python convention is the best choice. http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html -- Gabriel Genellina From horpner at yahoo.com Tue Sep 4 06:44:27 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 04 Sep 2007 10:44:27 GMT Subject: OT: pronounciation [was: list index()] References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> <46D7E36D.4000301@timgolden.me.uk> <1188591855.327294.181280@r34g2000hsd.googlegroups.com> Message-ID: On 2007-08-31, Paddy wrote: > On Aug 31, 11:19 am, Tim Golden wrote: >> Tim Golden wrote: >> > Erik Max Francis wrote: >> >> Paddy wrote: >> >> >>> I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll >> >>> and role similarly. >> >> >>> My accent is probably from the East Midlands of the UK, but is not >> >>> pronounced. >> >> _Troll_ and _frolic_ aren't pronounced with the same "o" sound in any >> >> accent I've ever heard of. Which you pronounce _boat_ and _bot_ the >> >> same way, too? >> >> > [Amusingly contemplating a trolling war about the pronunciation of "troll"] >> >> > Well they sound the same in my more-or-less South London accent. >> > I can't write those funny phonetic symbols (and I hate to >> > imagine the Unicode encoding hoops I'd have to jump through >> > to make them readable anyway) but both "o"s sound short to me. >> > Like "bot" rather than "boat" using your example. >> >> Since we're talking... I'm still a little startled when I listen >> to some of the excellent webcasts that are being produced these >> days (showmedo.com and friends) and hear American voices pronounce >> Python... well, the way they do, with the stress and something of a >> drawl on the second syllable. I'm sure it's just as amusing the other >> way round: we pronounce it with the stress on the first syllable and >> the characteristic short vowel sound in the second. >> (Something like: Pie'thun). >> >> TJG > > The only true way of pronouncing Python (the computing language), is > the way it is done at the beginning of Monty Pythons Flying Circus of > course :-) > > Your right, the American way does make me pause. Ya'll can keep yer gall-dern schwa outta my Pie-thawn, ya hear? -- Neil Cerutti Persons are prohibited from picking flowers from any but their own graves. --sign at Pennsylvania cemetery From siona at chiark.greenend.org.uk Wed Sep 5 07:52:13 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 05 Sep 2007 12:52:13 +0100 (BST) Subject: FCGI app reloading on every request References: <46DCDE59.8060109@animats.com> Message-ID: John Nagle wrote: > Tried putting this in the .htaccess file: > > >SetHandler fcgid-script >Options ExecCGI >allow from all > > > >ErrorDocument 403 "File type not supported." > > > Even with that, a ".foo" file gets executed as a CGI script, >and so does a ".fcgi" file. It's an Apache configuration problem. I'd look to see if you've got a AllowOverride None set somewhere unhelpful (probably on the cgi-bin directory, although I note the default Apache2 config on my machine here does it for the document root too). Mind you, if you're managing this with a web tool rather than having access to the Apache config files, it might not be so straightforward to do. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From cmpython at gmail.com Sun Sep 30 13:27:08 2007 From: cmpython at gmail.com (cmpython at gmail.com) Date: Sun, 30 Sep 2007 17:27:08 -0000 Subject: Can you please give me some advice? In-Reply-To: <13fuv0gh7342r27@corp.supernews.com> References: <13fuv0gh7342r27@corp.supernews.com> Message-ID: <1191173228.756531.225860@o80g2000hse.googlegroups.com> > Hello World in Ruby (and a few other languages):http://www.oreillynet.com/ruby/blog/2005/12/hello_world.html > Hello World in Python:http://python.about.com/od/gettingstarted/ss/helloworld.htm I know nothing of Ruby, but just the fact that in Ruby the Hello World program is puts 'Hello, World!' whereas the Python Hello World program is print 'Hello, World!' suggests to me that Python is more intuitive because the word "print" has a meaning in English that makes sense given what you want to do, but "puts" just doesn't. And, as someone who has been learning Python from almost no knowledge of programming, I've found it is not too bad in trying to keep as reasonably close to a natural language like English as possible. I also think the mandatory indenting of Python is helpful in forcing new programmers to be neat and see code blocks quickly. Plus I doubt the Ruby community has such a large group of helpful people and libraries and such (but I could be wrong about that, just assuming it based on the fact that Python has been around longer). On the other hand, perhaps because Ruby is newer it has been able to freshly start with advantages learned from the difficulties of other languages. Byung-Hee Hwang ought to go the Ruby group and see what they are saying. As far as English goes, Byung-Hee, you have to admit English grammar is easy (though spelling is not so easy). That anyone can speak and write Chinese is impressive to me, as the language looks completely impossible! Good luck! From joe at goldthwaites.com Wed Sep 26 14:26:43 2007 From: joe at goldthwaites.com (Joe Goldthwaite) Date: Wed, 26 Sep 2007 11:26:43 -0700 Subject: A question on python performance. Message-ID: <000a01c8006a$cac4af00$6c01a8c0@applexp> Hi everyone, I'm a developer who's been using python for a couple of years. I wrote a fairly large application using it but I was learning the language at the same time so it most of the code kind of sucks. I've learned a lot since then and I've been going through my code trying to organize it better and make better use of Python's features. I'm still not an expert by any definition but I'm slowly getting better. I've been working on a trend class that takes twelve monthly numbers and returns a period to date, quarter to date, year to date and quarterly year to date numbers for a specific period. This worked but I ended up with a lot of code like this; def getValue(trend, param, per): if param == 'Ptd': return trend.Ptd(per) elif param == 'Qtd': return trend.Qtd(per) elif param == 'Ytd': return trend.Ytd(per) elif param == 'YtdQ': return trend.YtdQ(per) The code gets kind of wordy so I started trying to figure out how to call them dynamically since the param type is the same as the method the retrieves it. I came up with this; def getValue(trend, param, per): return trend.__class__.__dict__[param](trend, per) That worked but it seems like the above line would have to do lots more object look ups at runtime so I didn't think it would be very efficient. I thought maybe I could add a caller method to the trend class and I came up with this; class trend: ... ... ... def caller(self, param, *args): return self.__class__.__dict__[param](self, *args) This simplified the getValue function to this; def getValue(trend, param, per): return trend.caller(param, per) Out of curiosity, I thought I'd do some benchmarking and see which one performs the best. I executed three multiple times; loop one. Time=11.71 seconds; trend.Ptd(per) trend.Qtd(per) trend.Ytd(per) trend.YtdQ(per) loop two. 12.107 seconds; trend.__class__.__dict__['Ptd'](trend, per) trend.__class__.__dict__['Qtd'](trend, per) trend.__class__.__dict__['Ytd'](trend, per) trend.__class__.__dict__['YtdQ'](trend, per) loop three. 17.085 seconds; trend.caller('Ptd', per) trend.caller('Qtd', per) trend.caller('Ytd', per) trend.caller('YtdQ', per) The first surprise was how close the first and second loops were. I would have thought the first loop would be much faster. The second surprise was how much slower the third loop was. I know it has an extra call in there but other than that, it's doing basically the same thing as loop two. Is there that much overhead in making a class method call? Can anyone explain the differences? From david at boddie.org.uk Sun Sep 23 18:57:40 2007 From: david at boddie.org.uk (David Boddie) Date: Mon, 24 Sep 2007 00:57:40 +0200 Subject: building a GUI Message-ID: <200709240057.40451.david@boddie.org.uk> On Mon Sep 24 00:08:09 CEST 2007, stef mientki wrote: > Phil Thompson wrote: > > On Sunday 23 September 2007, stef mientki wrote: > > >> Could well be, > >> but I never looked at PyQt seriously, > >> because of their weird license. > > > > It's not weird. It's either GPL or proprietary. Your choice. That's as > > complicated as it gets. > > This is what I find "weird": > == quote == > Trolltech's commercial license terms do not allow you to start > developing proprietary software using the Open Source edition. > == end quote == Well, if you know you're going to be developing proprietary software, what on earth are you doing with the Open Source edition? OK, perhaps by asking that rhetorical question I'm simplifying people's reasons and motives for using Open Source (and in this case Free/Libre) software to develop tools or solutions that they later want to release as closed, proprietary products. There are lots of ways people can end up in that position, of course. Some people find their way there by accident; others know what the situation is going to be well in advance... In any case, I think it's useful to be clear about what each license does or does not allow, especially if this leads to people making informed decisions well before they learn about the consequences. In this case, the terms of the commercial license place certain demands on the licensee, just as with many other commercial licenses. If someone develops a product using a GPL-licensed library, they can always release that product under the GPL, even if that's not what they had in mind when they started. ;-) David From hniksic at xemacs.org Thu Sep 6 04:56:57 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 06 Sep 2007 10:56:57 +0200 Subject: creating really big lists References: <874pi92tr4.fsf@mulj.homelinux.net> <1189057626.943757.210420@d55g2000hsg.googlegroups.com> Message-ID: <877in4goiu.fsf@mulj.homelinux.net> Dr Mephesto writes: > I need some real speed! Is the speed with the GC turned off sufficient for your usage? From tokland at gmail.com Sat Sep 22 11:04:19 2007 From: tokland at gmail.com (tokland at gmail.com) Date: Sat, 22 Sep 2007 15:04:19 -0000 Subject: find difference in days from YYYYMMDD to YYYYMMDD In-Reply-To: References: Message-ID: <1190473459.642519.288580@g4g2000hsf.googlegroups.com> On 22 sep, 11:37, Konstantinos Pachopoulos wrote: > does any body now any such algorith? to find difference in days from > YYYYMMDD to YYYYMMDD? Once I needed the same and I wrote: def days_difference(s1, s2): splitdate = lambda s: time.strptime(s, "%Y%m%d")[:3] str2date = lambda s: datetime.date(*splitdate(s)) delta = str2date(s1) - str2date(s2) return delta.days print days_difference("20071112", "20061029") # 379 Although I'm sure there is a better way. arnau From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Sep 13 03:41:17 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 13 Sep 2007 09:41:17 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <1189651204.408268.57580@19g2000hsx.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> Message-ID: <46e8e998$0$20168$426a34cc@news.free.fr> TheFlyingDutchman a ?crit : >> >>> Foo.bar(foo, "spam") >> >>> foo.bar("spam") > > That looks like a case of "There's more than one way to do it". ;) Nope, on the contrary. The nice thing with this model is that you don't have distinct rules for functions and methods, since methods are just plain functions. >> The latter two statements are equivalent. The 'instance.method(args)' >> syntax is just sugar for 'Class.method(instance, args)'. > > I think I saw where Guido Van Rossum had referred to something as > "syntactic sugar" in some python.org page. I am not familiar with > sugar as related to syntax. Is it being used as a synonym for "easier > way of doing it"? Yes. "syntactic sugar" mostly means "nicer, simpler syntax for something that could be done without". And one of the *great* strength of Python is that it exposes both the syntactic sugar for the most common uses case and the underlying implementation for most advanced tricks. From tjreedy at udel.edu Fri Sep 14 12:41:15 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Sep 2007 12:41:15 -0400 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com><46e7974d$0$31726$426a74cc@news.free.fr><5kq1hgF4r90oU1@mid.individual.net><1189618530.872819.136450@57g2000hsv.googlegroups.com><1189619033.968437.286580@g4g2000hsf.googlegroups.com><5kr8vlF53m8gU3@mid.individual.net><1189643616.826715.58150@d55g2000hsg.googlegroups.com><5ksoaoF5am8cU1@mid.individual.net><1189701793.466307.93210@g4g2000hsf.googlegroups.com><5ktfjqF5ctrvU2@mid.individual.net><46e98fd8$0$27757$426a34cc@news.free.fr><5ktre7F5ig0vU1@mid.individual.net> <5kv3neF5mo3hU3@mid.individual.net> Message-ID: "Bjoern Schliessmann" wrote in message news:5kv3neF5mo3hU3 at mid.individual.net... That's interesting. BTW, do you know something (apart from the dis docs) that's worth reading if you're interested in Python byte code? ------------------ That is the only Python specific thing I remember reading. Of course, it helps that I learned assembler a long time ago, and that I have used an HP reverse-polish notation calculator (a fixed-size stack machine), and that I have seen and understand algorithms for turning prefix and infix to postfix notation. tjr From http Sun Sep 2 13:37:01 2007 From: http (Paul Rubin) Date: 02 Sep 2007 10:37:01 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188742231.470668.29910@g4g2000hsf.googlegroups.com> <1i3t4ha.1r0xx7414w0taxN%aleax@mac.com> <7xfy1x0zhk.fsf@ruckus.brouhaha.com> <1i3t5rz.1l19v341prahzxN%aleax@mac.com> Message-ID: <7xejhht1du.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > Reusing xranges is exactly what my code was doing Oh cool, I missed that, I was just going by the text description. Looking at the code, yes, it's re-using the xranges. Thanks. From dstromberglists at gmail.com Mon Sep 24 18:38:38 2007 From: dstromberglists at gmail.com (Dan Stromberg) Date: Mon, 24 Sep 2007 15:38:38 -0700 Subject: Making a small change to a large XML document Message-ID: Say I want to take an existing XML document, and change the value="9997" and value="9998" to two different numbers, without changing any of the rest of the document - not even changing comments or indentation, if avoidable. What's the best way of doing it in python? My .xml file is full of such beans. I've played around with minidom a little in the past, and I'm targetting python 2.5.1. Thanks! From zentraders at gmail.com Wed Sep 12 20:08:50 2007 From: zentraders at gmail.com (Zentrader) Date: Wed, 12 Sep 2007 17:08:50 -0700 Subject: File Parsing Question In-Reply-To: References: <1189634861.631219.143310@57g2000hsv.googlegroups.com> Message-ID: <1189642130.651522.273310@d55g2000hsg.googlegroups.com> > for line in inp.readlines(): If you are now using readlines() instead of readline(), then a) it is only used once to read all data into a container b) you can access each element/line by it's relative number data=open(filename, "r").readlines() for eachline in data : (not readlines()) so try print data[0] ## first rec print data[9] ## 10th rec, etc you can use ctr = 0 for eachline in data: ##do something if ctr > 0: print "this line is", eachline ## or data[ctr] print "prev_line = ", data[ctr-1] ctr += 1 or a slightly different way stop = len(data) ctr=0 while ctr < stop: ## do something if ctr > 0 : this_line = data[ctr] prev_line = data[ctr-1] ctr += 1 Sorry, I don't use file.seek() so can't help there From kostaspaxos at yahoo.gr Thu Sep 20 03:12:43 2007 From: kostaspaxos at yahoo.gr (Konstantinos Pachopoulos) Date: Thu, 20 Sep 2007 10:12:43 +0300 Subject: cannot __getitem__ from DB reply list Message-ID: <46F21D6B.8070107@yahoo.gr> Hi, i have the following function: ################################ def getGNUPlotInputFeaturesVersion(self): s="" bugCommits=0 trdocCommits=0 featCommits=0 ct=CommitType() for version in self.releaseVersionsList_: self.execQuery("SELECT msg,prssedDevsFileNum,prssedMakesFileNum,prssedDocsFileNum,prssedGraphsFileNum FROM Commit WHERE \ projVersion=\""+version+"\";"); for tuple in self.dbcursor_.fetchall(): print tuple ################################ On the "print tuple" part, i get: kostas at sqo-oss:~/workspace/SVNLog2DB$ jython 2LaunchQueries.py Connection established to database... Traceback (innermost last): File "2LaunchQueries.py", line 5, in ? File "/home/kostas/workspace/SVNLog2DB/QueryExecutor.py", line 80, in getGNUPlotInputFeaturesVersion AttributeError: __getitem__ As far as i have read, this means, that there is a problem getting something from the list, because it might be FOR EXAMPLE , that "self.dbcursor_.fetchall()" doesn't return a list -i know it does. However, i did a "print self.dbcursor_.fetchall()" and i got a huge list of tuples... Why can't i iterate the list? Any advice? From ratchetgrid at googlemail.com Mon Sep 17 19:22:37 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Tue, 18 Sep 2007 00:22:37 +0100 Subject: adding a static class to another class In-Reply-To: <46eef7d2$0$13879$426a74cc@news.free.fr> References: <46eef7d2$0$13879$426a74cc@news.free.fr> Message-ID: <676224240709171622g49c366e7x3b58342b662b6b9@mail.gmail.com> Hi, I guess my description was a bit rubbish in retrospec, I dont even think the title of my email made sense....it doesnt to me now: class Manager(object): def __init__(self): pass def dosomething(self): return "RESULTS" class Foo(object): def __init__(self): self.a = "NEE" What I m trying to do is end up with the following syntax: f = Foo() # instantiates a Foo object g= Foo.objects.dosomething() # returns "RESULTS" The best way I ve found of doing this is overriding new class Foo(object): def __new__(cls, *args, **kw): cls.objects = Manager() ----> If I do it like this, I get exactly what I want - especially if I change the new method in Manager to one supplied by Bruno. However, I m playing around with SQLAlchemy (which is going to be used by some of the Managers I create, others will use different things) which means that overriding new is not allowed, I cant assign a mapper to Foo. So I was trying to think of another way of doing cls.objects = Manager()....and the only solution I could think of was to use a decorator and try to do it somehow....... >From Brunos answer I guess a decorator is not a good way of accomplishing this, so if there anyway of doing this without using a metaclass......or by using a decorator or not....any help would be greatly appreciated. Many Thanks in advance Nathan On 17/09/2007, Bruno Desthuilliers wrote: > Nathan Harmston a ?crit : > > HI, > > > > I m trying to start an api in a similar way to the djangic way of > > Class.objects.all(). Ie objects is a "Manager" class. > > > > So: > > > > class Foo(object): > > def __init__(self): > > self.test = "NEE" > > > > class Manager(object): > > def __init__(self): > > pass > > def all(self): > > return "COCONUTS" > > > > Because of how some of the code is set up I cant use > > metaclasses........so I try to use a decorator: > > > > def addto(instance): > > def decorator(f): > > import new > > f = new.instancemethod(f, instance, instance.__class__) > > setattr(instance, "objects", f) > > return f > > return decorator > > > > class Manager(object): > > @addto(Foo) > > def __init__(self): > > ............. > > > > however this only binds the init method to the Foo.objects, so not > > what I want. > > Indeed. > > > If I try using classmethod...then it just says the > > Foo.objects doesnt exist. > > You mean decorating Manager.__init__ with classmethod ??? > > I may be wrong, but I suspect you don't have a clear idea of what you're > doing here. > > > Does anyone have any ideas how I can accomplish this using decorators? > > Yes : don't use a decorator !-) > > Instead of asking for how to implement what you think is the solution, > you might be better explaining the problem you're trying to solve. > > > And also preventing more than one Manager instance instantiated at one > > time. > > Q&D: > > class Singleton(object): > def __new__(cls): > if not hasattr(cls, '_inst'): > cls._inst = object.__new__(cls) > return cls._inst > > > Same remark as above... > -- > http://mail.python.org/mailman/listinfo/python-list > From sjmachin at lexicon.net Wed Sep 5 09:09:24 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 05 Sep 2007 06:09:24 -0700 Subject: creating really big lists In-Reply-To: <1188985838.661821.41530@k79g2000hse.googlegroups.com> References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> Message-ID: <1188997764.337396.15640@r34g2000hsd.googlegroups.com> On Sep 5, 7:50 pm, Dr Mephesto wrote: > Hi! > > I would like to create a pretty big list of lists; a list 3,000,000 > long, each entry containing 5 empty lists. My application will append > data each of the 5 sublists, so they will be of varying lengths (so no > arrays!). Will each and every of the 3,000,000 slots be used? If not, you may be much better off storagewise if you used a dictionary instead of a list, at the cost of slower access. Cheers, John From paul.nospam at rudin.co.uk Thu Sep 20 12:53:57 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 20 Sep 2007 17:53:57 +0100 Subject: An Editor that Skips to the End of a Def References: Message-ID: <87odfxjn16.fsf@rudin.co.uk> "W. Watson" writes: > Is there an editor that allows one to position to put the cursor and > then by pushing some button goes to the end of the def? C-M-e in emacs/python-mode. From grante at visi.com Tue Sep 4 11:34:34 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 04 Sep 2007 15:34:34 -0000 Subject: How do I get triangles from a vtkPolyData object? References: <13do9eh8dtqa236@corp.supernews.com> Message-ID: <13dquoa1r252o60@corp.supernews.com> On 2007-09-03, Grant Edwards wrote: Is there _any_ documentation for the Python bindings to the vtk library? I'm still beating my head against a wall trying to figure out how to get the actual data out of vtk objects when Python doesn't make visible the required "Get" methods.... > I posted this question to the vtk mailing list last week: > > I've been Googling and wandering through the class references > most of the afternoon, but I can't figure out how to get the > triangles out of the vtkPolyData that vtkDelaunay2D produces? > > I can get the vertex corredinates like this: > > delny = vtk.vtkDelaunay2D() > delny.SetInput(profile) > delny.SetTolerance(0.001) > delny.Update() > > o = delny.GetOutput() > > vertexes = [o.GetPoint(i) for i in xrange(o.GetNumberOfPoints())] > > I can see that there are 84 triangles, and 'o' is a vtkPolyData > object that has 84 cells and 84 polygons, so they obviously > represent the triangles, but I can't figure out how to get > something useful out of the cells or polys. > > I got multiple replies telling me that I need to make calls to > o.GetNextCell(). The posters were even kind enough to include > examples in C++ showing how to do a delaunay triangulation and > retrieve the triangle info. I accidentally left out a step -- it's actually a vtkCellArray object obtained by calling o.GetPolys() that is missing the GetCell() and GetNextCell() methods which I need to call. -- Grant Edwards grante Yow! My mind is a potato at field ... visi.com From gagsl-py2 at yahoo.com.ar Fri Sep 14 00:23:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Sep 2007 01:23:52 -0300 Subject: Setting stdout encoding References: <1189416350.069995.220250@w3g2000hsg.googlegroups.com> <00e601c7f5fb$43d5ccf0$0203a8c0@MOUSE> Message-ID: En Thu, 13 Sep 2007 08:43:11 -0300, Ryan Ginstrom escribi?: >> On Behalf Of Fabio Zadrozny >> Makes sense... Do you think that creating a new object, >> setting it as sys.stdout and overriding its write() method to >> check for a unicode string to do >> original_stdout.write(unicode_str.encode(my_encoding)) would >> do it? > > Here's an output stream encoder I have used. It might be kind of > screwball, > so I'd welcome any feedback on it, but it does work for encoding output > streams. Looks fine to me, just two comments: > def write(self, obj): > """Wraps the output stream's write method, encoding it with > the specified encoding""" > > self.stdout.write(obj.encode(self.encoding)) You should check that obj is an unicode object before calling encode. Strings should not be encoded. > def __getattr__(self, attr): > """Delegate everything but write to the stream""" > > if attr != "write": > return getattr(self.stdout, attr) > return self.write __getattr__ is only called when the attribute has NOT been found in the usual way, so checking for "write" is unnecesary. Just return getattr(self.stdout, attr) always. -- Gabriel Genellina From steven at REMOVE.THIS.cybersource.com.au Fri Sep 7 06:34:08 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Sep 2007 10:34:08 -0000 Subject: Checking if elements are empty References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Fri, 07 Sep 2007 11:12:05 +0200, Wildemar Wildenburger wrote: > Lawrence D'Oliveiro wrote: >> In message , Chris >> Mellon wrote: >> >>> On 9/5/07, Steve Holden wrote: >>>> Doran, Harold wrote: >>>>> Is there a way to check if the first element of y is null? >>>>> >>>> len(y[0]) == 0 >>>> >>> Better spelled as >>> >>> if y[0]: >> >> Not a good idea. > > Why not? What happens if y is an empty list? -- Steven. From mail at microcorp.co.za Sat Sep 1 02:28:21 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 1 Sep 2007 08:28:21 +0200 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com><46d674c2$0$417$426a34cc@news.free.fr><1188496588.750629.208100@g4g2000hsf.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> Message-ID: <003301c7ec61$4b6d8500$03000080@hendrik> "Erik Max Francis" wrote: > Hendrik van Rooyen wrote: > > > weird this - maybe a native English speaker can comment - > > when I pronounce what fishermen do - it rhymes with roll, > > but when I am talking about the thing that lives under bridges > > and munches goats, the "O" sound is shorter, and more > > towards the back of my mouth. > > Native English accents vary as well, but _roll_ rhymes with _troll_, not > _trawl_. _Trawl_ would rhyme with _fall_, and _fall_ definitely doesn't > rhyme with _roll_. > I did not mean using a net to scour the seabed - Trawl, I meant using a spoon to see what you can induce to strike - Troll - Hendrik From gregpinero at gmail.com Sun Sep 23 00:16:43 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Sun, 23 Sep 2007 04:16:43 -0000 Subject: subprocess -popen - reading stdout from child - hangs In-Reply-To: <1190518129.356844.242710@19g2000hsx.googlegroups.com> References: <1190518129.356844.242710@19g2000hsx.googlegroups.com> Message-ID: <1190521003.928634.48900@d55g2000hsg.googlegroups.com> On Sep 22, 11:28 pm, "gregpin... at gmail.com" wrote: > Let's say I have this Python file called loop.py: > > import sys > print 'hi' > sys.stdout.flush() > while 1: > pass > > And I want to call it from another Python process and read the value > 'hi'. How would I do it? > > So far I have tried this: > > >>> proc = subprocess.Popen('python /home/chiefinnovator/loop.py',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE) > >>> proc.stdout.read() > > But it just hangs at read() > > proc.communicate() also just hangs. What am I doing wrong? Please > advise. Well, using this subclass of subprocess.Popen fixes the problem (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554) I don't understand how it works though. Would anyone mind explaining? I'm thinking there's something fundamental about Unix processes I'm not understanding. -Greg From timr at probo.com Sun Sep 16 22:41:59 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 17 Sep 2007 02:41:59 GMT Subject: curses: x, y positioning References: <1189891633.622313.81850@r29g2000hsg.googlegroups.com> Message-ID: 7stud wrote: >I can't see to get any y, x coordinates to work with curses. Here is >an example: > >import curses > >def my_program(screen): > while True: > ch = screen.getch() > if ch == ord("q"): > break > if ch <= 255: > screen.addstr(30, 10, "*%s*" % chr(ch)) > screen.refresh() > >curses.wrapper(my_program) Don't you want mvaddstr? (And remember that y comes first.) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gavin at madzag.com Fri Sep 14 00:57:43 2007 From: gavin at madzag.com (Gavin Tomlins) Date: Fri, 14 Sep 2007 14:57:43 +1000 Subject: Spaces from string specifier Message-ID: <03a601c7f68b$ccdf1ed0$669d5c70$@com> Greetings all, I'm trying to work out when using a format specifier I get spaces in the resulting string. Eg. Looking at the outputted string you can see that there are spaces after T5LAT, F4LAT etc. as I result from trying to keep the code aligned Does anyone have any insights in how to prevent this ? Regards Gavin --- Code Fragment --- fmtSqlP300Amp = 'UPDATE Patient SET \ O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s", P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s", TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s", \ CP3AMP = "%s", CPzAMP = "%s", CzAMP = "%s", FC4AMP = "%s", FT8AMP = "%s", TP7AMP = "%s", C3AMP = "%s", FCzAMP = "%s", FzAMP = "%s", F4AMP = "%s", F8AMP = "%s", \ T3AMP = "%s", FT7AMP = "%s", FC3AMP = "%s", F3AMP = "%s", FP2AMP = "%s", F7AMP = "%s", FP1AMP = "%s" \ WHERE Pat_Id = "%s;"' sqlAmpString = fmtSqlP300Amp % ( self.ERPAmpSites[O2],self.ERPAmpSites[O1],self.ERPAmpSites[Oz],self.ERPAmpSi tes[Pz],self.ERPAmpSites[P4],self.ERPAmpSites[CP4],self.ERPAmpSites[T6], \ self.ERPAmpSites[C4],self.ERPAmpSites[TP8],self.ERPAmpSites[T4],self.ERPAmpS ites[T5],self.ERPAmpSites[P3],self.ERPAmpSites[CP3], \ self.ERPAmpSites[CPz],self.ERPAmpSites[Cz],self.ERPAmpSites[FC4],self.ERPAmp Sites[FT8],self.ERPAmpSites[TP7],self.ERPAmpSites[C3], \ self.ERPAmpSites[FCz],self.ERPAmpSites[Fz],self.ERPAmpSites[F4],self.ERPAmpS ites[F8],self.ERPAmpSites[T3],self.ERPAmpSites[FT7], \ self.ERPAmpSites[FC3],self.ERPAmpSites[F3],self.ERPAmpSites[FP2],self.ERPAmp Sites[F7],self.ERPAmpSites[FP1], self.ERPPatId) print sqlAmpString --- Output --- .................................................... sqlAmpString .................................................... UPDATE Patient SET O2AMP = "2.43119", O1AMP = "2.77413", OzAMP = "2.47781", PzAMP = "2.50786", P4AMP = "4.579", CP4AMP = "3.50302", T6AMP = "9.55172", C4AMP = "1.21119", TP8AMP = "5.6498", T4AMP = "1.29149", T5AMP = "0.565705", P3AMP = "-0.957866", CP3AMP = "-0.231566", CPzAMP = "0.970299", CzAMP = "-0.214471", FC4AMP = "-0.607667", FT8AMP = "-0.226904", TP7AMP = "-1.51269", C3AMP = "-1.26248", FCzAMP = "-1.61319", FzAMP = "-2.55086", F4AMP = "-1.87688", F8AMP = "-1.11846", T3AMP = "-1.98619", FT7AMP = "-2.0613", FC3AMP = "-1.8458", F3AMP = "-2.23433", FP2AMP = "-2.01364", F7AMP = "-1.80539", FP1AMP = "-2.00328" WHERE Pat_Id = "GT0001;" -------------- next part -------------- An HTML attachment was scrubbed... URL: From hanke at brailcom.org Thu Sep 20 09:24:22 2007 From: hanke at brailcom.org (Hynek Hanke) Date: Thu, 20 Sep 2007 09:24:22 -0400 Subject: pdb attach? Message-ID: <46F27486.4000504@brailcom.org> Hello, please, is there something like 'attach' in pdb yet? My application uses threads and when it freezes (e.g. due to a deadlock situation), I'd like to get the traceback of all threads and inspect at which point did the application get into problems. Or could I send a signal to such a python process so that it would output backtraces from all threads before terminating? Because currently, if a thread runs into deadlock problems (or a thread fails on an exception and the other thread can't join it), I have no way of determining what went wrong. Such processes are not possible to terminate via CTRL-C in the interpreter, so I can't get the backtrace this way. Furthermore, I also need to debug subprocesses, so these are difficult to invoke interactively. I'm happy for any suggestions. Thank you, Hynek Hanke From bignose+hates-spam at benfinney.id.au Tue Sep 18 19:11:37 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Sep 2007 09:11:37 +1000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> Message-ID: <876427zhzq.fsf@benfinney.id.au> Bruno Desthuilliers writes: > Ben Finney a ?crit : > > Evan Klitzke writes: > >> On Tue, 2007-09-18 at 14:15 +1000, Ben Finney wrote: > >>> [the 'super' function] doesn't return the superclass, it returns > >>> the next class in the MRO, whether that's a superclass or not. > >> The next class in the MRO _is_ a superclass. > > > > [demonstration that the next class in the MRO is not necessarily a > > superclass] > > > > You seem to be saying that now suddenly D *is* a superclass of > > A. > > I don't see such an assertion in Evan's answer. Chapter and verse > ??? I've trimmed the quoting to make it clearer. Evan is claiming that "the next class in the MRO _is_ a superclass", apparently by his definition or some other that I've not seen. I've shown a fairly simple multiple-inheritance hierarchy where the next class in the MRO is not an ancestor of the subject class, but is instead a class that merely shares a common ancestor. Either "superclass of A" is equivalent to "ancestor class of A", or it's not. I maintain that many programmers will expect that it is, but Evan's assertion says otherwise. It can't be both. > > That's certainly not what users will think of when they think > > "superclass" though. > > If a class X is in the MRO of call Y, then X is a superclass of Y. That goes completely against what Alex Martelli told me, which was that "superclass" can be thought of as synonymous with "ancestor". > I agree that the documentation for super is somewhat misleading (and > obviously wrong), Well, that's the first time someone has acknowledged that in this thread, so I guess this is something. > but it still *give access to* (at least one of) the superclass(es). Only if you allow "some class somewhere in the inheritance tree, even one this class never inherited from directly or indirectly" to be in the definition of "superclass". I'm arguing that what people mean by "superclass" is "a direct or indirect ancestor class", and it's highly misleading to imply that by the function name what that's not what the function does. > >>> After reading the rest of the article, I'm amazed that 'super' > >>> as currently implemented is in Python at all. > > If you have a better solution for handling multiple inheritence, > please share with us. My concern is to at least not *directly mislead* the programmer through a badly-named function. If 'super' can invoke a non-superclass ? if instead it gets "the next class in the MRO" ? then this is at the least badly-named. > FWIW, after all the articles I've read explaining why Python is > badly designed, badly implemented, and totally flawed, I do wonder > why this language exists at all !-) In most of those arguments I'm firmly on the side of the Python designers. Not on this one. > > I don't want to break the inheritance chain. I want the > > superclass, > > A soon as you have either multiple inheritence and/or an inheritence > tree with depth > 1, there's no such thing as "the" superclass. wrt/ > your exemple, object, A, B, C and D are *all* superclasses of E. Yes, they are. But my example was not "get the superclass of E", but "get the superclass of A". The *only* ancestor of 'A' in the example is 'object', so I expect "superclass of A" to *always* get 'object'. But that's not what happens! Instead, it *sometimes* gets 'object', and *sometimes* gets 'D' ? depending on who has inherited from a class that isn't even 'A'! That's what makes 'super' definitely misnamed, and practically unusable. > The next class in the MRO is (usually and AFAICT) the most direct > superclass. Demonstrably not, in the examples given in . > I wouldn't use such an extreme word as 'madness', but I totally agree > that this should be corrected. Care to submit a doc patch ? I don't understand what practical uses 'super' is intended for (only that they don't seem to match any of my needs), so the only replacement I would come up with would not be constructive. -- \ "A computer once beat me at chess, but it was no match for me | `\ at kick boxing." -- Emo Philips | _o__) | Ben Finney From kw at codebykevin.com Fri Sep 14 09:42:14 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 14 Sep 2007 09:42:14 -0400 Subject: Install Mac OS X - Idle doesn't show up In-Reply-To: References: Message-ID: <46EA8FB6.4040405@codebykevin.com> Dominique wrote: > Hello, > > Sorry bothering you with such a trivial problem. > > I installed python on a new mac at office. > It seems everything is fine: in the console, I access to python. > But I just can't start Idle. It seems to open but closes immediately (it appears > in the dock and closes immediately). > It is also impossible to open any .py file. > > I am sure some of you have a good idea of what to do (path,...). > > Thanks in advance > Dominique > How did you install/build Python? On the Mac, you really aren't supposed to start it from the terminal unless you are running it under X11 or are using a non-framework build. If you built it the standard Mac way, or if you use the binary installer from python.org, Idle is installed in /Applications/MacPython 2.5. Look there, and you should be able to drag the Idle icon to the dock. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From xah at xahlee.org Mon Sep 10 18:39:14 2007 From: xah at xahlee.org (Xah Lee) Date: Mon, 10 Sep 2007 15:39:14 -0700 Subject: printing list containing unicode string In-Reply-To: References: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> Message-ID: <1189463954.322906.130590@r34g2000hsd.googlegroups.com> Google groups seems to be stripping my quotation marks lately. Here's a retry to post my previous message. -------------------------------------------------------------- Xah Lee wrote: If i have a nested list, where the atoms are unicode strings, e.g. # -*- coding: utf-8 -*- ttt=[[u"?",u"?"], [u"???"],...] print ttt how can i print it without getting the u'\u1234' notation? i.e. i want it print just like this: [[u"?"], ...] Carsten Haese wrote: It's not quite clear why you want to do this, but this is how you could do it: print repr(ttt).decode("unicode_escape").encode("utf-8") Super! Thanks a lot. About why i want to... i think it's just simpler and easier on the eye? here's a example output from my program: [[u' ', 1022], [u'?', 472], [u' ', 128], [u'?w', 300], [u'?s', 12], [u'?|', 184],...] wouldn't it be preferable if Python print like this by default... Xah x... at xahlee.org ? http://xahlee.org/ From zzbbaadd at aol.com Mon Sep 10 23:37:31 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 10 Sep 2007 20:37:31 -0700 Subject: Enum class with ToString functionality In-Reply-To: References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <87bqca9hrw.fsf@benfinney.id.au> <1189472591.797327.189180@w3g2000hsg.googlegroups.com> <87sl5m7xxm.fsf@benfinney.id.au> <1189478288.237609.25140@50g2000hsm.googlegroups.com> Message-ID: <1189481851.468452.198260@d55g2000hsg.googlegroups.com> On Sep 10, 7:55 pm, "J. Cliff Dyer" wrote: > TheFlyingDutchman wrote: > > On Sep 10, 7:12 pm, Ben Finney > > wrote: > >> TheFlyingDutchman writes: > >>>> > >> (Please preserve attribution lines so it's clear who wrote what.) > > >>> Looking at the documentation it looks excellent. But I don't > >>> understand the 0.4.2 version number, > >> Note the tag that says the "Development Status" is "Beta". > > >>> particularly when you refer to it as robust. > >> I assume you're referring to the short description, "Robust > >> enumerated type support in Python". > > >> That refers to the implemented type as robust, not the state of > >> the code. That is, the short description should be read as > >> "Support, in Python, for robust enumerated types". It's a > >> description of the package functionality. > > >> If, of course, the state of the code is not robust, that's a bug > >> that needs to be fixed; but that's true for any package. > > >> -- \ "Try to become not a man of success, but try rather to > >> become a | `\ man of value." > >> -Albert Einstein | _o__) > >> | Ben Finney > > > What is the difference between this version and the 1.0 version? > > Uh... The 1.0 version is vaporware? > > Cheers, > Cliff I think not. 42% of it is alive and kicking as we speak. From jeff at taupro.com Mon Sep 3 04:41:54 2007 From: jeff at taupro.com (Jeff Rush) Date: Mon, 03 Sep 2007 03:41:54 -0500 Subject: ShowMeDo.com Announces Winner of Most-Video-Plays of the Month Message-ID: <46DBC8D2.1000404@taupro.com> ShowMeDo.com, a website offering over 361 instructional screencasts about topics both Python and non-Python, has announced their first winner of the month for the most-played video. And the winner is: "Learn Django: Create a Wiki in 20 minutes" by Siddharta Govindaraj, founder of Silver Stripe Software, with 1851 views in August, far outpacing the second-place entry. The prize is a ?20 (UK) voucher to Amazon. Congratulations, Siddhi! You can watch it at: http://showmedo.com/videos/video?name=1100000&fromSeriesID=110 Siddhi is also helping Doug Napoleone with PyCon this year, providing a program for generating attendee badges and working to integrate it into the Django-based conference site. You can find Siddhi at: http://siddhi.blogspot.com/ http://www.silverstripesoftware.com/ So who will win this month? It could be you! How about a screencast showcasing a different web framework like TurboGears or Twisted Web? Or something about databases, either relational or object. Jeff Rush Python Advocacy Coordinator From dtrudgett at yahoo.com Sat Sep 15 00:54:32 2007 From: dtrudgett at yahoo.com (David Trudgett) Date: Sat, 15 Sep 2007 14:54:32 +1000 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> Message-ID: TheFlyingDutchman writes: > The confusing way about the current Python method when you first > encounter it is > why is "self" being passed in when you write the function but not > when you call it. If the compiler is smart enough to know that > > a = MyClass() > a.SomeFunction(12) > > SomeFunction() has a "self" implicitly added to the parameter list, it > seems that it should be smart enough to know that a function defined > in a class has a "self" implicitly added to the parameter list. Several languages use the "object.method(args)" form, which is syntactic sugar for "method(object, other_args)" which Ada, for instance, uses. Knowing this clears up half the confusion (the object /is/ passed as a parameter whichever syntax is used). The other half of the confusion is cleared up by considering that Python methods are ordinary functions that don't magically "know" in which "class" context they are executing: they must be told via the first parameter. David Trudgett -- These are not the droids you are looking for. Move along. From shankarjee at gmail.com Wed Sep 12 18:28:08 2007 From: shankarjee at gmail.com (Shankarjee Krishnamoorthi) Date: Wed, 12 Sep 2007 17:28:08 -0500 Subject: File Parsing Question In-Reply-To: <1189634861.631219.143310@57g2000hsv.googlegroups.com> References: <1189634861.631219.143310@57g2000hsv.googlegroups.com> Message-ID: I would prefer to use something with seek. I am not able to use seek() with "for line in inp". Use tell and seek does not seem to do anything with the code. When I try to do for line in inp.readlines(): # Top of Loop if not condition in line: do_something else: for lines in inp.readlines(): if not condition do_something else: break pos = inp.tell() inp.seek(pos) ---> This line has not effect in the program Not sure if Iam missing something very basic. Also the previous line needs to be used in the position I call # Top of Loop. Thanks On 9/12/07, Zentrader wrote: > I'm assuming you know that python has a file.seek(), but you have to > know the number of bytes you want to move from the beginning of the > file or from the current location. You could save the length of the > previous record, and use file seek to backup and then move forward, > but it is simpler to save the previous rec or use readlines() if the > file will fit into a reasonable amount of memory. > > -- > http://mail.python.org/mailman/listinfo/python-list > From bbrown at speakeasy.net Tue Sep 11 04:29:11 2007 From: bbrown at speakeasy.net (Robert Brown) Date: Tue, 11 Sep 2007 04:29:11 -0400 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> <13dmctogeh19410@corp.supernews.com> Message-ID: Neil Cerutti writes: > On 2007-09-02, Steven D'Aprano > wrote: >> A big question mark in my mind is Lisp, which according to >> aficionados is just as dynamic as Python, but has native >> compilers that generate code running as fast as highly >> optimized C. > Lisp, as far as I know, requires type declarations, discipline, > deep knowledge of Lisp, and more than passing knowledge of your > Lisp implementation in order to generate code that's competitive > with C. On my Mac Mini, the original Python code runs in 6 minutes 37 seconds using Python 2.3.5. The Common Lisp code below, a straightforward translation, containing *no* type declarations, runs in 27 seconds on the same Mini using SBCL. When the commented out optimization declaration is included in the code, the run time drops to 3.3 seconds. For comparison, run times with GCC on the C version posted earlier are 3.5 seconds unoptimized and 0.58 seconds with optimization flag "-O3". So for this example, deep knowledge of the Lisp implementation and type declarations are not required to get speed equivalent to unoptimized C code. Approaching the speed of optimized C code does require more work. ==================== (defun doit () ;; (declare (optimize (speed 3) (safety 0) (debug 0))) (let ((solutions (make-array 1001 :initial-element 0))) (loop for a upfrom 1 below 10000 do (loop for b upfrom 1 below (- 1000 a) do (loop for c upfrom 1 below (- 1000 a b) do (let ((p (+ a b c))) (when (and (< p 1000) (= (+ (* a a) (* b b)) (* c c))) (incf (aref solutions p))))))) (loop with max-index = 0 with max = 0 for solution across solutions for index upfrom 0 do (when (> solution max) (setf max solution) (setf max-index index)) finally (print max-index)))) From ivoras at _fer.hr_ Mon Sep 17 05:49:55 2007 From: ivoras at _fer.hr_ (Ivan Voras) Date: Mon, 17 Sep 2007 11:49:55 +0200 Subject: Python "with" In-Reply-To: References: Message-ID: Laurent Pointal wrote: > The ugly part is the 'tmp' name, try to choose a name with a proper > meaning about what it is really, and it become clean and readable: > > filerefs = some.big.structure.or.nested.object.with.file.references > filerefs.encoding = "utf-8" > filerefs.name = "MyFileName.txt" > filerefs.use_quotes = True > > Isn't it ? Well, no, but this might be due to personal tastes. At least, I don't think it's better then some other alternatives. For example, in C99 you can do: static struct option_s foo_option = { .name = "foo", .type = O_STRING, .def_value = "default" }; At least to me, this looks even better than the Pascal's syntax. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 257 bytes Desc: OpenPGP digital signature URL: From attn.steven.kuo at gmail.com Thu Sep 13 11:10:46 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 13 Sep 2007 08:10:46 -0700 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1i4bnbp.1l8sr3mjdojghN%aleax@mac.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> <1i4bnbp.1l8sr3mjdojghN%aleax@mac.com> Message-ID: <1189696246.195431.244960@22g2000hsm.googlegroups.com> On Sep 12, 10:05 am, al... at mac.com (Alex Martelli) wrote: ... > into a function and a call to it: > > def f(): > with implicit_self(t): > print a > print b > a = 40 > b = a * 2 > f() > > ...even with different values for the argument to _getframe. You just > can't "dynamically" add local variables to a function, beyond the set > the compiler has determined are local (and those are exactly the ones > that are *assigned to* in the function's body -- no less, no more -- > where "assigned to" includes name-binding statements such as 'def' and > 'class' in addition to plain assignment statements, of course). > > Making, say, 'a' hiddenly mean 'x.a', within a function, requires a > decorator that suitably rewrites the function's bytecode... (after > which, it WOULD still be terrible and horrible and not to be used, just > as you say, but it might at least _work_;-). Main problem is, the > decorator needs to know the set of names to be "faked out" in this > terrible and horrible way at the time the 'def' statement executes: it > can't wait until runtime (to dynamically determine what's in var(self)) > before it rewrites the bytecode (well, I guess you _could_ arrange a > complicated system to do that, but it _would_ be ridiculously slow). > > You could try defeating the fundamental optimization that stands in your > way by adding, say, > exec 'pass' > inside the function-needing-fakeouts -- but we're getting deeper and > deeper into the mire...;-) What about abusing 'import' like this: def f(): with implicit_self(t): sys.modules['__the_mire__'] = t from __the_mire__ import a, b print a print b a = 40 b = a * 2 If the list of attributes is long then 'import' can save some typing compared to a = self.a b = self.b ... z = self.z -- Regards, Steven From bignose+hates-spam at benfinney.id.au Tue Sep 18 01:38:46 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 18 Sep 2007 15:38:46 +1000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> Message-ID: <87vea8zg61.fsf@benfinney.id.au> Evan Klitzke writes: > If you're using multiple inheritance, and you're _not_ using super > everywhere, then your code is broken anyway. This seems to support the notion that 'super' is unusable. If I inherit from code that isn't under my control, and then use super(), my code is broken. Therefore, to avoid writing broken code, I must either never inherit from code not under my control, or I must never use super(). Since the former is practically unavoidable, I must choose the latter. Which, naturally, compounds the problem, since when someone else uses *my* code, they in turn must conclude that they can't use super(). > Use super correctly in your own code, and you don't need to worry > about other people using it incorrectly. As the article points out, when using super(), you must remember that super does not call your superclass. You must be prepared to call any other class's method in the hierarchy and be prepared to be called from any other class's method. So, the programmer using super() very much *does* need to worry about other people using it correctly. -- \ "Quidquid latine dictum sit, altum viditur." ("Whatever is | `\ said in Latin, sounds profound.") -- Anonymous | _o__) | Ben Finney From arvind1.singh at gmail.com Sat Sep 29 23:48:16 2007 From: arvind1.singh at gmail.com (Arvind Singh) Date: Sun, 30 Sep 2007 09:18:16 +0530 Subject: HOT!!!PYTHON DEVELOPER REQUIRED @ ADOBE SYSTEMS In-Reply-To: <1190916344.841925.94900@57g2000hsv.googlegroups.com> References: <1190916344.841925.94900@57g2000hsv.googlegroups.com> Message-ID: THANKS for introducing me to Python "applets". Applications --> Applets --> Apploids --> Applcainers --> ... --> Approcities Sorry, couldn't resist. On 9/27/07, Recruiter-Adobe wrote: > > Hi PYTHON DEVELOPERS, > > ADOBE SYSTEMS is looking for a PYTHON DEVELOPER who can troubleshoot > Python based applet which makes data base queries and populates Excel > tables used to generate pivot charts, graphs and tables showing bug > metrics. Isolate problem which is causing reports to crash and > institute fix. > > This is a position through Manpower at our customer Adobe Systems, > you will be employed as a Manpower's contractor. > > Job Responsibilities: > > ? Setup a new server (development environment) > > ? Install updated versions of both python and other plugins > used for our applet. > > ? Import Code/applet instance. > > ? Remove code that uploads it to the Production Server > Instance > > ? Eventually move the entire Production Instance over to the > newer server. > > ? Update Code to comply with the latest Python standards > > Knowledge & Skills: > > ? Expert in Python Programming > > ? Experience in COM Object programming speficially Excel COM > Objects > > ? Experience in using WebServices (SOAP) > > ? Win2k System Administration Experience a Plus > > ? Need to migrate from version 2.3 to latest version of Python > > Hourly Pay rate: $85-$100/hr > > If interested, please send a Word copy of your resumeto > rbadame at manpowersj.com with your expected hourly rate, availability, > visa status, best time and phone # to contact you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards, Arvind -------------- next part -------------- An HTML attachment was scrubbed... URL: From stodge at gmail.com Wed Sep 19 20:43:25 2007 From: stodge at gmail.com (Stodge) Date: Wed, 19 Sep 2007 17:43:25 -0700 Subject: Saving parameters between Python applications? In-Reply-To: References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> <1190060967.696332.113190@n39g2000hsh.googlegroups.com> <1190122569.509673.41420@57g2000hsv.googlegroups.com> Message-ID: <1190249005.462312.281240@22g2000hsm.googlegroups.com> I wrote a small C program in Linux and used setenv() from stdlib and it modified the console's environment. I can also modify the console's environment from a DOS batch file, so why not in Python? Guess I'm inexperienced and I just don't get it. :) On Sep 18, 11:48 am, Steve Holden wrote: > Stodge wrote: > > os.path.expanduser isn't an option; I need each console/window to > > maintain different values which I wouldn't get from saving to a user's > > home directory. Unless I used a different file for each console/window > > but that just gets me into the same situation I'm already in. I think > > the only option is to set environment variables using another script. > > I'm really surprised and disapponited by this. > > That's a sign of your inexperience, then. As someone has already pointed > out, this is nothing to do with Python. > > Under UNIX/Linux you could use the $$ variable to construct a filename > specific to a particular shell process and put it in the environment, > but I'm not aware of a similar feature in Windows. This is probably a > sign of *my* inexperience :-) > > > One option I thought of but haven't investigated, is the ability to > > get the parent (i.e. console's) process id and use that to create a > > file somewhere. Not sure if this is even possible. > > You might be able to write a Python program to access it :-) > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline From bignose+hates-spam at benfinney.id.au Sun Sep 16 01:05:55 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 16 Sep 2007 15:05:55 +1000 Subject: Needless copying in iterations? References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> Message-ID: <874phv42to.fsf@benfinney.id.au> Steven D'Aprano writes: > In *general* the compiler can't tell, but in specific cases it > could. A (hypothetical) optimizing compiler would tell the > difference between: > > for item in alist[1:5]: > print item # no possible side-effects The 'print' statement converts the 'item' to a str. That conversion could, in a pathological case, have a side-effect (say, if the class of 'item' had an overridden '__str__' method with side effects), and the compiler can't know this isn't a pathological case. > for item in alist[1:5]: > alist.append(item) # side-effects DON'T matter The compiler doesn't know that, at the time of invocation, 'alist.append' doesn't have side effects that matter. The compiler for a dynamic language like Python has very little absolute "no significant side-effect in these specific cases" guarantee of the kind you're assuming even in the cases you choose for contrast with the ones that *do* have significant side-effects. -- \ "When we call others dogmatic, what we really object to is | `\ their holding dogmas that are different from our own." -- | _o__) Charles Issawi | Ben Finney From bj_666 at gmx.net Fri Sep 7 07:14:03 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2007 11:14:03 GMT Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <5kcq3rF31i6hU2@mid.uni-berlin.de> On Fri, 07 Sep 2007 10:40:47 +0000, Steven D'Aprano wrote: > Nor does it include "peek" and "poke" commands for reading and writing > into random memory locations. I guess `ctypes` offers tools to write `peek()` and `poke()`. :-) Ciao, Marc 'BlackJack' Rintsch From http Sat Sep 29 04:48:40 2007 From: http (Paul Rubin) Date: 29 Sep 2007 01:48:40 -0700 Subject: Python and SSL References: <1190959345.041723.108130@k79g2000hse.googlegroups.com> <46fd7e7b$0$18410$9b622d9e@news.freenet.de> <7x641u0zvl.fsf@ruckus.brouhaha.com> <46fdf708$0$2775$9b622d9e@news.freenet.de> Message-ID: <7xve9tvouv.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > Please try to understand that OP's question. He got some error, > and for some reason, he concluded that he needs to tell Python > to trust the server certificate (most likely to make the error > go away). I told him that he is likely wrong, and that Python already > trusts his server certificate. I was not proposing any judgment on > whether that's a good thing or not. In fact, I have no idea whether > security was of any concern to the OP. Oh, I see, I didn't interpret the question that way but it does fit and the answer is reasonable in that situation. From steve at REMOVE-THIS-cybersource.com.au Wed Sep 12 13:17:56 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 12 Sep 2007 17:17:56 -0000 Subject: Dynamically removing methods in new-style classes References: <1189607295.676704.215210@r34g2000hsd.googlegroups.com> Message-ID: <13eg7q4tbrksj36@corp.supernews.com> On Wed, 12 Sep 2007 14:28:15 +0000, agupta0318 wrote: > I am trying unsuccessfully to remove some methods from an instance, > based on values passed in to the constructor as in the following > example: [snip] >>> class C(object): ... def method(self): ... return "method exists" ... >>> c = C() >>> c.method() 'method exists' >>> del c.__class__.method >>> c.method() Traceback (most recent call last): File "", line 1, in AttributeError: 'C' object has no attribute 'method' Of course deleting methods from the class has the disadvantage that you delete them from the class. A better solution might be to mask them: >>> class C(object): ... def method(self): ... return "method exists" ... def methodgone(self, *args): ... raise AttributeError("method gone") ... >>> c = C() >>> d = C() >>> c.method = c.methodgone >>> c.method() Traceback (most recent call last): File "", line 1, in File "", line 5, in methodgone AttributeError: method gone >>> d.method() 'method exists' -- Steven. From bignose+hates-spam at benfinney.id.au Wed Sep 19 22:04:48 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 20 Sep 2007 12:04:48 +1000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <1i4lvsx.mhw5621jlsd53N%aleax@mac.com> <87r6kwzg1h.fsf@benfinney.id.au> <13f3j83lun4ckc5@corp.supernews.com> Message-ID: <87tzpqw0qn.fsf@benfinney.id.au> Scott David Daniels writes: > Ben Finney wrote: > > aleax at mac.com (Alex Martelli) writes: > > > >> In general, "a superclass of foo" means "a class X such that foo is a > >> sublass of X" > > > > Sure. However, this doesn't equate to the assertion that "next class > > in the MRO is the superclass", which is what I was responding to. > > > One thing not pointed out in this thread is that the chain of classes > on the MRO starting with super(A, obj) _will_ include all superclasses > of A. That is the guarantee of the MRO, and that is why super is an > appropriate name. Yes, it does include those classes. The problem is it also includes an unknown (to the implementation of A) number of classes that are *not* superclasses of A. Thus, 'super' is a *bad* name for such a function. -- \ "There are always those who think they know what is your | `\ responsibility better than you do." -- Ralph Waldo Emerson | _o__) | Ben Finney From deets at nospam.web.de Sat Sep 15 08:47:34 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 15 Sep 2007 14:47:34 +0200 Subject: python 2.5 cElementTree entity troubles Message-ID: <5l22jsF5taqoU1@mid.uni-berlin.de> Hi, this snippet, adapted from http://svn.effbot.org/public/tags/celementtree-1.0-20050126/selftest.py fails miserably with an unknown entity exception: from xml.etree.cElementTree import * ENTITY_XML = """ &entity; """ parser = XMLTreeBuilder() parser.entity["entity"] = "text" print parser.entity parser.feed(ENTITY_XML) root = parser.close() Any suggestions on how to teach the built-in ET-parser entities? Python version is Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) on OSX. Regards, Diez From usenet at solar-empire.de Thu Sep 27 11:33:03 2007 From: usenet at solar-empire.de (Marc Christiansen) Date: Thu, 27 Sep 2007 17:33:03 +0200 Subject: os.removedirs - How to force this delete? References: <1190904657.333070.45290@n39g2000hsh.googlegroups.com> Message-ID: cstewart913 at gmail.com wrote: > I've been searching to find a way to force this delete to work even if > the directory isn't empty. I've had no luck thus far. Anyone know > what that would be? Answering your immediate question: you can't force os.removedirs to delete non-empty dirs. But shutil.rmtree(path, ignore_errors=True) does what you want. HTH, Marc From cappy2112 at gmail.com Tue Sep 4 02:00:40 2007 From: cappy2112 at gmail.com (Cappy2112) Date: Tue, 04 Sep 2007 06:00:40 -0000 Subject: pyPortMidi Message-ID: <1188885640.409493.147160@w3g2000hsg.googlegroups.com> Does anyone here use pyPortMidi- in particular for Sending/receiving sysex? From tjreedy at udel.edu Fri Sep 14 02:42:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Sep 2007 02:42:03 -0400 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com><46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net><1189618530.872819.136450@57g2000hsv.googlegroups.com><1189619033.968437.286580@g4g2000hsf.googlegroups.com><5kr8vlF53m8gU3@mid.individual.net><1189643616.826715.58150@d55g2000hsg.googlegroups.com><5ksoaoF5am8cU1@mid.individual.net><1189701793.466307.93210@g4g2000hsf.googlegroups.com><5ktfjqF5ctrvU2@mid.individual.net><46e98fd8$0$27757$426a34cc@news.free.fr> <5ktre7F5ig0vU1@mid.individual.net> Message-ID: "Bjoern Schliessmann" wrote in message news:5ktre7F5ig0vU1 at mid.individual.net... |> - only functions being attributes of a class... |What, IYHO, is the difference between a method and a function? A method is a function accessed as an attribute of a class or instance. As an object type, it is a *runtime* function wrapper. |> (ok, I know, you meant "functions declared within a class> statement"). | I think that those functions _are_ special ones Thinking does not make things so. |since the compiler is able to make "method(instance, a, b)" out of |"instance.method(a, b)". No it does not. The method wrapping is done at runtine. The compiler is ignorant of the wrapping that will be done. >>> class C: def meth(self): pass >>> c = C() >>> import dis >>> def f(): return c.meth() >>> dis.dis(f) 1 0 LOAD_GLOBAL 0 (c) 3 LOAD_ATTR 1 (meth) 6 CALL_FUNCTION 0 9 RETURN_VALUE The function gets wrapped as a bound method as part of LOAD_ATTR. When the compiler sees (args), it does not know and does not care about the particular type that will become. It just assumes that it will be callable and emits the code to call it. Consider >>> def g(): return C() >>> dis.dis(g) 1 0 LOAD_GLOBAL 0 (C) 3 CALL_FUNCTION 0 6 RETURN_VALUE It does not notice and does not care that 'C' will be bound to a class. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Tue Sep 18 01:41:30 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 18 Sep 2007 15:41:30 +1000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <1i4lvsx.mhw5621jlsd53N%aleax@mac.com> Message-ID: <87r6kwzg1h.fsf@benfinney.id.au> aleax at mac.com (Alex Martelli) writes: > In general, "a superclass of foo" means "a class X such that foo is a > sublass of X" Sure. However, this doesn't equate to the assertion that "next class in the MRO is the superclass", which is what I was responding to. -- \ "Even if the voices in my head are not real, they have pretty | `\ good ideas." ?anonymous | _o__) | Ben Finney From paul.nospam at rudin.co.uk Sun Sep 16 14:25:22 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Sun, 16 Sep 2007 19:25:22 +0100 Subject: how to join array of integers? References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <13eos6ihf2mjg4a@corp.supernews.com> Message-ID: <87lkb6o4bx.fsf@rudin.co.uk> Steven D'Aprano writes: > On Sat, 15 Sep 2007 15:56:40 +0200, Arnau Sanchez wrote: > >> js escribi?: >> >>>> On 9/15/07, Summercool wrote: >> >>>> in Python... is the method to use ",".join() ? but then it must take >>>> a list of strings... not integers... >>>> >>>> any fast method? >> >> > print ''.join([str(i) for i in [1,2,3]]) >> >> It's better to use generator comprehension instead of LC: >> >> ",".join(str(i) for i in [1, 2, 3]) > > > Really? Why do you say that a generator expression is "better" than a > list comprehension? > > >>>> import timeit >>>> timeit.Timer("', '.join([str(i) for i in [1,2,3]])", "").repeat() > [5.0969390869140625, 4.5353701114654541, 4.5807528495788574] >>>> timeit.Timer("', '.join(str(i) for i in [1,2,3])", "").repeat() > [11.651727914810181, 10.635221004486084, 10.522483110427856] > > The generator expression takes about twice as long to run, and in my > opinion it is no more readable. So what's the advantage? If you do it with a decent size list they take more or less the same time. You'd presumably expect the generator to use less memory; which might be an advantage if you have large lists. Isn't it odd that the generator isn't faster, since the comprehension presumably builds a list first and then iterates over it, whereas the generator doesn't need to make a list? From nytrokiss at gmail.com Sat Sep 29 23:29:38 2007 From: nytrokiss at gmail.com (James Matthews) Date: Sat, 29 Sep 2007 20:29:38 -0700 Subject: HOT!!!PYTHON DEVELOPER REQUIRED @ ADOBE SYSTEMS In-Reply-To: <1190916344.841925.94900@57g2000hsv.googlegroups.com> References: <1190916344.841925.94900@57g2000hsv.googlegroups.com> Message-ID: <8a6b8e350709292029u7944e9a7x5b6af461f4129369@mail.gmail.com> Spam! On 9/27/07, Recruiter-Adobe wrote: > > Hi PYTHON DEVELOPERS, > > ADOBE SYSTEMS is looking for a PYTHON DEVELOPER who can troubleshoot > Python based applet which makes data base queries and populates Excel > tables used to generate pivot charts, graphs and tables showing bug > metrics. Isolate problem which is causing reports to crash and > institute fix. > > This is a position through Manpower at our customer Adobe Systems, > you will be employed as a Manpower's contractor. > > Job Responsibilities: > > ? Setup a new server (development environment) > > ? Install updated versions of both python and other plugins > used for our applet. > > ? Import Code/applet instance. > > ? Remove code that uploads it to the Production Server > Instance > > ? Eventually move the entire Production Instance over to the > newer server. > > ? Update Code to comply with the latest Python standards > > Knowledge & Skills: > > ? Expert in Python Programming > > ? Experience in COM Object programming speficially Excel COM > Objects > > ? Experience in using WebServices (SOAP) > > ? Win2k System Administration Experience a Plus > > ? Need to migrate from version 2.3 to latest version of Python > > Hourly Pay rate: $85-$100/hr > > If interested, please send a Word copy of your resumeto > rbadame at manpowersj.com with your expected hourly rate, availability, > visa status, best time and phone # to contact you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/mens/cufflinks.html http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Fri Sep 21 10:53:37 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 21 Sep 2007 16:53:37 +0200 Subject: Calling constructor but not initializer References: <13f7kmfhe19lb7b@corp.supernews.com> Message-ID: <87tzpocbny.fsf@mulj.homelinux.net> Steven D'Aprano writes: > I can construct an empty instance in the __new__ constructor, and I > can initialize an non-empty instance in the __init__ initializer, > but I can't think of any good way to stop __init__ from being called > if the instance is empty. In pseudo-code, I want to do something > like this: > > class Parrot(object): > def __new__(cls, data): > construct a new empty instance > if data is None: > return that empty instance > else: > call __init__ on the instance to populate it > return the non-empty instance Suggestion 1: since you "construct a new empty instance" in both cases, simply move the entire logic to __init__. Suggestion 2: name your initialization method something other than __init__ and the calling-type-object-automatically-calls-__init__-after-__new__ simply disappears. Can you specify the way you'd like to instantiate the class? From stefan.behnel-n05pAM at web.de Thu Sep 27 13:46:08 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 27 Sep 2007 19:46:08 +0200 Subject: How do I get the value out of a DOM Element In-Reply-To: <1190906039.259425.312640@50g2000hsm.googlegroups.com> References: <1190872252.204687.286640@19g2000hsx.googlegroups.com> <46FB5B8E.8050100@web.de> <1190906039.259425.312640@50g2000hsm.googlegroups.com> Message-ID: <46FBEC60.3030904@web.de> kj7ny wrote: > Forgot to mention I'm using Python 2.4.3. You can install both lxml and ET on Python 2.4 (and 2.3). It's just that ET went into the stdlib from 2.5 on. Stefan From bignose+hates-spam at benfinney.id.au Sun Sep 30 21:48:02 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 01 Oct 2007 11:48:02 +1000 Subject: Using fractions instead of floats References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> Message-ID: <87ir5rzju5.fsf@benfinney.id.au> andresj writes: > The problem arises when you try to represent some number, like 0.4 in > a float. Which is really a specific case of the general problem that, for any given number base, some non-integer numbers cannot be exactly represented as fractions. > Secondly, what happens if I need to sum 1/3 and 0.4? I could use > Decimal to represent 0.4 precisely, but what about 1/3? What about the sum of ? (pi) and ?2 (sqrt(2))? > So the solution I think is using a fraction type/class As explained above, a fractional-number class only shifts the "exact representation" problem, it doesn't solve it. -- \ "Facts do not cease to exist because they are ignored." -- | `\ Aldous Huxley | _o__) | Ben Finney From jgardner.jonathangardner.net at gmail.com Thu Sep 13 15:57:22 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Thu, 13 Sep 2007 19:57:22 -0000 Subject: Python Database Apps In-Reply-To: References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> Message-ID: <1189713442.091878.41910@g4g2000hsf.googlegroups.com> On Sep 11, 5:56 am, Harry George wrote: > I use postgresql as well. I wonder if Pythonistas do so out of > concern for rigor, clarity, and scalability. It works fine for a > quick one-off effort and still works fine after scaling to a DBMS > server supporting lots of clients, and running 10's of GBs of data. > I can only speak for myself, but I use it for the reasons you listed. I also appreciate the concise and clear documentation, the helpfulness of the community, and the clarity of the code. It's also pretty easy to get back into PostgreSQL after leaving it for years. There's not too many weird details you have to remember to get your job done. > Of course, as long as you write DBI2 compliant code, your app doesn't > much care which DBMS you use. The postgresql payoff is in admin > functionality and scaling and full ACID. > It's not true that DBI2 compliance meands plug-and-play. Among the various databases, the featuresets are different, and the way certain features are implemented is different. You need something like SQLAlchemy on top to make it truly portable. From arnodel at googlemail.com Sun Sep 9 10:09:39 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 09 Sep 2007 07:09:39 -0700 Subject: unexpected behavior: did i create a pointer? In-Reply-To: <13e7rhtqelbcb54@corp.supernews.com> References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <13e2jdobu2kqkf1@corp.supernews.com> <13e4rno5qal6h4b@corp.supernews.com> <1189330200.935267.107970@19g2000hsx.googlegroups.com> <13e7rhtqelbcb54@corp.supernews.com> Message-ID: <1189346979.198156.115170@g4g2000hsf.googlegroups.com> On Sep 9, 1:59 pm, Steven D'Aprano wrote: > On Sun, 09 Sep 2007 02:30:00 -0700, Arnaud Delobelle wrote: > >> You know, maybe because I came to Python with no C experience, I never > >> had trouble with the "unexpected behaviour" that so confused the > >> original poster. It's just obvious. > > > The funny thing is that if the OP had thought of both 'a' and 'copyOfA' > > as C-like pointers then he wouldn't have been confused :) > > You're almost certainly wrong. He would have written to ask why this > doesn't do what he expects: > > >>> x = 3 > >>> y = x # x and y are both pointers to the same value > >>> x += 1 This means that x now points to the value of x + 1, i.e. an int object with value 4. > >>> print x == y # of course, they are pointers to the same value Of course not, now x points to 4 and y points to 3 ! > False > > Or why lower_list() works as expected, but lower_string() doesn't: > > >>> def lower_list(L): > > ... for i, x in enumerate(L): > ... L[i] = x.lower() > ...>>> s = ['STRING'] > >>> lower_list(s) > >>> print s == ['string'] > True > > >>> def lower_string(s): > > ... s = s.lower() > ...>>> s = "STRING" > >>> lower_string(s) Let's see what happens here: when lower_string(s) is called, the 's' which is local to lower_string is made to point to the same object as the global s (i.e. the string object with value "STRING"). In the body of the function, the statement s=s.lower() makes the local 's' point to a new string object returned s.lower(). Of course this has not effect on what object the global 's' points to. > >>> print s == "string" Obviously not, since s still points to the string object with value "STRING" > False > > The "names in Python are pointers" analogy only gives you the right > answer half the time. They give *you* the right answer only half the time ;) They give me the right answer all the time. Not that I usually think of names as pointers. But if I choose to do so, I can still get it right. And if it works for me consistently, there must be some validity in it, no? What I think is a more dangerous misconception is to think that the assignement operator (=) has the same meaning in C and python. -- Arnaud From wizzardx at gmail.com Sat Sep 8 17:44:10 2007 From: wizzardx at gmail.com (David) Date: Sat, 8 Sep 2007 23:44:10 +0200 Subject: Spell-checking Python source code In-Reply-To: <46E314FD.7030200@bigfoot.com> References: <1189285495.185657.88010@o80g2000hse.googlegroups.com> <46E314FD.7030200@bigfoot.com> Message-ID: <18c1e6480709081444x69c4d23cx65f7c9b62eda8271@mail.gmail.com> > > > > (I know that the better practice is to isolate user-displayed strings > > from the code, but in this case that just didn't happen.) > > > > Use the re module, identify the strings and write them to another file, > then open the file with your spell checker. Program shouldn't be more > than 10 lines. > > Have a look at the tokenize python module for the regular expressions for extracting strings (for all possible Python string formats). On a Debian box you can find it here: /usr/lib/python2.4/tokenize.py It would probably be simpler to hack a copy of that script so it writes all the strings in your source to a text file, which you then spellcheck. Another method would be to log all the strings your web app writes, to a text file, then run through your entire site, and then spellcheck your logfile. From mridula.ccpl at gmail.com Wed Sep 26 05:58:16 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Wed, 26 Sep 2007 15:28:16 +0530 Subject: frame refresh or redraw for records? Message-ID: <33dffc910709260258h4bdb24aeifa6a6b218f0aac0b@mail.gmail.com> hi. my actual code is a bit too long to post here, but this is how the code works : the application loads, the first screen appears. it is to view the records in a database, so you can scroll and view records by clicking on the standard navigation buttons ( |<, <<, >>, >| ). the problem is that since all my navigation code is in one class, and the display class is called from class navigation() to make frame and the buttons, the frame and buttons are reloaded afresh each time. this means that if the text fields' lengths vary, the frame messily tends to move around to accommodate them. 1. is it wrong (ie. inefficient/ slower/ BAD pgming practice!) to reload the frame and its children widgets every time? 2. is there a way to clear the frame of the child widgets? - this would solve the problem of the Jumping Buttons! frame.destroy() seems to be crashing my whole application. is there another way? is it possible to make a function so that every time the main values change, a series of events is triggered? i'm sorry, i've searched quite a bit for this frame business, and so far it's either not worked/ been incomprehensible! thank you for your patience - mridula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sat Sep 15 00:15:59 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 14 Sep 2007 23:15:59 -0500 Subject: [Tutor] Is there some sort of Python Error log. In-Reply-To: References: Message-ID: <46EB5C7F.2070901@gmail.com> Lamonte Harris wrote: > Command prompt is a pain and it would be pretty nice to have this feature. If you're on windows, try using an IDE for your code editing. Then the errors will show up in the interactive shell that the IDE runs, and you won't have to deal with starting a DOS command prompt to catch your errors. -Luke From tismer at stackless.com Mon Sep 3 20:19:47 2007 From: tismer at stackless.com (Christian Tismer) Date: Tue, 04 Sep 2007 02:19:47 +0200 Subject: [Crew] Four Years of Starship hosting come to an end In-Reply-To: <46DC1042.5020906@drees.name> References: <46DC1042.5020906@drees.name> Message-ID: <46DCA4A3.8060404@stackless.com> Stefan Drees wrote: > Dear Crew of the Python Starship, > > after a short email exchange of thoughts with Christian Tismer, that he > might take over again the hosting of the ship or silently give over some > of its remains to a museum, he encouraged me, to let go after four years > of hosting, so that I can get a grip on new stuff. Yes, Stefan! You hosted the ship, you payed the bills, and you got all the little to nothing feed-backs from the Starship crew that really made you into continuing your job. I am very fond of you. We could go for some real task, now. > Remember? Back in those days, when hosting providers did not offer > python environements but html or perl or php or sh cgi's ... Chris > 'Pirx' Tismer founded the Starship, by spreading the idea that > Pythonistas should buy planks, and he then would assemble a ship - what > would become "our" ship This is almost 10 years ago, and I do remember very well. The Starship had its role, and this was very explicitly stated at one of the ancient PyCon events, when Guido stated that I had not enough resources to support the Starship well enough. Meanwhile, the world has changed quite a lot, and starship's role might have diminished or redefined. > I am convinced, that Chris will be interested, if there is still a need > for the ship and what kind of exact need there is. Yes. If there is a wish to continue Starship, then we can do this. I have a new server with a XEN site set up, ready for you. I also can toss it. It is not me who needs Starship, I'm asking you. > On October, 1st of this year 2007, whatever makes out "the ship" will > have been transferred to another location or just vanish into space. I will at least take the archives, and consider how to carry on, dependent from the community's response. > It has been a real pleisure for me to serve this community with hosting > the ship! It has been great to experience your support! We can now try something completely different. Please let us know your opinions. p.s.: this is the only time I'll be cross-posting to python-list. -- Christian Tismer :^) tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From walterbyrd at iname.com Tue Sep 18 13:44:28 2007 From: walterbyrd at iname.com (walterbyrd) Date: Tue, 18 Sep 2007 10:44:28 -0700 Subject: What's with "long running processes" ? Message-ID: <1190137468.694220.126180@d55g2000hsg.googlegroups.com> I understand that Python has them, but PHP doesn't. I think that is because mod_php is built into apache, but mod_python is not usually in apache. If mod_python was built into apache, would python still have long running processes (LRP)? Do LRPs have to do with a Python interpreter running all the time? Or is it something else? I also understand that LRPs are the reason that shared hosting is less common, and more expensive for python than php. The LRP have a major effect on how many users can packed onto a single server. As to LRPs: does it matter if you're using mod_python, fastcgi, wsgi, scgi, cgi, or whatever? Obviously, I am a little foggy about LRPs, can somebody help me out? From steven.bethard at gmail.com Mon Sep 24 15:09:43 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Sep 2007 13:09:43 -0600 Subject: Passing parameters at the command line (New Python User) In-Reply-To: <1190621098.582906.49760@r29g2000hsg.googlegroups.com> References: <1190621098.582906.49760@r29g2000hsg.googlegroups.com> Message-ID: cjt22 at bath.ac.uk wrote: > Hi there. I just wondered whether anyone could recommend the correct > way I should be passing command line parameters into my program. I am > currently using the following code: > > def main(argv = None): > > > file1= "directory1" > file2 = "directory2" > > > if argv is None: > args = sys.argv[1:] > > if len(args) == 0: > Initialise.init(0) > Process.processCon(file1, 0) > Output.print() > > for i in range(len(args)): > if args[i] == "-no": > Initialise.init(0) > Process.processCon(file2,1) > Output.print() > > if args[i] == "-not": > Initialise.init(1) > Process1.process(stepStore, firstSteps) > Output.print1() > > > > if __name__ == "__main__": > main() > > > Have I used bad syntax here so that a user can either run the program > with commands: > main.py > main.py -no > main.py -not > > If I also wanted an option file to be passed in at the command line > for 'main.py' and 'main.py -no' what would be the best way to go about > this? I have never used Python to pass in arguments at the command > line so any help would be much appreciated. A solution using argparse (http://argparse.python-hosting.com/): import argparse def main(no=False, nott=False): file1 = "directory1" file2 = "directory2" if nott: print 'Initialise.init(1)' print 'Process1.process(stepStore, firstSteps)' print 'Output.print1()' else: print 'Initialise.init(0)' if no: print 'Process.processCon(file2, 1)' else: print 'Process.processCon(file1, 0)' print 'Output.print()' if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-no', action='store_true') parser.add_argument('-not', action='store_true', dest='nott') args = parser.parse_args() main(no=args.no, nott=args.nott) Note that I've used print statements since I don't have your Initialize, Process, etc. objects. If I knew what "-no" and "-not" meant better, I could give you a better suggestion, e.g. where you parse the 0 or 1 value for Initialize.init directly from the command line. STeVe From gagsl-py2 at yahoo.com.ar Thu Sep 27 00:41:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Sep 2007 01:41:17 -0300 Subject: scope, modyfing outside object from inside the method References: Message-ID: En Wed, 26 Sep 2007 10:39:22 -0300, Marcin St?pnicki escribi?: > At first glance (before adding id()) it's a little bit weird. The > original > object was supposedly "overwritten", but as one can see it has different > id then the new one. mystruct still holds references to old object, > though. I can handle it and just change original object, but I'm curious > if there's a way to "swap" them "on-the-fly". You should read this -- Gabriel Genellina From fabioztessitore at libero.it Mon Sep 3 11:46:49 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 03 Sep 2007 15:46:49 GMT Subject: Problem with extremely small real number References: <1188831370.133673.205230@r29g2000hsg.googlegroups.com> Message-ID: <46dc2c69$0$10623$4fafbaef@reader2.news.tin.it> Il Mon, 03 Sep 2007 07:56:10 -0700, Andrea ha scritto: > [cut] > > I want to call factorial(2)//binomial(1024,2) for example, in this way > trivially I obtain 0 as probability, how can I obtain the probability > forcing this division to output extremely small real numbers???? int to float will help print float(factorial(2))/binomial(1024,2) bye From geoffness8 at gmail.com Mon Sep 17 06:38:16 2007 From: geoffness8 at gmail.com (geoff_ness) Date: Mon, 17 Sep 2007 10:38:16 -0000 Subject: UnicodeEncodeError in Windows Message-ID: <1190025496.308969.51400@n39g2000hsh.googlegroups.com> Hello - and apologies in advance for the length of this post. I am having a hard time understanding the errors being generated by a program I've written. The code is intended to parse text files which are copied and pasted from web pages from an online game. The encoding of the pages is ISO-8859-1, but the text that gets copied contains characters from character sets other than latin-1. For instance, one of the lines I need to be able to read is: 196679 Daimyo ? Druid 145 27 12/09/07 21:40:04 [ Expel ] I start with the file 'citizen_list' and use this function to read it and return a list of names (for instance, Daimyo ? Druid) and ID numbers: # builds the list of names from the citizens list def getNames(f): """Builds a list from the town list of names Returns a list""" newlist = [] for line in f: namewords = line.rstrip('[Expel]\n\t ')\ .rstrip(':/0123456789 ').rstrip('\t ').rstrip('0123456789 ')\ .rstrip('\t ').rstrip('0123456789 ').rstrip('\t ').split() entry = ";".join([namewords[0], " ".join(namewords[1:len(namewords)])]) newlist.append(entry) return newlist citizens = codecs.open('citizen_list', 'r', 'utf-8', 'strict') listNames = getNames(citizens) citizens.close() I've specified 'utf-8' as the encoding as this seemed to be the best candidate for picking up all the names in the list. I use the names in other functions - for example: def getdamage(warrior, rpt): """reads each line of war report returns damage and number of kills for citizen name""" for line in rpt: if (line.startswith(warrior.name) or \ line.startswith('A blue aura surrounds ' + warrior.name))\ and line.find('weapon') > 0: warrior.addDamage(int(line[line.find('caused ') +7:line.find(' damage')])) if rpt.next().find('is dead') >0: warrior.addKill() elif line.startswith(warrior.name+' is dead'): warrior.dies() break elif line.startswith('Starting round'): warrior.addRound() for cit in listNames: c = Warrior(cit.split(';')[0], cit.split(';')[1]) totalnum += 1 report = codecs.open('war_report','r', 'utf-8', 'strict') getdamage(c, report) report.close() --[snip]-- def buildString(warrior): """Build a string from a warrior's stats Returns string for output to warStat.""" return "!tr!!td!!id!"+str(warrior.ID)+"!/id!!/td!"+\ "!td!"+str(warrior.damage)+"!/td!!td!"+str(warrior.kills)+\ "!/td!!td!"+str(warrior.survived)+"!/td!!/tr!" This code runs fine on my linux machine, but when I sent the code to a friend with python running on windows, he got the following error: Traceback (most recent call last): File "D:\Python25\Lib\SITE-P~1\PYTHON~1\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in _main_._dict_ File "C:\Documents and Settings\Administrator\Desktop \reparser_014(2)\parser_1.0.py", line 63, in "".join(["%s" % buildString(c) for c in citlistS[:100]])+"!/ table!") File "C:\Documents and Settings\Administrator\Desktop \reparser_014(2)\iotp_alt2.py", line 169, in buildString "!/td!!td!"+str(warrior.survived)+"!/td!!/tr!" UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 0: ordinal not in range(128) As I understand it the error is related to the ascii codec being unable to cope with the unicode string u'\ufeff'. The issue I have is that this error doesn't show up for me - ascii is the default encoding for me also. Any thoughts or assistance would be welcomed. Cheers From xkenneth at gmail.com Sat Sep 8 15:42:19 2007 From: xkenneth at gmail.com (xkenneth) Date: Sat, 08 Sep 2007 12:42:19 -0700 Subject: Organizing Code - Packages In-Reply-To: <46e1a0bc$0$7689$9b4e6d93@newsspool2.arcor-online.net> References: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> <46e17143$0$6189$426a74cc@news.free.fr> <1189183088.922537.18290@r34g2000hsd.googlegroups.com> <87r6laa0ir.fsf@rudin.co.uk> <46e1a0bc$0$7689$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1189280539.449868.169910@22g2000hsm.googlegroups.com> On Sep 7, 2:04 pm, Wildemar Wildenburger wrote: > Paul Rudin wrote: > > xkenneth writes: > > >>> Ah, yes, a couple of things: > >>> - avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens > >> Yes but i find it hard to edit classes easily when I have more than > >> one class per file. > > > Why? > > Scroll-Blindness would be a good reason. > > It would however be completely rediculous to create a file for every > 10-liner class you have (and I have found that Python classes tend to be > rather short). > > / Yes I agree, "Scroll-Blindness" it just gets long and confusing. Navigating isn't so bad (emacs) here. I have another question for something I don't quite understand. How do import statements that are declared at the top of a python module work? for instance.... from MyModule.Objects import * class Class: def function: #here i cannot access the things that should have been imported from the above statement #i printed the dir() function to verify this This happens when I'm using the Class i just defined from another python script. I can understand if that statement at the top if not being executed when I import the above defined class, if so, I need to access the classes from the other modules, so where do I put the import statement? Is it proper to put import statements inside of class function definitions? This solves my problem but seems VERY incorrect coming from my old C/C++ ways. Thanks Again! Regards, Ken From paul at boddie.org.uk Thu Sep 27 04:27:58 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 27 Sep 2007 01:27:58 -0700 Subject: How do I get the value out of a DOM Element In-Reply-To: <1190872252.204687.286640@19g2000hsx.googlegroups.com> References: <1190872252.204687.286640@19g2000hsx.googlegroups.com> Message-ID: <1190881678.362175.211980@g4g2000hsf.googlegroups.com> On 27 Sep, 07:50, kj7ny wrote: > I have been able to get xml.dom.minidom.parse('somefile.xml') and then > dom.getElementsByTagName('LLobjectID') to work to the point where I > get something like: [] which I > can get down to but then I > can't find any way to just get the value out from the thing! > > .toxml() returns something like: u' LLobjectID>'. > > How do I just get the 1871203 out of the DOM Element? DOM Level 3 provides the textContent property: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-textContent You'll find this in libxml2dom and possibly some other packages such as pxdom. For the above case with minidom specifically (at least with versions I've used), you need to iterate over the childNodes of the element, obtaining the nodeValue for each node and joining them together. Something like this might do it: "".join([n.nodeValue for n in element.childNodes]) It's not pretty, but encapsulating stuff like this is what functions are good for. Paul From Shawn at Milochik.com Tue Sep 11 20:31:06 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 11 Sep 2007 20:31:06 -0400 Subject: Difference between two times (working ugly code, needs polish) In-Reply-To: References: <13ee01cfc7f4be2@corp.supernews.com> <2dc0c81b0709111420r453ac15av6c7aa19473785080@mail.gmail.com> Message-ID: <2dc0c81b0709111731t3063d10cr60127c973a2a30b4@mail.gmail.com> > > I suppose really oneDay should be a global (i.e. outside the function > definition). Apart from that it would be hard to improve on: obvious, > easy to read, in short - pythonic. > > Are you concerned about daylight savings? That could certainly introduce > a whole new level of complexity into the problem. Let's hope not ... I'm not concerned with DST; this is a script which checks my Ebay auctions (I have some things for sale), and sends me e-mail whenever someone bids. It's run by cron every half hour -- it keeps me from compulsively checking my auctions. ^_^ In any case, DST isn't an issue because the same machine generates both timestamps, and all I use it for is to stop displaying auctions after they are 10 days old, so I don't get all my old crap filling up the alert e-mail or skewing the total dollar amount for all active auctions. Thanks. Shawn From kyosohma at gmail.com Tue Sep 11 09:26:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 11 Sep 2007 13:26:04 -0000 Subject: newbie: stani's python editor if-else In-Reply-To: <1189484688.520933.25000@22g2000hsm.googlegroups.com> References: <1189484688.520933.25000@22g2000hsm.googlegroups.com> Message-ID: <1189517164.302630.307850@w3g2000hsg.googlegroups.com> On Sep 10, 11:24 pm, madzientist wrote: > hi, > > two quick questions: > > a) i am using SPE (latest version) and for some reason, when i type, > say > > if 1==2: > print "not equal" > else: > print "equal" > > the else is at the same indentation level as the preceding print > statement, and i get a syntax error > > why doesn't spe automatically put the else at the level of the if > statement ? what am i dong wrong ? once i manually change the > indentation, the code snippet runs perfectly. > > b) if this is not the group for such elementary questions, please do > let me know. > > thanks !!!! > > suresh I agree with Steve. I have yet to see an IDE for Python (or anything else) that unindents statements. Even IDLE, the Official IDE for Python, doesn't do that. Mike From lasses_weil at klapptsowieso.net Sun Sep 2 15:07:13 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 02 Sep 2007 21:07:13 +0200 Subject: Glade + Python = No GUI In-Reply-To: <1188750465.530463.271750@22g2000hsm.googlegroups.com> References: <1188750465.530463.271750@22g2000hsm.googlegroups.com> Message-ID: <46db09e1$0$7697$9b4e6d93@newsspool2.arcor-online.net> Kveldulv wrote: > When interrupted, I get > > File "gui.py", line 11, in > gtk.main() > Ah, I see now. Thats just telling you that *you* interrupted the function/method/whateverthatis. > When GUI coded manually, all works. > Hence: Something in your (generated) code or XML file is corrupt or missing. Perhaps some sort of show() call or attribute. I really only have marginal experience with pygtk so I'm just stabbing at thin air. sorry :( /W From grante at visi.com Wed Sep 12 11:18:37 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 12 Sep 2007 15:18:37 -0000 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> Message-ID: <13eg0qd93d90e1a@corp.supernews.com> On 2007-09-12, Tim Golden wrote: > I think it's one of those things which comes down, fairly > enough, to: we do things this way and it works for us; other > languages do other things and it works for them. But not as nearly well as our way works for us, of course. ;) -- Grant Edwards grante Yow! I'm meditating on at the FORMALDEHYDE and the visi.com ASBESTOS leaking into my PERSONAL SPACE!! From kivilaya at 163.com Fri Sep 28 23:12:25 2007 From: kivilaya at 163.com (kivilaya) Date: Fri, 28 Sep 2007 20:12:25 -0700 Subject: How to display a videostream in the PyQt GUI by a efficient way Message-ID: <1191035545.816512.171410@g4g2000hsf.googlegroups.com> Hello, everyone? : ) I'm a beginner of pyqt, and recently I'm having a problem with it. I hope someone could help me. As required, I need to get a videostream from a camera, and process every frame to add some information on it, and then display the frame in a PyQt GUI. But I don't know how to display the videostream in the PyQt GUI by a efficient way. Currently, I do these like this: 1. Get the videostream by the videocapture module (a useful module written by Markus Gritsch) in the format of PIL images; 2. Process every PIL image and add the information; 3. Convert every PIL image to QPixmap and display it using QLabel.setPixmap. I think it is a very inefficient way, but I don't known how to display the videostream in other ways, so I need your help, Thanks! PS:I do it with Windows XP, Python 2.5.1, PyQt4.3.0 From gherzig at fmed.uba.ar Mon Sep 3 09:28:02 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 03 Sep 2007 10:28:02 -0300 Subject: How does super() work? In-Reply-To: References: Message-ID: <46DC0BE2.5000901@fmed.uba.ar> Lamonte Harris wrote: >I've searched Google, and other search engines to try to find out how >super() works. Can someone explain in short detail how super() works? I >may and may not need to know this information, but it is good to know. > > > There is at least one explanation in the python.org site, among other topics related to super() usage: http://www.python.org/download/releases/2.2.3/descrintro/#cooperation Cheers, Gerardo From mail at microcorp.co.za Sat Sep 1 02:40:26 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 1 Sep 2007 08:40:26 +0200 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com><1188497498.3468.60.camel@dot.uniqsys.com><0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> Message-ID: <005201c7ec62$fb267460$03000080@hendrik> "Paddy" wrote: > > I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll > and role similarly. > > My accent is probably from the East Midlands of the UK, but is not > pronounced. Same here - when the Troll lives under a bridge - I could not think of something to rhyme with it - frolic is just right. - Hendrik From kyosohma at gmail.com Wed Sep 26 17:04:42 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 26 Sep 2007 21:04:42 -0000 Subject: setuptools without unexpected downloads In-Reply-To: References: <87ejgmklep.fsf@benfinney.id.au><5lumarFae888U1@mid.uni-berlin.de> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> <5luv0iFaai82U1@mid.uni-berlin.de> <1190808836.056298.232640@57g2000hsv.googlegroups.com> Message-ID: <1190840682.716950.131830@r29g2000hsg.googlegroups.com> On Sep 26, 8:30 am, Steve Holden wrote: > Fredrik Lundh wrote: > > Paul Boddie wrote: > > >> P.S. Of course, the package maintainer problem manifests itself most > >> prominently on Windows where you often see people asking for pre-built > >> packages or installers. > > > for the record, I'd love to see a group of volunteers doing stuff like > > this for Windows. there are plenty of volunteers that cover all major > > Linux/*BSD distributions (tons of thanks to everyone involved in this!), > > but as far as I can remember, nobody has ever volunteered to do the same > > for Windows. > > I'd like to see something like this happen, too, and if a group of > volunteers emerges I'll do what I can through the PSF to provide > resources. Activities that benefit the whole community (or a large part > of it) are, IMHO, well worth supporting. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline What would it entail to do this? Using py2exe + some installer (like Inno Setup) to create an installer that basically copies/installs the files into the site-packages folder or wherever the user chooses? If that's all it is, I would think it would be fairly easy to create these. Maybe I'm over-simplifying it though. What are a some examples of packages that need this? Mike From paddy3118 at googlemail.com Sat Sep 1 03:17:46 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 01 Sep 2007 07:17:46 -0000 Subject: Way off topic In-Reply-To: References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188551958.728836.137370@x35g2000prf.googlegroups.com> Message-ID: <1188631066.050222.69840@22g2000hsm.googlegroups.com> On Sep 1, 7:40 am, "Hendrik van Rooyen" wrote: > "Paddy" wrote: > > > I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll > > and role similarly. > > Same here - when the Troll lives under a bridge - I could not think > of something to rhyme with it - frolic is just right. > > - Hendrik Yep, they would have posted about it way-back if they had the tech... http://uk.youtube.com/watch?v=zZ3fjQa5Hls (Gershwin doesn't seem to have a line about troll though :-) - Paddy. From pablo at decode.com.ar Sat Sep 29 13:55:53 2007 From: pablo at decode.com.ar (Pablo Ziliani) Date: Sat, 29 Sep 2007 14:55:53 -0300 Subject: Program inefficiency? In-Reply-To: <1191087234.915654.182370@k79g2000hse.googlegroups.com> References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> <1191087234.915654.182370@k79g2000hse.googlegroups.com> Message-ID: <46FE91A9.1080904@decode.com.ar> thebjorn wrote: > On Sep 29, 5:22 pm, hall.j... at gmail.com wrote: > >> I wrote the following simple program to loop through our help files >> and fix some errors (in case you can't see the subtle RE search that's >> happening, we're replacing spaces in bookmarks with _'s) >> (...) >> > > Ugh, that was entirely too many regexps for my taste :-) > > How about something like: > > def attr_ndx_iter(txt, attribute): > (...) > def substr_map(txt, indices, fn): > (...) > def transform(s): > (...) > def zap_spaces(txt, *attributes): > (...) > def mass_replace(): > (...) Oh yeah, now it's clear as mud. I do think that the whole program shouldn't take more than 10 lines of code using one sensible regex (impossible to define without knowing the real input and output formats). And (sorry to tell) I'm convinced this is a problem for regexes, in spite of anybody's personal taste. Pablo From Shawn at Milochik.com Tue Sep 11 17:20:36 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 11 Sep 2007 17:20:36 -0400 Subject: Difference between two times (working ugly code, needs polish) In-Reply-To: <13ee01cfc7f4be2@corp.supernews.com> References: <13ee01cfc7f4be2@corp.supernews.com> Message-ID: <2dc0c81b0709111420r453ac15av6c7aa19473785080@mail.gmail.com> On 9/11/07, Grant Edwards wrote: > On 2007-09-11, Shawn Milochik wrote: > > > I have done what I wanted, but I think there must be a much better way. > > See the strptime() function in either the time or the datetime > modules: > > http://docs.python.org/lib/module-time.html > http://docs.python.org/lib/module-datetime.html > Grant: Thanks, this works, and is much shorter. Any further improvements, anyone? def isOld(lastUpdate, runTimeStamp): oneDay = 60 * 60 * 24 lastUpdate = time.mktime(time.strptime(lastUpdate, "%Y-%m-%d_%H:%M")) runTimeStamp = time.mktime(time.strptime(runTimeStamp, "%Y-%m-%d_%H:%M")) return (runTimeStamp - lastUpdate) / oneDay From paddy3118 at googlemail.com Thu Sep 13 15:38:07 2007 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 13 Sep 2007 19:38:07 -0000 Subject: Coming from Perl In-Reply-To: References: Message-ID: <1189712287.671352.72940@w3g2000hsg.googlegroups.com> On Sep 13, 1:30 am, Amer Neely wrote: > I'm a complete newbie with Python, but have several years experience > with Perl in a web environment. > > A question I have, if someone here is familiar with Perl, does Python > have something like Perl's 'here document'? I've just searched and read > some postings on generating HTML but they all seem to refer to various > template utilities. Is this the only way, or am I missing something? I'm > used to generating X/HTML by hand, which makes the here document in Perl > ideal for me. Also, many times a client already existing HTML code that > I can use in a script. > > -- > Amer Neely > w:www.webmechanic.softouch.on.ca/ > Perl | MySQL programming for all data entry forms. > "Others make web sites. We make web sites work!" Hi Amer, Just as an aside, you might find this helpful: http://wiki.python.org/moin/PerlPhrasebook It has perl code with python equivalents/notes. - Paddy. From kivilaya at 163.com Sun Sep 30 03:10:40 2007 From: kivilaya at 163.com (kivilaya) Date: Sun, 30 Sep 2007 00:10:40 -0700 Subject: How to display a videostream in the PyQt GUI by a efficient way In-Reply-To: References: Message-ID: <1191136240.057573.254230@w3g2000hsg.googlegroups.com> Hi, David, thank you for your help! ^__^ I read the method in the given link and learn a lot from it. I'll try to display the data inside a QWidget directly instead of the current way. But I still have a question, is there any way to make the displaying of RGB data in a QWidget more quickly. In fact, my work is to make a gui for displaying my partners'experimental results to our teacher, the source video is no need to be encoded to mpeg or h264 format, so I get the video from camera in the raw format and display them without encodeing or decoding process. As my partners will do some experiments on the raw data, maybe add a mark to label some area in the current frame, or change some part of it, I get every frame as a picture before they process the picture data, and then display the picture after their process. But displaying the pictures one by one in my current way is so slow, I'm afraid that time spend on it is too long and the displaying of results will be discontinuous. So I think maybe there is another way to show these pictures. Look forward to more advices.^ ^ Thanks! Kivilaya From michele.simionato at gmail.com Wed Sep 5 08:56:30 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 05 Sep 2007 12:56:30 -0000 Subject: Multi Heritage with slots In-Reply-To: References: <1188982916.071976.160170@g4g2000hsf.googlegroups.com> <1188994956.570845.269250@w3g2000hsg.googlegroups.com> Message-ID: <1188996990.810829.122910@w3g2000hsg.googlegroups.com> On Sep 5, 2:52 pm, "Simon Brunning" wrote: > On 9/5/07, Alexandre Badez wrote: > > > I use __slots__ not for memory optimization nor doing java. > > I use __slots__ because my class are used by other lib, and in the > > past, some of them misspell some attributes and involved a very > > annoying comportment of the global application. > > So the objective is only to prevent unwanted dynamism (but not in all > > the application, just some class). > > Using slots to prevent the creation of new properties is what Eric > *means* by "doing java". You're trying to write Java style code in > Python, and it's not going to be pretty. Slots are not intended for > this purpose, and they aren't very good for it. > Right, and this the way to do what the original poster wants: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 Michele Simionato From Michael.Coll-Barth at VerizonWireless.com Sat Sep 29 12:07:52 2007 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Sat, 29 Sep 2007 12:07:52 -0400 Subject: Program inefficiency? In-Reply-To: References: Message-ID: <20070929161816.43FD71E4004@bag.python.org> > -----Original Message----- > From: hall.jeff at gmail.com > the program works great except for one thing. It's significantly > slower through the later files in the search then through the early > ones... Before anyone criticizes, I recognize that that middle section > could be simplified with a for loop... I just haven't cleaned it > up... > > The problem is that the first 300 files take about 10-15 seconds and > the last 300 take about 2 minutes... If we do more than about 1500 > files in one run, it just hangs up and never finishes... > > Is there a solution here that I'm missing? What am I doing that is so > inefficient? You did not mention the OS, but because you are using "pathname\editfile.txt", it sounds like you are using an MS OS. From past experience with various MS OSes, I found that as the number of files in a directory increases the slower your process runs for each file. You might try putting these files into multiple sub-directories. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From whamil1 at entergy.com Mon Sep 10 12:24:11 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 10 Sep 2007 11:24:11 -0500 Subject: Silent SaveAs when using the Excel win32com module In-Reply-To: <1189439861.200686.245420@k79g2000hse.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB38@LITEXETSP001.etrsouth.corp.entergy.com> > From: Chris > > I'm trying to create an excel file which will act as a log, however I > want to overwrite the file if it exists. > > Looking at the SaveAs method I can't find anything that would allow > it. I don't want the prompt to appear to ask whether to replace the > file or not. I just want to replace it without thinking. > > Thanks in advance. Check if the file exists and delete it before saving the new one. -- -Bill Hamilton From nospam at nowhere.com Sat Sep 29 23:17:03 2007 From: nospam at nowhere.com (DavidM) Date: 30 Sep 2007 15:17:03 +1200 Subject: ANN: y4m - Python video editing framework Message-ID: <46ff071f@news.orcon.net.nz> Hi all, Just a quick message to announce the latest release (v0.1.1) of the 'y4m' framework. www.freenet.org.nz/y4m What is 'y4m'? y4m is a python framework for manipulating yuv4mpeg video streams. Young but growing rapidly. It offers an intuitive Python API for: - opening yuv4mpeg streams for reading from stdin or a file (or auto-converting from any other video format ffmpeg can cope with) - opening yuv4mpeg streams for writing to stdout or a file (or autoconverting to any other video format ffmpeg can handle) - reading/changing stream and frame attributes - manipulating frames at any level - as rows/columns, or as pixels, or as Y,Cb,Cr planes - performing basic editing operations, such as: - scaling - cropping - clipping (eg taking 15 secs of a stream after the first minute) - flipping - overlaying - cross-fading (also known as 'dissolve') - transparency - polygon fill - arbitrary rotation - simple keyframe interpolation It also features a plugin architecture, whereby you can overcome the performance penalties of python by invoking fast plugins written in C. The plugin interface offers a simple and powerful framework to support writing your own plugins easily, and comes with several working example plugins). y4m is a toolkit you can use for writing your own yuv4mpeg stdio filters, or even building your own video editing software. y4m is still in alpha, but works quite well on 32-bit architecture. (I can't guarantee it on 64-bit just yet - at least not till I've pulled out all the remaining (sizeof)int==(sizeof)(*) assumptions. Anyone with 64-bit architecture is welcome to try it - I'd love to hear how you get on with it.) All feedback, suggestions, patches, bouquets, brickbats etc welcome. Cheers David From mauro.tiz at gmail.com Thu Sep 27 10:16:45 2007 From: mauro.tiz at gmail.com (mauro) Date: Thu, 27 Sep 2007 07:16:45 -0700 Subject: Launching command on windows In-Reply-To: <1190899078.141370.116190@57g2000hsv.googlegroups.com> References: <1190899078.141370.116190@57g2000hsv.googlegroups.com> Message-ID: <1190902605.700575.127180@n39g2000hsh.googlegroups.com> On 27 Set, 15:17, Alexandre Badez wrote: > Hy, > > I'm working on windows and I try to do something like: > > import os > APP = os.path.abspath("C:\\Program Files\\Notepad++\\notepad++.exe") > FILE1 = os.path.abspath("D:\\Documents and settings\\test1.py") > FILE2 = os.path.abspath("D:\\Documents and settings\\test2.py") > command = '"%(app)s" "%(file1)s" "%(file2)s"' % { > 'app' : APP, > 'file1' : FILE1, > 'file2' : FILE2} > # === FOR 'DEBUG' === > print APP > print FILE1 > print FILE2 > print command > print repr(command) > # === END FOR 'DEBUG' === > os.system(command) > > This code give in output: > C:\Program Files\Notepad++\notepad++.exe > D:\Documents and settings\test1.py > D:\Documents and settings\test2.py > "C:\Program Files\Notepad++\notepad++.exe" "D:\Documents and settings > \test1.py" "D:\Documents and settings\test2.py" > '"C:\\Program Files\\Notepad++\\notepad++.exe" "D:\\Documents and > settings\\test1.py" "D:\\Documents and settings\\test2.py"' > > 'C:\Program' n'est pas reconnu en tant que commande interne > ou externe, un programme ex,cutable ou un fichier de commandes. > # <= My windows is a french one > # This error message could be translated as: > # 'c:\Program' is not an internal nor external command, an executable > program nor a command file > > But if I copy the command in the output, an paste it in a console, it > work very well. > Does any of you know what I can do ? > > PS: I think I'm oblige to add " neer every path for spaces in path, > but if you know an other way, it could be cool :) If you don't mind using spawnl instead of system, this should work even with spaces: os.spawnl(os.P_NOWAITO, command) I hope it helps. Mauro From cyberco at gmail.com Fri Sep 21 16:08:08 2007 From: cyberco at gmail.com (cyberco) Date: Fri, 21 Sep 2007 20:08:08 -0000 Subject: uninstall python2.5 on debian In-Reply-To: References: Message-ID: <1190405288.005864.153180@r29g2000hsg.googlegroups.com> On Sep 18, 9:03 am, "dimitri pater" wrote: > Hello, > both python2.3 and python2.5 are installed on my Debian webserver. For > some reason, I would like to uninstall Python2.5 which was installed > from source (make install) and keep 2.3. > I have tried make uninstall and searched the web, but that did not help me. > I guess rm -Rf python2.5 is not a wise thing to do. > > thanks, > Dimitri > > -- > --- > You can't have everything. Where would you put it? -- Steven Wright > --- > please visitwww.serpia.org I'm not sure if this is what you're looking for, but in /usr/bin/ there is a symbolic link named 'python' that points to a python version in the same directory. I had the same issue and just redirected the pointer (deleted the old one and created an new one with the same name that pointed to the python version I wanted to use when invoking 'python'). Having said that, the other python version is still installed...(which was no problem at all in my case). From BjornSteinarFjeldPettersen at gmail.com Sat Sep 29 13:33:54 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sat, 29 Sep 2007 10:33:54 -0700 Subject: Program inefficiency? In-Reply-To: <1191079347.192272.240540@22g2000hsm.googlegroups.com> References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> Message-ID: <1191087234.915654.182370@k79g2000hse.googlegroups.com> On Sep 29, 5:22 pm, hall.j... at gmail.com wrote: > I wrote the following simple program to loop through our help files > and fix some errors (in case you can't see the subtle RE search that's > happening, we're replacing spaces in bookmarks with _'s) > > the program works great except for one thing. It's significantly > slower through the later files in the search then through the early > ones... Before anyone criticizes, I recognize that that middle section > could be simplified with a for loop... I just haven't cleaned it > up... > > The problem is that the first 300 files take about 10-15 seconds and > the last 300 take about 2 minutes... If we do more than about 1500 > files in one run, it just hangs up and never finishes... > > Is there a solution here that I'm missing? What am I doing that is so > inefficient? Ugh, that was entirely too many regexps for my taste :-) How about something like: def attr_ndx_iter(txt, attribute): "Return all the start and end indices for the values of attribute." txt = txt.lower() attribute = attribute.lower() + '=' alen = len(attribute) chunks = txt.split(attribute) if len(chunks) == 1: return start = len(chunks[0]) + alen end = -1 for chunk in chunks[1:]: qchar = chunk[0] end = start + chunk.index(qchar, 1) yield start + 1, end start += len(chunk) + alen def substr_map(txt, indices, fn): "Apply fn to text within indices." res = [] cur = 0 for i,j in indices: res.append(txt[cur:i]) res.append(fn(txt[i:j])) cur = j res.append(txt[cur:]) return ''.join(res) def transform(s): "The transformation to do on the attribute values." return s.replace(' ', '_') def zap_spaces(txt, *attributes): for attr in attributes: txt = substr_map(txt, attr_ndx_iter(txt, attr), transform) return txt def mass_replace(): import sys w = sys.stdout.write for f in open(r'pathname\editfile.txt'): try: open(f, 'w').write(zap_spaces(open(f).read(), 'href', 'name')) w('.') # progress-meter :-) except: print 'Error processing file:', f minimally-tested'ly y'rs -- bjorn From lasses_weil at klapptsowieso.net Sun Sep 2 13:29:01 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 02 Sep 2007 19:29:01 +0200 Subject: Glade + Python = No GUI In-Reply-To: <1188750465.530463.271750@22g2000hsm.googlegroups.com> References: <1188750465.530463.271750@22g2000hsm.googlegroups.com> Message-ID: <46daf2de$0$4530$9b4e6d93@newsspool3.arcor-online.net> Kveldulv wrote: > I made simple GUI in Glade 3 (Ubuntu 7.04) consisting of only 2 > buttons. When I run > 2buttonsgui.py, no GUI pops out > > #!/usr/bin/env python > import pygtk > import gtk.glade > > class TwoButtonsGUI: > def __init__(self): > self.window = gtk.glade.XML("/home/myusername/Desktop/ > 2buttons.glade", "window1") > > if __name__ == '__main__': > TwoButtonsGUI() > gtk.main() > > When interrupted, I get > > File "gui.py", line 11, in > gtk.main() > > When GUI coded manually, all works. > Shouldnt there be more to that error message of yours? I would expect something like "NameError: name 'gtk' is not defined"? Because as it seems you haven't impored gtk (only gtk.glade). So adding "import gtk" at the beginning should help. I may be wrong; I recall some weird importing requirements for pygtk, so I'm not sure if I'm to uninformed to see the actual problem. /W From mridula.ccpl at gmail.com Tue Sep 25 06:21:24 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Tue, 25 Sep 2007 15:51:24 +0530 Subject: buttons keep jumping, frame loads on top of itself Message-ID: <33dffc910709250321j5695933dq84b5d8c6b76273ed@mail.gmail.com> hi. my actual code is a bit too long to post here, but this is how the code works : the application loads, the first screen appears. it is to view the records in a database, so you can scroll and view records by clicking on the standard navigation buttons ( |<, <<, >>, >| ). the problem is that since all my navigation code is in one class, and the display class is called from class navigation() to make frame and the buttons, the frame and buttons are reloaded afresh each time. this means that if the text fields' lengths vary, the frame messily tends to move around to accommodate them. 1. is it wrong (ie. inefficient/ slower/ BAD pgming practice!) to reload the frame and its children widgets every time? 2. is there a way to clear the frame of the child widgets? - this would solve the problem of the Jumping Buttons! frame.destroy() seems to be crashing my application. thank you for your patience! regards, mridula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Sep 24 04:47:17 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Sep 2007 10:47:17 +0200 Subject: Passing parameters at the command line (New Python User) References: <1190621098.582906.49760@r29g2000hsg.googlegroups.com> Message-ID: <5lpbslF904p8U1@mid.uni-berlin.de> cjt22 at bath.ac.uk wrote: > Hi there. I just wondered whether anyone could recommend the correct > way I should be passing command line parameters into my program. I am > currently using the following code: Use the module optparse. Diez From sjmachin at lexicon.net Mon Sep 17 08:46:39 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 17 Sep 2007 05:46:39 -0700 Subject: how to join array of integers? In-Reply-To: <1190031374.566560.312510@19g2000hsx.googlegroups.com> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <1190031374.566560.312510@19g2000hsx.googlegroups.com> Message-ID: <1190033199.800006.288530@y42g2000hsy.googlegroups.com> On Sep 17, 10:16 pm, "timw.google" wrote: > On Sep 15, 8:36 am, Summercool wrote: > > > i think in Ruby, if you have an array (or list) of integers > > > foo = [1, 2, 3] > > > you can use foo.join(",") to join them into a string "1,2,3" > > > in Python... is the method to use ",".join() ? but then it must take > > a list of strings... not integers... > > > any fast method? > > Isn't the OP just looking for something like: > > > > >>> foo=[1,2,3] > >>> bar=[4,5,6] > >>> foo+bar > [1, 2, 3, 4, 5, 6] No. Read what he wrote. He has a SINGLE list whose elements are (e.g.) integers [1, 2, 3], *NOT* two lists. He wants to create a STRING "1,2,3", not a list. From mydomdom at gmail.com Fri Sep 14 08:43:41 2007 From: mydomdom at gmail.com (Dominique) Date: Fri, 14 Sep 2007 12:43:41 +0000 (UTC) Subject: Install Mac OS X - Idle doesn't show up References: Message-ID: Dominique gmail.com> writes: > > One precision: When I go in the console and type idle, it works: idle appears. But I would like to be able to launch idle from the dock Dominique From fw3 at hotmail.co.jp Fri Sep 7 18:59:26 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Fri, 07 Sep 2007 22:59:26 +0000 Subject: Speed of Python In-Reply-To: Message-ID: I also have tried to use numpy to speed it up. However, surprisingly, it is slower than the pure python code. Here is the code: import numpy arange=numpy.arange nlog=numpy.log def bench6(n): for i in xrange(n): for j in xrange(1000): m=j+1 z=nlog(m) z1=nlog(m+1) z2=nlog(m+2) z3=nlog(m+3) z4=nlog(m+4) z5=nlog(m+5) z6=nlog(m+6) z7=nlog(m+7) z8=nlog(m+8) z9=nlog(m+9) return z9 from math import log def bench3(n): for i in xrange(n): for j in xrange(1000): # m=j+1 z=log(j+1) z1=log(j+2) z2=log(j+3) z3=log(j+4) z4=log(j+5) z5=log(j+6) z6=log(j+7) z7=log(j+8) z8=log(j+9) z9=log(j+10) return z9 Here is the result: >>> t6=timeit.Timer("bench1.bench6(10)", "import bench1") >>> t6.repeat(1,1) [0.73878858905254674] >>> t3=timeit.Timer("bench1.bench3(10)", "import bench1") >>> t3.repeat(1,1) [0.056632337350038142] Anyone know why? Thanks Frank >From: "Kurt Smith" >To: "wang frank" >Subject: Re: Speed of Python >Date: Fri, 7 Sep 2007 16:49:05 -0500 > >On 9/7/07, wang frank wrote: > > Hi, > > Here is the matlab code: > > function [z]=bench1(n) > > for i=1:n, > > for j=1:1000, > > z=log(j); > > z1=log(j+1); > > z2=log(j+2); > > z3=log(j+3); > > z4=log(j+4); > > z5=log(j+5); > > z6=log(j+6); > > z7=log(j+7); > > z8=log(j+8); > > z9=log(j+9); > > end > > end > > z = z9; > > > > I am not familiar with python, so I just simply try to reproduce the same > > code in python. > > If you think that my python script is not efficient, could you tell me how > > to make it more efficient? > >One thing you can do is bind math.log to the function's namespace thusly: > >import math >def bench1_opt(n): > log = math.log > for i in range(n): > for j in range(1000): > m=j+1 > z=log(m) > z1=log(m+1) > z2=log(m+2) > z3=log(m+3) > z4=log(m+4) > z5=log(m+5) > z6=log(m+6) > z7=log(m+7) > z8=log(m+8) > z9=log(m+9) > return z9 > >On my system I get about a 20% speedup over the 'unoptimized' version >(even though this optimization is rather trivial and may even help >readability). Still not matlab speed, but better. You might be able >to do better using xrange instead of range, but the loop overhead >isn't the main slowdown (only about 1% ). > >For comparisons in real-world usage (if you are doing numerical work), >I urge you to take a look at a specifically numerical package -- >numpy/scipy or their equivalents: http://www.scipy.org/ Python is a >*very* general language not suited for heavy numerical work out of the >box -- dedicated numerical packages adapt python to this specialized >envirornment, and are becoming more and more competitive with Matlab. >The best part is you can put your time-critical code in FORTRAN or C >and wrap it with pyrex, f2py, weave, etc. pretty easily, and still >have the beauty of Python gluing everything together. > >Kurt _________________________________________________________________ ??????????????????????????????????? http://messenger.live.jp/ From steve at holdenweb.com Mon Sep 10 21:02:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Sep 2007 21:02:20 -0400 Subject: question on python syntax In-Reply-To: <1189467581.200075.236120@g4g2000hsf.googlegroups.com> References: <1189467581.200075.236120@g4g2000hsf.googlegroups.com> Message-ID: a.m. wrote: > If I type this in shell > > $ ./yourfile.py 12:34 PM & > > What does '$', '.', '/' and '& means in this succession? Note: 12:34 > PM is a argument to the yourfile.py. > "$" is the shell prompting you to let you know it's ready for you to type a command. "./" says "look in the current directory for a file called ...". Since the first token in the command contains a path separator ("/") the normal mechanism of looking for the executable in each of the directories in the current $PATH is not used [if you don't understand this sentence, ignore it]. "&" says "run this command in the background and immediately prompt for another command, instead of waiting for the command to finish like you usually do". Technically, by the way, 12:34 PM is *two* arguments to the yourfile.py, not one. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Sep 12 18:47:31 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 13 Sep 2007 00:47:31 +0200 Subject: pythonesque constructs for c++ References: Message-ID: <5kr8k3F53m8gU2@mid.individual.net> Josh wrote: > Does anyone know of analagous c++ libraries? It seems to me that > most of the functionality of these modules could easily be > replicated in c++. Sure, there are many. Apart from the already named, also widget libraries often bring their own tools for this. wxWidgets and Qt do, for instance. Regards, Bj?rn -- BOFH excuse #15: temporary routing anomaly From steve at holdenweb.com Tue Sep 18 11:51:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Sep 2007 11:51:20 -0400 Subject: Using pseudonyms (was Re: Python 3K or Python 2.9?) In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46ee2d9d$0$26213$426a74cc@news.free.fr> <46ef893c$0$21882$426a34cc@news.free.fr> Message-ID: <46EFF3F8.7000303@holdenweb.com> Aahz wrote: > In article <46ef893c$0$21882$426a34cc at news.free.fr>, > Bruno Desthuilliers wrote: >> Aahz a ?crit : >>> In article <46ee2d9d$0$26213$426a74cc at news.free.fr>, >>> Bruno Desthuilliers wrote: >>>> But what, given that I'm an AOL user still thinking it's kewl to hide >>>> behind a pseudo, what else would you expect ? >>> What exactly is a "pseudo", pray tell? >> Sorry : a pseudonym (a nickname). > > You apparently missed the thrust of my sarcasm. You can't tell what is > or is not a pseudonym online. For all I know, "Bruno Desthulliers" is a > pseudonym. While I recognize that there is some social advantage to > linking consistent identifiers with people, I have I think understandable > irritation with people who insist that names follow certain patterns. > > (For those joining only recently, my full legal name is "Aahz", which I > changed from my former name precisely because of attitudes like Bruno's.) > ... coupled with a certain bloody-mindedness that forces you to rub people's noses in your ability to choose to do so? ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From istvan.albert at gmail.com Thu Sep 20 20:48:39 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 20 Sep 2007 17:48:39 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190330015.131971.265680@y42g2000hsy.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> Message-ID: <1190335719.911878.299700@k79g2000hse.googlegroups.com> On Sep 20, 7:13 pm, "mensana... at aol.com" wrote: > How come it's not? Then I noticed you don't have brackets in > the join statement. So I tried without them and got If memory serves me right newer versions of python will recognize and optimize string concatenation via the += operator, thus the advice to use join does not apply. i. From http Thu Sep 13 16:14:14 2007 From: http (Paul Rubin) Date: 13 Sep 2007 13:14:14 -0700 Subject: An ordered dictionary for the Python library? References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> Message-ID: <7xps0mmig9.fsf@ruckus.brouhaha.com> Mark Summerfield writes: > > Yes. It should use a functional data structure. > Could you elaborate? I mean use a data structure like an AVL tree, that can make a new dict object quickly, whose contents are the same as the old object except for one element (i.e. most of the contents are shared with the old dict). You should also have ordered versions of both lists and sets. Consider the situation with lists: a = some 1000 element list b = a + [23] Now a has 1000 elements and b has 1001 elements (23 followed by a's elements), but constructing b required copying all of a's elements. It's sort of the same with sets: a = 1000 element set b = a + set((23,)) b had to copy the contents of a. By using a tree structure, you can construct b in O(log(1000)) operations so that most of the elements are shared with a, while at the same time you don't mutate a. That makes it a lot easier to program in a style where you have a bunch of slightly different versions of some set or dict flying around. For an example of where this came up, see this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/78b5953488d772e9/82f701c302122777 For sample implemetations and API's, you could look at the Hedgehog Lisp version of AVL trees (including a Python dict-like interface): http://hedgehog.oliotalo.fi/ and Haskell's Data.Map library: http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Map.html I think there is something similar in the ML Basis library but I'm not familiar with that. For more about functional data structures, see some of Chris Okasaki's articles: http://www.eecs.usma.edu/webs/people/okasaki/pubs.html Dr. Okasaki also has written a book about the topic, called "Purely Functional Data Structures", which is very good. That said, in Python maybe this stuff would be easier to use improperly because Python coding style uses mutation so much. It might be best to limit sharing to the case of frozen dicts and frozen sets. From gigs at hi.t-com.hr Fri Sep 14 07:40:17 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 14 Sep 2007 13:40:17 +0200 Subject: recursion In-Reply-To: References: Message-ID: sorry i think that i express wrong. having problem with english what i mean is how python knows to add all thing at the end of recursion >>> def f(l): if l == []: return [] else: return f(l[1:]) + l[:1] f([1,2,3]) recursion1 f([2,3]) + [1] recursion2 f([3]) + [2] or [2, 1]? recursion3 f([]) + [3] or [3, 2, 1] i dont get all this >>> def f(l): if l == []: print l return [] else: return f(l[1:]) + l[:1] >>> f([1,2,3]) [] [3, 2, 1] # how this come here? how python save variables from each recursion? sorry again for first post thanks From jstroud at mbi.ucla.edu Fri Sep 7 00:51:40 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 06 Sep 2007 21:51:40 -0700 Subject: why should I learn python In-Reply-To: <1189133913.480902.289070@57g2000hsv.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <1189117798.506367.278560@y42g2000hsy.googlegroups.com> <1189118200.040934.151520@57g2000hsv.googlegroups.com> <1189133913.480902.289070@57g2000hsv.googlegroups.com> Message-ID: BartlebyScrivener wrote: > On Sep 6, 5:36 pm, Andr? wrote: > >> Easy to read, easy to write, good libraries and, I have found, an >> extremely helpful community. >> >> Hobbyists (like me) can work on projects written in Python on and off >> (sometimes for weeks if not months without programming) and be able to >> resume the work very quickly (because it's so easy to read and >> understand the code). >> > > I second these. I am not a programmer. You can get busy with other > projects for weeks and come back to Python code and pick up where you > left off, because it uses WORDS. Try remembering what (<>) or <*> > means after being away from Perl for a month. > > rd > Better is to try to remember the differences between and uses of: $stupidPerl[4] ${stupidPerl}[4] $stupidPerl->[4] ${stupidPerl}->[4] $#stupidPerl[4] $#{stupidPerl}[4] $#{stupidPerl}->[4] $#{$stupidPerl}->[4]->[4] And so on. Quiz: which are valid? (Careful now.) The friggin' language is useless (except for the fact that, like window$, a lot of people insist on using it over superior alternatives and so you find yourself confronting it from time to time). In fact, it was the need to use nested data structures that made me move to python when I realized all of the above would be a thing of the past (also made useless my perl "cheat sheet" that sits in my big-fat-useless-camel-book). $Perl->[Useless] -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From gagsl-py2 at yahoo.com.ar Wed Sep 5 22:35:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Sep 2007 23:35:36 -0300 Subject: Wanted: safe codec for filenames References: <87sl5tcrw9.fsf@wilson.homeunix.com> <87ps0w92ki.fsf@wilson.homeunix.com> Message-ID: En Wed, 05 Sep 2007 19:20:45 -0300, Torsten Bronger escribi?: > Torsten Bronger writes: > >> I'd like to map general unicode strings to safe filename. I tried >> punycode but it is case-sensitive, which Windows is not. Thus, >> "Hallo" and "hallo" are mapped to "Hallo-" and "hallo-", however, >> I need uppercase Latin letters being encoded, too, and the >> encoding must contain only lowercase Latin letters, numbers, >> underscores, and maybe a little bit more. The result should be >> more legible than base64, though. > > Okay, the following works fine for me: Nice codec. Altough if one is looking for really portable file names, there are additional rules, collected here http://www.boost.org/libs/filesystem/doc/portability_guide.htm Hard to comply with all the character set rules *and* keep all name lengths below the limits. -- Gabriel Genellina From erik at myemma.com Wed Sep 19 16:02:25 2007 From: erik at myemma.com (Erik Jones) Date: Wed, 19 Sep 2007 15:02:25 -0500 Subject: Google and Python In-Reply-To: <1190231094.276099.136250@22g2000hsm.googlegroups.com> References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> Message-ID: <9D568821-D3E6-4702-B5C6-6BC9AA22BCD6@myemma.com> On Sep 19, 2007, at 2:44 PM, TheFlyingDutchman wrote: > >> Have you tried Google "google python". Turns up a lot of links >> for me. >> > I had done it on this newsgroup, but not google. I did find a pretty > good link: > > http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm > > Which says: > "A few services including code.google.com and google groups. Most > other front ends are in C++ (google.com) and Java (gmail). All web > services are built on top of a highly optimizing http server wrapped > with SWIG." > > I am not clear on how you would use a language - whether C++, Java or > Python to write the web app with this custom http server. Is this http > server what is referred to as an "application server" or is it the > main web server which is usually Apache at most sites? No an http server and application server are two different things. An http server services requests of a web server those requests can be for static files or for services of a local application in which case the request if forwarded on to the application. An application services requests of an application. They are separate concepts, often chained, although they are sometimes implemented together. What they are saying here is that they have built a highly optimizing custom web server in C++ that services web requests for services of applications written in any of the three listed languages. So, yes, in this case it is what is often Apache in other installations. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From mrkafk at gmail.com Sun Sep 30 15:08:28 2007 From: mrkafk at gmail.com (mrkafk at gmail.com) Date: Sun, 30 Sep 2007 12:08:28 -0700 Subject: s.split() on multiple separators In-Reply-To: <1191176852.604761.179480@y42g2000hsy.googlegroups.com> References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> <1191176852.604761.179480@y42g2000hsy.googlegroups.com> Message-ID: <1191179308.473354.98850@n39g2000hsh.googlegroups.com> On 30 Wrz, 20:27, William James wrote: > On Sep 30, 8:53 am, mrk... at gmail.com wrote: > E:\Ruby>irb > irb(main):001:0> ' abcde abc cba fdsa bcd '.split(/[ce ]/) > => ["", "ab", "d", "", "ab", "", "", "ba", "fdsa", "b", "d"] That's acceptable only if you write perfect ruby-to-python translator. ;-P Regards, Marcin From steve at REMOVE-THIS-cybersource.com.au Tue Sep 4 17:13:21 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 04 Sep 2007 21:13:21 -0000 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> Message-ID: <13drijhfqlvlk96@corp.supernews.com> On Mon, 03 Sep 2007 23:42:56 -0700, Paul Rubin wrote: > Antoon Pardon writes: >> > No the idea is that once there's enough entropy in the pool to make >> > one encryption key (say 128 bits), the output of /dev/urandom is >> > computationally indistinguishable from random output no matter how >> > much data you read from it. >> >> If you were talking about /dev/random I would agree. But this is what >> the man page on my system says about /dev/urandom. ... >> the returned values are theoretically vulnerable to a >> cryptographic attack on the algorithms used by the driver. > > Right. The idea is that those attacks don't exist and therefore the > output is computationally indistinguishable from random. It is a huge leap from what the man page says, that they don't exist in the unclassified literature at the time the docs were written, to what you're saying, that they don't exist. The man page is clear: there is a possible vulnerability in /dev/urandom. Any cryptographer worth his salt (pun intended) would be looking to close that vulnerability BEFORE an attack is made public, and not just wait for the attack to trickle down from the NSA to the script kiddies. The time to close the stable door is _before_ the horse gets away. > Of course > whether the idea is correct, an unproven conjecture, but it looks pretty > good; certainly finding any problem with the specific algorithms in > urandom would be a significant research discovery and not likely to > affect the application being discussed. I agree that this flaw doesn't sound like it will effect the application being discussed, but a problem has already been found and a solution is already known: block until there's enough entropy. That's what /dev/ random does. [snip] > In short, using /dev/random is fairly silly once you know there's enough > entropy in the randomness pool to make a good key. If /dev/urandom's > algorithms are broken then whatever you're doing with the /dev/random > output is probably also broken. That doesn't follow. Antoon is specifically warning that /dev/urandom is non-blocking. If you knew there was enough entropy available, you wouldn't need /dev/random -- but how do you know there's enough entropy? (I suppose you could look in /proc/sys/kernel/random/entropy_avail.) For this specific application, it probably doesn't matter -- using /dev/ urandom is surely overkill, and on a single-user Linux desktop you're unlikely to have vast numbers of applications reading /dev/urandom without your knowledge. But why not use /dev/random? What's the downside? -- Steven. From ricaraoz at gmail.com Sat Sep 8 11:08:16 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 08 Sep 2007 12:08:16 -0300 Subject: How to determine the bool between the strings and ints? In-Reply-To: <1189193206.466633.148610@r34g2000hsd.googlegroups.com> References: <1189182688.290480.102350@o80g2000hse.googlegroups.com> <5kdjmcF31i6hU7@mid.uni-berlin.de> <1189193206.466633.148610@r34g2000hsd.googlegroups.com> Message-ID: <46E2BAE0.7030106@bigfoot.com> Zentrader wrote: > On Sep 7, 11:30 am, Marc 'BlackJack' Rintsch wrote: >> On Fri, 07 Sep 2007 18:49:12 +0200, Jorgen Bodde wrote: >>> As for why caring if they are bools or not, I write True and False to >>> the properties, the internal mechanism works like this so I need to >>> make that distinction. >> Really? Can't you just apply the `int()` function? >> >> In [52]: map(int, [1, 0, True, False]) >> Out[52]: [1, 0, 1, 0] >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Blackjack's solution would take care of the problem, so this is just > for general info. Looks like a "feature" of isinstance() is to > consider both True and 1 as booleans, but type() distinguishes between > the two. >>>> x=True > ... if type(x) == type(1): > ... print "int" > ... else: > ... print "not int" > ... > not int > > if type(x) == type(True): > ... print "bool" > ... > bool > Or just : >>> a = True >>> type(a) == int False >>> type(a) == bool True >>> a = 'True' >>> type(a) == bool False >>> type(a) == str True >>> a = 5 >>> type(a) == bool False >>> type(a) == str False >>> type(a) == int True >>> a = 4.323 >>> type(a) == int False >>> type(a) == float True From steven.klass at gmail.com Thu Sep 6 13:26:34 2007 From: steven.klass at gmail.com (rh0dium) Date: Thu, 06 Sep 2007 17:26:34 -0000 Subject: Help setting default class attributes Message-ID: <1189099594.432512.278950@22g2000hsm.googlegroups.com> Hi all, I have the following piece of code and I wanted to set the default attributes based on a dictionary. What I am looking for is a way to take PIPODEFAULTS and assign each one as an attribute for the class pipo. Can someone show me how to do this by iterating over the PIPODEFAULTS and assign them. What I would expect to be able to do is call the class and modify them. example: a = pipo() print a.caseSensitivity "preserve" a.caseSensitivity = "lower" print a.caseSensitivity "lower" Lastly - here is my code: class pipo: PIPODEFAULTS={ "caseSensitivity" : "preserve","cellMapTable" : "","checkPolygon" : "nil","compression" : "none", "convertDot" : "ignore","convertPathToPoly" : "nil","convertToGeo" : "nil","dumpPcellInfo" : "nil", "snapToGrid" : "nil","techFileChoice" : "nil","units": "micron","useParentXYforText" : "nil","viewName" : "layout", } def __init__(self, *args, **kwargs): """This simply will run a PIPO stream out """ # Setup Logging self.pipoargs=self.setdefaults() def setdefaults(self): for x in self.PIPODEFAULTS: self.log.debug("Setting %s to %s" % (x, self.PIPODEFAULTS[x])) From deets at nospam.web.de Wed Sep 26 06:48:59 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Sep 2007 12:48:59 +0200 Subject: setuptools without unexpected downloads References: <87ejgmklep.fsf@benfinney.id.au><878x6ukkvq.fsf@benfinney.id.au> <5luhb0Faal8aU1@mid.uni-berlin.de> <874phhlupi.fsf@benfinney.id.au> <5lumarFae888U1@mid.uni-berlin.de> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> Message-ID: <5lurorFa92euU1@mid.uni-berlin.de> > If you look at PEP 345... > > http://www.python.org/dev/peps/pep-0345/ > > ...you'll see that the dependency information described is quite close > to how such information is represented in Debian packages and with > other dependency management systems. This isn't an accident because > the authors were surely already familiar with such representations, > which have been around for quite some time. Admittedly, it isn't easy > to make a system which observes the rules of all the different > existing systems; for example, can .deb metadata and .rpm metadata be > interpreted in the same way and be taken to mean the same thing? > However, the argument that a dependency manager cannot deal with > different system packages is a weak one: apt and Smart have shown that > dependency management can be decoupled from package management. Do you care to elaborate on how apt has shown that? I use it every day (or at least often), but I have to admit I never delved to deeply into them - to me it appears that apt is a retrieval-solution, not so much a dependency management system. The dependencies are declared in the debs themselves, used by dpkg-* - aren't they? Sure, apt does solve them, but how so decoupled from the underlying .deps? Regarding smart: what I read here """ Smart is not meant as an universal wrapper around different package formats. It does support RPM, DEB and Slackware packages on a single system, but won't permit relationships among different package managers. While cross-packaging system dependencies could be enabled easily, the packaging policies simply do not exist today. This is not at all different from what you can already do. In fact, Debian has been shipping the RPM package manager for a few years now. "Possible" does not equal "good idea", and everybody should stick to their native package format. """ in the FAQ doesn't make me think that it's just a matter of unwillingness from the setuptools-people but instead an intrinsic property of dependency-handling that makes cross-package-management-management (or meta-management) hard. Apart from the technical intricacies of .deb/.rpm and their respective tools, on thing sure makes this an argument: THEY evolve as they like, and it sure puts a lot of additional burden to the setuptools-guys to keep track with that. > Of course, I've already pointed out that despite being written in > Python, there's apparently no interest in the setuptools community to > look at what Smart manages to do, mostly due to spurious licensing > "concerns", and there's always the "argument zero" from people who > choose to ignore existing dependency management solutions: that > Windows doesn't provide such solutions - which is apparently not > entirely true, either. > > [...] > >> For example - what if there is no debian package that provides module XY >> in the required version? Do you rather install it into the global >> site-packages, or do you rather keep it private to the program requiring >> it? I'd say the latter is better in mostly all circumstances, as it will >> not disrupt the workings of other programs/modules. > > For what it's worth, it is possible to use Debian dependency/package > management as a non-root user with a local site-packages directory, > but it isn't particularly elegant. See this proof of concept for > details: > > http://www.boddie.org.uk/paul/userinstall.html > > It's a fairly heavy solution which installs a lot of the > administrative toolchain just for local package installations, but you > do get dependency integration with the packages providing the > libraries that may be required by various Python extension modules. Certainly a nice solution to a real problem that might be handy for me at some time. Yet I fail to see how that relates to the above question: if the OS package repository fails to meet a certain version requirement, how do you deal with that - installation local to the product you're actually interested in installing, or in a more public way that possibly interferes with other software? Diez From samy.rolka at gmail.com Sun Sep 30 06:58:13 2007 From: samy.rolka at gmail.com (rolkA) Date: Sun, 30 Sep 2007 10:58:13 -0000 Subject: which language allows you to change an argument's value? In-Reply-To: <1191149233.346818.246170@22g2000hsm.googlegroups.com> References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> Message-ID: <1191149893.586846.283530@22g2000hsm.googlegroups.com> On 30 sep, 12:47, Summercool wrote: > I wonder which language allows you to change an argument's value? > like: > > foo(&a) { > a = 3 > > } > > ... > is there any way to prevent a function from changing the argument's > value? > ... > Is there a way to prevent it from happening in the > languages that allows it? Hi, Of course in C++, functions that don't modify argument's value should (i'd rather say MUST) wait for a CONST reference or a value : // const ref foo(const T& a) { a = 3; // error } // value foo(T a) { a = 3; // ok, but modify only the formal parameter : the argument (aka actual parameter) is not changed } Now if you want to prevent a function (from a library you are using) to modify it... Erm well, you shouldn't : a good librairy will never wait for a non-const argument if it doesn't need to be modified. So in this case "Is there a way to prevent it from happening" is unpertinent : you could copy the object, but if the purpose of the fucntion was to modify it, it's pointless. From DouhetSukd at gmail.com Fri Sep 14 12:10:31 2007 From: DouhetSukd at gmail.com (DouhetSukd at gmail.com) Date: Fri, 14 Sep 2007 09:10:31 -0700 Subject: How to Start In-Reply-To: References: Message-ID: <1189786231.993024.128900@k79g2000hse.googlegroups.com> On Sep 13, 4:02 pm, Nikita the Spider wrote: > My $.02 for someone such as yourself > is to deal with Python and as little else as possible. So write your > code in a simple text editor like UltraEdit or Notepad Second that opinion. Use _your_ favorite basic text editor and run on command line. Don't clutter your attention with complex tools, yet, Python's not J2EE for Pete's sake. I started on Kedit, but mostly use Eclipse + pydev now, with KEdit as a backup. Do use one of the interactive interpreters (pythonwin, python prompts, etc...) to try out one liners and short pieces of code. But I've never really liked them for writing full programs. And I would just do the tutorial or Dive Into Python (http:// www.diveintopython.org/toc/index.html). If you are as experienced as you say, you should have very little trouble working through them, really quickly (3-4 hours?) and you'll have a good tour of the features. I picked up Python on a Montreal to Vancouver flight, doing just that. For your problem domain. Modules: optparse, regular expressions. Perhaps the "Text Processing in Python" book by Mertz. I don't like it much myself, but it does cover text processing in depth and it refers to a number of existing specialized libraries. Cheers From deets at nospam.web.de Fri Sep 28 15:34:43 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Sep 2007 21:34:43 +0200 Subject: Python 3.0 migration plans? References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> Message-ID: <5m53aiFbfe3hU1@mid.uni-berlin.de> TheFlyingDutchman wrote: > >> >> Or bind resources of these pocket protectors that otherwise would lead to >> answers for people that do seek enlightment... > > I don't think it would be correct to characterize my posts as not > seeking enlightenment. I do also happen to voice my opinion which > seems appropriate since this can be characterized as a discussion > group. It theoretically is possible for a discussion group to tolerate > opinions that diverge from the majority. I would characterize """ I like how someone here characterized decorators - those silly @ things. They remind me of Perl. Not adding keywords for abstract and static is like Perl not adding a keyword for class. """ not as seeking enlightenment, but as pure trolling. Disqualifying features without actually understanding them as "silly" certainly doesn't lie on one of the many path's to enlightenment known man - which to my knowledge usually require more humble approaches.... > One issue I have with this group and that I encountered many years ago > in the Perl group is that there is no separate group > comp.lang.python.beginner where you can ask questions without getting > hit with RTFM! and the like. And I wish people that have no clue about the deeper workings of Python wouldn't insist on commenting on these in inappropriate ways as above, but instead try and _understand_ them before debuking them or suggesting changes. Diez From laurent.pointal at limsi.fr Tue Sep 11 08:22:39 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 11 Sep 2007 14:22:39 +0200 Subject: XML: SAX and XInclude In-Reply-To: <46E5490F.8060107@web.de> References: <46E5490F.8060107@web.de> Message-ID: Stefan Behnel a ?crit : > Laurent Pointal wrote: >> does anybody know about an XML parser usable with the sax API (xml.sax) >> and with XInclude feature support (directly or via hacks). > > Try lxml.etree. > > http://codespeak.net/lxml/ > > http://codespeak.net/lxml/tutorial.html > http://codespeak.net/lxml/api.html#xinclude-and-elementinclude > http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk > > It's not half as complicated as SAX, BTW. > > Stefan I've already used ElementTree for XML tree manipulations in some projects... will try to adapt my sax based processing to lxml using those links. Thanks, Laurent. From bwarren at qstreams.com Thu Sep 6 23:02:12 2007 From: bwarren at qstreams.com (Ben Warren) Date: Thu, 6 Sep 2007 20:02:12 -0700 (PDT) Subject: Passing a tuple to a function as multiple arguments Message-ID: <789865.44579.qm@web313.biz.mail.mud.yahoo.com> Hello, Let's say I have a function with a variable number of arguments (please ignore syntax errors): def myfunc(a,b,c,d,...): and I have a tuple whose contents I want to pass to the function. The number of elements in the tuple will not always be the same. T = A,B,C,D,... Is there a way that I can pass the contents of the tuple to the function without explicitly indexing the elements? Something like: myfunc(magic(T)) where magic() expands the tuple to its multiple elements. I've tried various for loop constructs, but everything I can think of returns a list, which doesn't work because it's viewed as one parameter. thanks, Ben From bdesth.quelquechose at free.quelquepart.fr Sun Sep 9 11:18:03 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 09 Sep 2007 17:18:03 +0200 Subject: Compiler Python In-Reply-To: <5kod78F3udmuU1@mid.individual.net> References: <000001c7f4a2$307fa720$917ef560$@com> <5kod78F3udmuU1@mid.individual.net> Message-ID: <46e7045d$0$3290$426a74cc@news.free.fr> Bjoern Schliessmann a ?crit : > anton a wrote: > >>Someone knows since as I can obtain the information detailed about >>the compiler of Python? (Table of tokens, lists of productions of >>the syntactic one , semantic restrictions...) > > > I'm not really about the syntax of your question, lol !-) Sorry... Please don't take it as a personal offense (FWIW, my English is barely better than yours) From byte8bits at gmail.com Tue Sep 25 15:18:51 2007 From: byte8bits at gmail.com (byte8bits at gmail.com) Date: Tue, 25 Sep 2007 19:18:51 -0000 Subject: Script to extract text from PDF files In-Reply-To: <1190746968.162359.39890@r29g2000hsg.googlegroups.com> References: <1190746968.162359.39890@r29g2000hsg.googlegroups.com> Message-ID: <1190747931.415834.75670@n39g2000hsh.googlegroups.com> On Sep 25, 3:02 pm, Paul Hankin wrote: > Googling for 'pdf to text python' and following the first link giveshttp://pybrary.net/pyPdf/ Doesn't work that well, I've tried it, you should too... the author even admits this: extractText() [#] Locate all text drawing commands, in the order they are provided in the content stream, and extract the text. This works well for some PDF files, but poorly for others, depending on the generator used. This will be refined in the future. Do not rely on the order of text coming out of this function, as it will change if this function is made more sophisticated. - source http://pybrary.net/pyPdf/pythondoc-pyPdf.pdf.html From bdesth.quelquechose at free.quelquepart.fr Fri Sep 7 12:44:18 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 07 Sep 2007 18:44:18 +0200 Subject: How to insert in a string @ a index In-Reply-To: <1189274564.462664.131240@22g2000hsm.googlegroups.com> References: <1189274564.462664.131240@22g2000hsm.googlegroups.com> Message-ID: <46e4153a$0$32052$426a74cc@news.free.fr> lolu999 at gmail.com a ?crit : > Hi; > > I'm trying to insert XYZ before a keyword in a string. Then forget about it. Python's strings are immutable. (snip) > The python doesn't supports t1[keyword_index]="XYZhello" (string > object assignment is not supported). How do I get to this problem? Any > sugguestions? Build a new string. From carsten at uniqsys.com Thu Sep 13 14:35:06 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 13 Sep 2007 14:35:06 -0400 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189699510.244755.85080@r34g2000hsd.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> <1189699510.244755.85080@r34g2000hsd.googlegroups.com> Message-ID: <1189708506.3407.7.camel@dot.uniqsys.com> On Thu, 2007-09-13 at 09:05 -0700, Charles Fox wrote: > when you are implementing a model from a published > paper, the variables tend to be single greek or roman letter names, > possibly with subscripts and superscripts, and it helps if the name > you see on the screen is the same as the name on the paper, as is the > case in matlab. You want the equation on screen to look as similar to > the one on the paper as possible, especially if its going to be read > by another programmer who is familiar with the paper. In that case, you could/should move the calculations into a function that uses local variables, instead of a method that uses instance attributes. Accessing local variables is faster than accessing instance attributes, and you get rid of the annoying self prefix. -- Carsten Haese http://informixdb.sourceforge.net From hniksic at xemacs.org Tue Sep 25 15:14:16 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Sep 2007 21:14:16 +0200 Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> Message-ID: <873ax2o8vr.fsf@mulj.homelinux.net> Steven Bethard writes: > With this is the implementation, I'm definitely -1. Not because it's a > bad implementation, but because if the iteration is always doing a > sort, then there's no reason for a separate data structure. Agreed. A true sorted dict would keep its keys sorted in the first place, a la C++ std::map. From bignose+hates-spam at benfinney.id.au Wed Sep 26 19:41:48 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 27 Sep 2007 09:41:48 +1000 Subject: Test-driven development and code size References: <5ls95aF9pq3gU1@mid.uni-berlin.de> <87ejgmmgc2.fsf_-_@benfinney.id.au> Message-ID: <87zlz9570j.fsf@benfinney.id.au> (Joel, please preserve attribution lines on your quoted material so we can see who wrote it.) Joel Hedlund writes: > My presumption has been that in order to do proper test-driven > development I would have to make enormous test suites covering all > bases for my small hacks before I could getting down and dirty with > coding This presumption is entirely opposite to the truth. Test-driven development has the following cycle: - Red: write one test, watch it fail - Green: write minimal code to satisfy all existing tests - Refactor: clean up implementation without changing behaviour (The colours refer to the graphical display for some unit test runners: red for a failing test, green for a test pass.) This cycle is very short; it's the exact opposite to your presumption of "write huge unit test suites before doing any coding". For me, the cycles are on the order of a few minutes long; maybe longer if I have to think about the interface for the next piece of code. In more detail, the sequence (with rationale) is as follows: - Write *one* test only, demonstrating one simple assertion about the code you plan to write. This requires you to think about exactly what your planned code change (whether adding new features or fixing bugs) will do, at a low level, in terms of the externally-visible behaviour, *before* making changes to the code. The fact that it's a single yes-or-no assertion keeps the code change small and easily testable. - Run your automated unit test suite and watch your new test fail. This ensures that your test actually exercises the code change you're about to make, and that it will fail when that code isn't present. Thus your new test becomes a regression test as well. - Write the simplest thing that could possibly make the new test pass. This ensures that you write only the code absolutely necessary to the new test, and conversely, that *all* your code changes exist only to satisfy test cases. If, while making the code change, you think the code should also do something extra, that's not allowed at this point: you need a new test for that extra feature. Your current code change must be focussed only on satisfying the current test, and should do it in the way that lets you write that code quickly, knowing that you'll be refactoring soon. - Run your automated unit test suite and watch *all* tests pass. This ensures that your code change both meets the new test and doesn't regress any old ones. During this step, while any tests are failing, you are only allowed to fix them ? not add new features ? in the same vein as making the new test pass, by doing the simplest thing that could possibly work. Fixing a failing test might mean changing the code, or it might mean changing the test case if it's become obsoleted by changes in requirements. - Refactor the code unit to remove redundancy or other bad design. This ensures that, while the code unit is fresh in your mind, you clean it up as you proceed. Refactoring means that you change the implementation of the code without changing its interface; all existing tests, including the new one, must continue to pass. If you cause any test to fail while refactoring, fix the code and refactor again, until all tests pass. That is: the discipline requires you to write *one* new test and watch it fail ("Red"), then write minimal code to make *all* tests pass ("Green"), and only then refactor the code design while maintaining the "all tests pass" state. Only then do you move on to a new code change, starting a new cycle by writing a new test. It ensures that the code process ratchets forward inexorably, with the code always in a well-designed, well-factored, tested state that meets all current low-level requirements. This also encourages frequent commits into version control, because at the end of any cycle you've got no loose ends. The above effects ? short coding cycles, constant tangible forward motion, freedom to refactor code as you work on it, freedom to commit working code to the VCS at the end of any cycle, an ever-increasing test suite, finding regressed tests the moment you break them instead of spending ages looking at follow-on symptoms ? also have significantly positive effects on the mood of the programmer. When I started this discipline, I found to my surprise that I was just as happy to see a failing test as I was to see all tests passing ? because it was proof that the test worked, and gave contextual feedback that told me exactly what part of the code unit needed to be changed, instead of requiring an unexpected, indefinite debugging trek. > (as for example in http://www.diveintopython.org/unit_testing). Yes. While that chapter is a good demonstration of how unit tests work, the impression given by that chapter is an unfortunate demonstration of the *wrong* way to do unit testing. The unit test shown in that chapter was *not* written all at once, as the chapter implies; it was rather built up over time, while developing the code unit at the same time. I don't know whether Pilgrim used the above cycle, but I'm positive he wrote the unit test in small pieces while developing the code unit in correspondingly small increments. > But if I understand you correctly, if I would formalize what little > testing I do, so that I can add to a growing test suite for each > program as bugs are discovered and needs arise, would you consider > that proper test-driven development? (or rather, is that how you do > it?) Yes, "test-driven development" is pretty much synonymous with the above tight cycle of development. If you're writing large amounts of test code before writing the corresponding code unit, that's not test-driven development ? it's Big Design Up Front in disguise, and is to be avoided. For more on test-driven development, the easiest site to start with is ? which, though much of its community is focussed on Java, still has much to say that is relevant to any programmer trying to adopt the practice. Its "web links" section is also a useful starting point. -- \ "I hope that after I die, people will say of me: 'That guy sure | `\ owed me a lot of money.'" -- Jack Handey | _o__) | Ben Finney From tommy.nordgren at comhem.se Tue Sep 18 12:49:23 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Tue, 18 Sep 2007 18:49:23 +0200 Subject: Writing to multiple excel worksheets In-Reply-To: <969892.43175.qm@web50103.mail.re2.yahoo.com> References: <969892.43175.qm@web50103.mail.re2.yahoo.com> Message-ID: On 17 sep 2007, at 23.00, SPJ wrote: > Hi, > > I have a list which I need to write to excel worksheet. The list is > like: > data = > ['IP1','21','ftp','\n','IP1','22','ssh','\n','IP2','22','ssh','\n','IP > 2','23','telnet','\n'] > Now the task is to create a workbook with tabbed sheet for each of > the service's in the list i.e. tabs for ftp, ssh, telnet etc. The > data needs to be written in the corresponding sheets. > > What is the best way to achieve this? > I couldn't find much help on the internet nor in the earlier > threads. Please help. > > Thanks, > SPJ Excel files are in a binary and proprietary format. You can however generate tab-separated text files, which Excel can import. ------ 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 george.sakkis at gmail.com Sat Sep 1 10:28:34 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 01 Sep 2007 14:28:34 -0000 Subject: Important Research Project In-Reply-To: <13dhm7uec5sp855@corp.supernews.com> References: <13ddcvm1bsu3s94@corp.supernews.com> <13dhm7uec5sp855@corp.supernews.com> Message-ID: <1188656914.179330.167630@r29g2000hsg.googlegroups.com> On Sep 1, 7:13 am, "E.D.G." wrote: > "E.D.G." wrote in message > > news:13ddcvm1bsu3s94 at corp.supernews.com... > > > Important Research Project (Related to computer programming) > > > Posted by E.D.G. on August 30, 2007 edgrs... at ix.netcom.com > > This effort was not successful. Shocking, isn't it ? > And I am returning to trying to slowly > make progress with the computer program I have been developing. You might have more luck if you read http://catb.org/~esr/faqs/smart-questions.html#forum before asking for help again. From ldo at geek-central.gen.new_zealand Tue Sep 25 22:15:46 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 26 Sep 2007 14:15:46 +1200 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: In message , A.T.Hofkamp wrote: > On 2007-09-25, Lawrence D'Oliveiro > wrote: > >> Why does it "choose" to modify your position when you exit insert mode? > > Try to insert 1 character in the middle of a line. You'll end up at the > same position. Now press 'j' (one line down), then '.' (do it again). > I believe that's why. > > Great when you have nicely formatted columns of code underneath each > other. It's strange, but in nearly 30 years of writing code in dozens of different languages, I've never felt the urge to line up my code in columns. Never. (Apart from assembly language, which I suspect you don't want to hear about.) > The cost of that power is a command/insert mode and a steep learning > curve. That's another issue, that of ROI. Having learnt the vi/vim keystrokes, what does that enable you to do? Use vi/vim, and that's it. Whereas I've found other situations where subsets of Emacs keystrokes are recognized, such as anything that uses GNU readline (including the Python console--see, this IS relevant to Python after all), and pico/nano. These are all extra goodies that are to be found on the way up the Emacs learning curve. > For example, ever wondered why you on earth you need CTL-C and CTL-V to > copy/paste? Why not simply select with the mouse, then right-click to > paste? Or better still, why not allow both? >> And the downside is that the largest single proportion of those commands >> end up being variations on "enter insert mode". Because most of the >> keystrokes you enter during an editing session are in fact text to be >> input into the file, not commands to manipulate that text. So in a modal >> editor, having to > > Depends on what you are doing. When entering new code, yes. When > maintaining code, no (lots of small changes). Making lots of small changes is even worse--it means you're jumping into insert mode for shorter times, more frequently. And that's when you discover something else: that how you delete text in vi/vim differs, depending on whether it's something you just inserted while currently in insert mode, or whether it was there from before you last entered insert mode: in the former case, you use backspace to delete, in the latter case, you can't use backspace, you have to use "X". What does backspace do when not in insert mode? It just moves you through the text. What does the forward-delete key do? In both modes, it actually deletes text! At least with Emacs, text is text--it doesn't matter when it was inserted, it still behaves the same way. From gagsl-py2 at yahoo.com.ar Wed Sep 12 23:59:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Sep 2007 00:59:53 -0300 Subject: mod_python and pysvn References: <1189525797.361829.69380@g4g2000hsf.googlegroups.com> <5ko2anF4iuuiU1@mid.individual.net> <1189535700.882545.253160@k79g2000hse.googlegroups.com> Message-ID: En Tue, 11 Sep 2007 15:35:00 -0300, Sjoerd escribi?: > The actual command: > > client = Client() > repLog = client.log("\\P:\\tools\builds\publish\\") > I used an UNC path. The forming of the repository path must be inside > the pysvn > library. If that's really actual code, looks wrong. You should double all your backslashes or use a raw string. And \\P:... doesn't look well formed either. -- Gabriel Genellina From stefan.behnel-n05pAM at web.de Fri Sep 21 01:31:35 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 21 Sep 2007 07:31:35 +0200 Subject: newb: BeautifulSoup In-Reply-To: <1190348543.472684.243840@50g2000hsm.googlegroups.com> References: <1190343890.375836.78630@r29g2000hsg.googlegroups.com> <1190348543.472684.243840@50g2000hsm.googlegroups.com> Message-ID: <46F35737.5090608@web.de> TheFlyingDutchman wrote: > On Sep 20, 8:04 pm, crybaby wrote: >> I need to traverse a html page with big table that has many row and >> columns. For example, how to go 35th td tag and do regex to retireve >> the content. After that is done, you move down to 15th td tag from >> 35th tag (35+15) and do regex to retrieve the content? > > Make the file an xhtml file (valid xml) if it isn't already and then > you can use software written to process XML files: > > http://pyxml.sourceforge.net/topics/ ... or just use software that can process XML and HTML the same way *and* that supports XPath and tree iteration so that you can easily select the content you want. http://codespeak.net/lxml/ Stefan From bdesth.quelquechose at free.quelquepart.fr Mon Sep 3 11:24:30 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 03 Sep 2007 17:24:30 +0200 Subject: function call In-Reply-To: References: <1188937059.459609.61850@57g2000hsv.googlegroups.com> <46ddc12c$0$24997$426a74cc@news.free.fr> Message-ID: <46ddc866$0$25003$426a34cc@news.free.fr> Chris Mellon a ?crit : > On 9/3/07, Bruno Desthuilliers wrote: > >>ianar? a ?crit : >> >>>Hey all, >>> >>>Is there a way of printing out how a function was called? In other >>>words if I do the following: >>> >>>def someFunction(self): >>> self.someOtherFunction(var1, var2) >>> >>> >>>I would get something like "someOtherFunction: called by: >>>someFunction, args are: var1, var2" >>> >>>Thanks in advance >>> >> >>You may be able to solve this using a decorator (to avoid polluting your >>code with this) and the infamous sys._getframe() hack. >>-- > > > Every reasonable use case for this (and several unreasonable ones) > that I've encountered (and some that I've just imagined) can be better > addressed with a trace function (sys.set_trace) than by trying to do > this at the point of call. Indeed. Thanks for the correction. relevant doc here: http://docs.python.org/lib/debugger-hooks.html From furkankuru at gmail.com Sun Sep 2 16:16:22 2007 From: furkankuru at gmail.com (Furkan KURU) Date: Sun, 2 Sep 2007 23:16:22 +0300 Subject: how can I find out the process ids with a process name In-Reply-To: <1188761187.522146.192380@y42g2000hsy.googlegroups.com> References: <1188761187.522146.192380@y42g2000hsy.googlegroups.com> Message-ID: <3a4a8f930709021316p4a6ccfd7r8e2db9d85cad7f5a@mail.gmail.com> the easiest but slowest way: you can send output to a file ps -ef |grep emacs > output_file and then read the file content (I believe there is a much better way) On 9/2/07, herman wrote: > Hi, > > I would like to find out all the process id with the process name > 'emacs'. > > In the shell, i can do this: > > $ ps -ef |grep emacs > root 20731 8690 0 12:37 pts/2 00:00:09 emacs-snapshot-gtk > root 25649 25357 0 13:55 pts/9 00:00:05 emacs-snapshot-gtk rtp.c > root 26319 23926 0 14:06 pts/7 00:00:04 emacs-snapshot-gtk > stressTestVideo.py > root 26985 1 0 14:15 ? 00:00:01 /usr/bin/emacs-snapshot- > gtk > root 27472 21066 0 14:23 pts/5 00:00:00 grep emacs > > > and I can see the process id is 20731, 25649, etc, etc. > > But now I would like to do the programmically in my python script. > I know I can use ' os.system(cmd)' to execute the command 'ps -ef | > grep emacs', but how > can I pipe the output of my 'ps -ef | grep emacs' to my python script > and then run a regression expression with it to get the process Ids? > > Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru From ldo at geek-central.gen.new_zealand Wed Sep 26 03:05:18 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 26 Sep 2007 19:05:18 +1200 Subject: stopping a while True: with the keyboard References: Message-ID: In message , patrick wrote: > i am looking for a way to break a while True: when pressing "s" on my > keyboard. how can i do this? From fw3 at hotmail.co.jp Fri Sep 7 16:25:41 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Fri, 07 Sep 2007 20:25:41 +0000 Subject: Speed of Python In-Reply-To: <1189193265.845514.190500@y42g2000hsy.googlegroups.com> Message-ID: Thanks for all your help. Using Istvan Albert's suggestion, I have recompared the speed of the following funciton: matlab: function [z]=bench2(n) for i=1:n, j=(0:999); z=log(j+1); end python: from numpy import arange, log def bench4(n): for i in xrange(n): nums = arange( n ) a = log( nums + 1) Python actually is faster than Matlab. tic; z=bench2(1000); toc Elapsed time is 0.159485 seconds. Python: >>> import timeit >>> t=timeit.Timer("bench1.bench4(1000)","import bench1") >>> t.repeat(1,1) [0.10052953657517924] Thanks again. Frank >From: ajaksu >To: python-list at python.org >Subject: Re: Speed of Python >Date: Fri, 07 Sep 2007 19:27:45 -0000 > >On Sep 7, 2:37 pm, "wang frank" wrote: > > I am not familiar with python, so I just simply try to reproduce the same > > code in python. >Seems almost correct, but from what I guess of MatLab, George's >suggestions make it a bit more fair. > > > If you think that my python script is not efficient, could you tell me how > > to make it more efficient? >In pure Python? No idea (besides using Roberto's and George's >suggestions). If you allow for extensions, Istvan has the answer. If >you allow compiling Python to C++ (using ShedSkin: http://shed-skin.blogspot.com/), >here's a small report: > >---------- >ajaksu at Belkar:~/sandbox$ cat bench.py >import math >n = 1 >def bench1(n): > for i in range(n): > for j in range(1000): > m=j+1 > z=math.log(m) > z1=math.log(m+1) > z2=math.log(m+2) > z3=math.log(m+3) > z4=math.log(m+4) > z5=math.log(m+5) > z6=math.log(m+6) > z7=math.log(m+7) > z8=math.log(m+8) > z9=math.log(m+9) > return z9 >a = bench1(10) > >ajaksu at Belkar:~/sandbox$ ss -e bench.py >*** SHED SKIN Python-to-C++ Compiler 0.0.22 *** >Copyright 2005-2007 Mark Dufour; License GNU GPL version 2 (See >LICENSE) >(Please send bug reports here: mark.dufour at gmail.com) > >[iterative type analysis..] >** >iterations: 2 templates: 44 >[generating c++ code..] >ajaksu at Belkar:~/sandbox$ make bench.so >g++ -O3 -s -pipe -fomit-frame-pointer -I/home/ajaksu/shedskin-0.0.22/ >lib -g -fPIC -I/usr/include/python2.5 -D__SS_BIND /home/ajaksu/ >shedskin-0.0.22/lib/builtin.cpp /home/ajaksu/shedskin-0.0.22/lib/ >math.cpp bench.cpp -lgc -shared -Xlinker -export-dynamic -lpython2.5 - >o bench.so > >ajaksu at Belkar:~/sandbox$ mv bench.py pbench.py > >ajaksu at Belkar:~/sandbox$ ipython >Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) >[...] >In [1]: from pbench import bench1 as pbench1 > >In [2]: from bench import bench1 > >In [3]: %timeit a = bench1(10) >100 loops, best of 3: 10.2 ms per loop > >In [4]: %timeit a = pbench1(10) >10 loops, best of 3: 92.8 ms per loop > >---------- > >I guess you'd also see nice improvements from Pyrex or Cython, Blitz >and other tools. Check http://wiki.python.org/moin/PythonSpeed/PerformanceTips >for the general ideas and http://scipy.org/PerformancePython for an >insight on available tools that even compares their speeds to Matlab. > >And-if-you-run-more-benchmarks-please-do-post-them-ly yrs, >Daniel > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ 3?????????????????3?????????? ?????2.2??? ? http://clk.atdmt.com/GBL/go/msnjpqjl0060000010gbl/direct/01/ From bignose+hates-spam at benfinney.id.au Wed Sep 19 22:52:38 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 20 Sep 2007 12:52:38 +1000 Subject: cmsg cancel <87sl5aw0k0.fsf@benfinney.id.au> Message-ID: <87bqbyvyix.fsf@benfinney.id.au> I am canceling my own article. From ldo at geek-central.gen.new_zealand Mon Sep 24 00:40:36 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 24 Sep 2007 16:40:36 +1200 Subject: building a GUI References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> <5lnp2rF90pqqU1@mid.uni-berlin.de> Message-ID: In message , stef mientki wrote: > ... I never looked at PyQt seriously, because of their weird license. What's weird about it? Lots of software products are dual-licensed, e.g. MySQL, Perl. From steve at holdenweb.com Sat Sep 1 12:07:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Sep 2007 12:07:33 -0400 Subject: metaclasses: timestamping instances In-Reply-To: References: Message-ID: km wrote: > Hi all, > > I have extended a prototype idea from Alex Martelli's resource on > metaclasses regarding time stamping of instances. > > > import time > class Meta(type): > start = time.time() > def __call__(cls, *args, **kw): > print 'Meta start time %e'%cls.start > x = super(Meta, cls).__call__(*args, **kw) > current_time = time.time() > x._created = current_time - Meta.start > Meta.start = time.time() > return x > > class X(object): > __metaclass__ = Meta > class Y(X): > __metaclass__ = Meta > pass > a = X() > print 'a time stamp %e'%a._created > b = Y() > print 'b time stamp %e'%b._created > print abs(a._created - b._created) > > > I donot understand the difference between > 1) setting __metaclass__ to 'Meta' in class Y > 2) not setting __metaclass__ to Meta in class Y > > Why is the difference in behaviour of time stamping between 1 & 2 ? > > kindly enlighten > I don't see and difference. The rules for establishing the metaclass of a class are fairly well defined: see http://docs.python.org/ref/metaclasses.html which says * If dict['__metaclass__'] exists, it is used. * Otherwise, if there is at least one base class, its metaclass is used (this looks for a __class__ attribute first and if not found, uses its type). * Otherwise, if a global variable named __metaclass__ exists, it is used. * Otherwise, the old-style, classic metaclass (types.ClassType) is used. By the second rule it would appear that the metaclass of X is the same as that of Y even if the __metaclass__ assignment is commented out, and informal testing appears to show that this is the case. Debugging with Wing IDE and examining the classes at a breakpoint shows this to be true (even after Y's __metaclass__ assignment is commented out): >>> X.__metaclass__ >>> Y.__metaclass__ >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From mail at timgolden.me.uk Thu Sep 20 09:21:51 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 20 Sep 2007 14:21:51 +0100 Subject: frange() question In-Reply-To: References: Message-ID: <46F273EF.6060001@timgolden.me.uk> George Trojan wrote: > A while ago I found somewhere the following implementation of frange(): . . . > return (limit1 + n*increment for n in range(count)) > > I am puzzled by the parentheses in the last line. Somehow they make > frange to be a generator: > But I always thought that generators need a keyword "yield". What is > going on here? That's what's known as a generator expression: http://docs.python.org/ref/genexpr.html http://www.python.org/dev/peps/pep-0289/ TJG From http Sun Sep 2 02:04:56 2007 From: http (Paul Rubin) Date: 01 Sep 2007 23:04:56 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <1188585630.539835.242460@i38g2000prf.googlegroups.com> <1188592039.612652.223700@r23g2000prd.googlegroups.com> <1i3ryxd.g2pzgq159lt5sN%aleax@mac.com> <1188711881.370954.175830@o80g2000hse.googlegroups.com> Message-ID: <7xfy1xob5j.fsf@ruckus.brouhaha.com> Russ writes: > > try: > > blah blah with as many return statements as you want > > finally: > > something that gets executed unconditionally at the end > Thanks. I didn't think of that. > So design by contract *is* relatively easy to use in Python already. > The main issue, I suppose, is one of aesthetics. Do I want to use a > lot of explicit function calls for pre and post-conditions and "try/ > finally" blocks in my code to get DbC (not to mention a global > variable to enable or disable it)? I still don't understand why you don't like the decorator approach, which can easily implement the above. > I personally use Python for its clean syntax and its productivity with > my time, so I am certainly not denigrating it. For the R&D work I do, > I think it is very appropriate. But I did raise a few eyebrows when I > first started using it. I used C++ several years ago, and I thought > about switching to Ada a few years ago, but Ada just seems to be > fading away (which I think is very unfortunate, but that's another > story altogether). It seems to be getting displaced by Java, which has some of the same benefits and costs as Ada does. I've gotten interested in static functional languages (including proof assistants like Coq, that can generate certified code from your mechanically checked theorems). But I haven't done anything serious with any of them yet. I think we're in a temporary situation where all existing languages suck (some more badly than others) but the functional languages seem like a more promising direction to get out of this hole. From UrsusMaximus at gmail.com Sun Sep 23 18:22:26 2007 From: UrsusMaximus at gmail.com (UrsusMaximus at gmail.com) Date: Sun, 23 Sep 2007 15:22:26 -0700 Subject: SimPy, audio interview with creators of Message-ID: <1190586146.546763.218070@r29g2000hsg.googlegroups.com> SimpPy is a powerful simulation package for Python. I have just posted an interview (podcast) with Dr. Klaus Muller in Amsterdam and Professor Tony Vignaux in New Zealand about their creation, SimPY, an object-oriented, process-based discrete-event simulation language based on standard Python. Check it out at www.awaretek.com From bignose+hates-spam at benfinney.id.au Mon Sep 3 19:55:42 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 04 Sep 2007 09:55:42 +1000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <878x7te9h4.fsf@benfinney.id.au> Message-ID: <87bqcj9udd.fsf@benfinney.id.au> Thorsten Kampe writes: > * Ben Finney (Thu, 30 Aug 2007 18:02:15 +1000) > > Bruno Desthuilliers writes: > > > What's with using your brain instead of whining ? > > > > Now now, no need for snappiness. > > Actually there was. The OP's claim [...] ...is just plain nonsense. Which was pointed out in several ways without snapping. Hence the part of my response you omitted. Ben Finney wrote: > If you don't feel a constructive response is merited, please ignore. There's no need to fuel flames with content-free flaming, and Bruno agreed with that when it was pointed out. If one doesn't have the time or inclination to post a constructive response, not responding at all is better than flaming. The Python community is remarkable for its low level of flaming and high level of content in this forum, even in response to poor attitudes and cluelessness. I'd like it to remain that way. -- \ "I don't like country music, but I don't mean to denigrate | `\ those who do. And for the people who like country music, | _o__) denigrate means 'put down'." -- Bob Newhart | Ben Finney From raychorn at hotmail.com Sat Sep 22 00:55:01 2007 From: raychorn at hotmail.com (Python Maniac) Date: Fri, 21 Sep 2007 21:55:01 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> <1190394011.148384.106280@q3g2000prf.googlegroups.com> <1190417120.723579.267560@22g2000hsm.googlegroups.com> Message-ID: <1190436901.529332.326010@19g2000hsx.googlegroups.com> On Sep 21, 4:48 pm, "Matt McCredie" wrote: > > It would be nice if Python could be made to automatically detect the > > LC and string translation patterns used by the unoptimized Python code > > and make them into optimized Python code on the fly at runtime. I am > > more than a little amazed nobody has chosen to build a JIT (Just In- > > Time compiler) or cached-compiler into Python but maybe that sort of > > thing is just not needed given the fact that Python code can be easily > > optimized to run 30x faster. > > See PyPyhttp://codespeak.net/pypy/for a JIT comiler for python. > Although it is in the research phase, but worth taking a look at. > > Matt You need to check-out a project called Psyco (forerunner for pypy). I was able to get almost 2x better performance by adding 3 lines of code for Psyco. See also: http://psyco.sourceforge.net/download.html I am rather amazed ! Psyco was able to give much better performance above and beyond the already optimized Python code without negatively impacting performance during its analysis at runtime. From lorenzo.digregorio at gmail.com Fri Sep 14 08:38:11 2007 From: lorenzo.digregorio at gmail.com (Lorenzo Di Gregorio) Date: Fri, 14 Sep 2007 05:38:11 -0700 Subject: "once" assigment in Python In-Reply-To: <46ea4381$0$15390$4c368faf@roadrunner.com> References: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> <46ea4381$0$15390$4c368faf@roadrunner.com> Message-ID: <1189773491.560250.205580@y42g2000hsy.googlegroups.com> Thank you very much for your suggestions! I'll try in the next days to elaborate a bit on the last two ones. By the way, the "once" assignment is not that evil if you use it for hardware modeling. Most hardware models look like: wire1 = function() instance component(input=wire1,output=wire2) result = function(wire2) When employing Python it's pretty straightforward to translate the instance to an object. instance = Component(input=wire1,output=wire2) Then you don't use "instance" *almost* anymore: it's an object which gets registered with the simulator kernel and gets called by reference and event-driven only by the simulator kernel. We might reuse the name for calling some administrative methods related to the instance (e.g. for reporting) but that's a pretty safe thing to do. Of course all this can be done during initialization, but there are some good reasons (see Verilog vs VHDL) why it's handy do be able to do it *anywhere*. The annoying problem was that every time the program flow goes over the assignment, the object gets recreated. Indeed Python itself is not a hardware modeling language, but I built some infrastructure to fill what I was missing and for quickly building up a functional prototype and testing some ideas Python is really excellent. Best Regards, Lorenzo From stefan.behnel-n05pAM at web.de Sat Sep 22 16:28:07 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 22 Sep 2007 22:28:07 +0200 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <874phou1pa.fsf@benfinney.id.au> <46f3708c$0$32593$426a74cc@news.free.fr> Message-ID: <46F57AD7.6050905@web.de> W. Watson wrote: > Bruno Desthuilliers wrote: >> W. Watson a ?crit : >>> How about in the case of MS Win? >>> >>> Ben Finney wrote: >>>> >>>> (Please don't top-post. Instead, reply below each point to which >>>> you're responding, removing quoted text irrelevant to your response.) >>>> >> >> Wayne, may I second Ben on his suggestion to stop top-posting ? > > Well, you may. Unfortunately, there are many NGs that do the opposite. Well, not this one. Stefan From rbonvall at gmail.com Sun Sep 16 01:21:31 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sat, 15 Sep 2007 22:21:31 -0700 Subject: subclass of integers In-Reply-To: <1189780201.692192.291010@k79g2000hse.googlegroups.com> References: <1189780201.692192.291010@k79g2000hse.googlegroups.com> Message-ID: <1189920091.529076.82100@d55g2000hsg.googlegroups.com> On Sep 14, 10:30 am, Mark Morss wrote: > I would like to construct a class that includes both the integers and > None. I desire that if x and y are elements of this class, and both > are integers, then arithmetic operations between them, such as x+y, > return the same result as integer addition. However if either x or y > is None, these operations return None. No need to create a new class: try: result = a * b except TypeError: result = None -- Roberto Bonvallet From simon at brunningonline.net Fri Sep 28 10:59:33 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 28 Sep 2007 15:59:33 +0100 Subject: Emailing the attachment created with the Quick Screenshots Script(Python + PIL) In-Reply-To: <000001c801de$b670c370$eafca8c0@tfccorp.intra> References: <000001c801de$b670c370$eafca8c0@tfccorp.intra> Message-ID: <8c7f10c60709280759r652feb88t602b31485effef18@mail.gmail.com> On 9/28/07, Mark Bratcher wrote: > > I tried the suggestion at the other end of this link without any luck. Does > anyone have a working script which will send the screenshot file created by > the Quick Screenshots Script (Python + PIL)? I receive errors like access > denied errors and not defined errors. Could you show us the code you are running, and the exact error messages that you get? This might be worth a look: . -- Cheers, Simon B. simon at brunningonline.net From mail at timgolden.me.uk Mon Sep 3 04:28:59 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 03 Sep 2007 09:28:59 +0100 Subject: Soemthing wrong w/ urllib module or something. In-Reply-To: References: Message-ID: <46DBC5CB.3040007@timgolden.me.uk> Lamonte Harris wrote: > Error Message in cmd: > Traceback (most recent call last): > File "wniamp_lastest5_playlist.py", line 25, in > response = urllib2.urlopen(request) > 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: abort')> > For some reason its not acting right when trying to run. I get that error > message and I never seen anything like it. My experience is that that error message represents the local firewall or virus scanner blocking your network activity. That said, it doesn't seem likely that your firewall is blocking activity on port 80 without your having noticed! Maybe the domain you're posting to is selectively blacklisted by your local firewall? To do the obvious, can you open a socket connection to the domain you're using? from socket import socket socket ().connect (("DOMAINHERE", 80)) or does it give you the same error? TJG From dotancohen at gmail.com Tue Sep 11 20:49:49 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 12 Sep 2007 03:49:49 +0300 Subject: wx module? In-Reply-To: <880dece00709111745p2f816833j8f2cdaf2113633ee@mail.gmail.com> References: <880dece00709111745p2f816833j8f2cdaf2113633ee@mail.gmail.com> Message-ID: <880dece00709111749p725caf73pcbe8f8fc003cf431@mail.gmail.com> False alarm, found it, sorry... From pavlovevidence at gmail.com Sat Sep 22 04:51:31 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Sep 2007 04:51:31 -0400 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <46f45f02$0$15350$4c368faf@roadrunner.com> <7xps0bgq6p.fsf@ruckus.brouhaha.com> Message-ID: <46f4dd90$0$32490$4c368faf@roadrunner.com> On Fri, 21 Sep 2007 23:38:38 -0700, Paul Rubin wrote: > Carl Banks writes: >> Especially someone like an >> engineer (in the classical sense), who isn't building versatile >> software packages, won't need to resort to functional programming much. > > http://www.math.chalmers.se/~rjmh/Papers/whyfp.html >From the link: "Abstract As software..." That's it, lost me already. You ever see the kinds of programs mechanical engineers write? It isn't software. Carl Banks From pcooke at philc.net Mon Sep 3 14:17:54 2007 From: pcooke at philc.net (PhilC) Date: Mon, 03 Sep 2007 14:17:54 -0400 Subject: Applying transformation matrix to 3D vertex coordinates Message-ID: <5rjod3lih4mnupjcm2184k5no15eodlc8r@4ax.com> ''' ################################################ Task:- to apply a translation array to an array of 3D vertex coordinates to produce the resulting location of each vertices. Translation array and vertex coordinates taken from a Truespace COB file. The text in the COB file looks like this:- Transform -2.11786 -0.817596 0.946387 0.864939 0.405189 1.25484 2.11894 0.434915 -1.16679 1.9198 -0.981965 1.13894 0 0 0 1 World Vertices 8 -0.200000 -0.029486 -0.236313 0.200000 0.029486 -0.163687 -0.200000 0.370514 -0.282911 -0.200000 0.370514 0.117089 -0.200000 -0.029486 0.163687 0.200000 0.029486 0.236313 0.200000 0.429486 -0.210286 0.200000 0.429486 0.189714 ############################################### ''' # script start import Numeric transArray = Numeric.array(( (-2.11786, -0.817596, 0.946387, 0.864939), (0.405189, 1.25484, 2.11894, 0.434915), (-1.16679, 1.9198, -0.981965, 1.1389), (0, 0, 0, 1) )) # a "1" added to the end of each set of vertix coordinates vertArray = Numeric.array(( (-0.200000, -0.029486, -0.236313, 1), (0.200000, 0.029486, -0.163687, 1), (-0.200000, 0.370514, -0.282911, 1), (-0.200000, 0.370514, 0.117089, 1), (-0.200000, -0.029486, 0.163687, 1), (0.200000, 0.029486, 0.236313, 1), (0.200000, 0.429486, -0.210286, 1), (0.200000, 0.429486, 0.189714, 1) )) print transArray print "" print vertArray print "" transArray = Numeric.reshape(transArray,(4,4)) vertArray = Numeric.reshape(vertArray,(4,8)) print Numeric.matrixmultiply(transArray,vertArray) # script end ''' ################################################################## Result:- [[ 0.5708016 0.10309048 0.70481144 -1.12413 0.1022124 0.03400637 0.63866924 -1.12413 ] [-0.6688108 0.57729922 -0.19537307 4.213884 0.3408408 0.72615216 0.66384632 4.213884 ] [ 0.273571 1.26381257 -0.66763452 0.909945 -0.585931 1.13709619 0.39979 0.909945 ] [ 0.2 0.429486 -0.210286 1. 0.2 0.429486 0.189714 1. ]] Am I going in the right direction? What do I do with the result? :) Thanks, PhilC ''' From kar1107 at gmail.com Sun Sep 23 02:58:02 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Sun, 23 Sep 2007 06:58:02 -0000 Subject: subprocess -popen - reading stdout from child - hangs In-Reply-To: <1190518129.356844.242710@19g2000hsx.googlegroups.com> References: <1190518129.356844.242710@19g2000hsx.googlegroups.com> Message-ID: <1190530682.420121.31520@y42g2000hsy.googlegroups.com> On Sep 22, 8:28 pm, "gregpin... at gmail.com" wrote: > Let's say I have this Python file called loop.py: > > import sys > print 'hi' > sys.stdout.flush() Add sys.stdout.close() > while 1: > pass > > And I want to call it from another Python process and read the value > 'hi'. How would I do it? > > So far I have tried this: > > >>> proc = subprocess.Popen('python /home/chiefinnovator/loop.py',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE) > >>> proc.stdout.read() > > But it just hangs at read() > > proc.communicate() also just hangs. What am I doing wrong? Please > advise. Since your loop.py is still alive and hasn't closed its stdout, the caller continues to wait for EOF (it doesn't know if loop.py is done generating all its output) Karthik > > Thanks, > > Greg From jakub.piotr.nowak at gmail.com Thu Sep 27 07:31:19 2007 From: jakub.piotr.nowak at gmail.com (Jakub P. Nowak) Date: Thu, 27 Sep 2007 11:31:19 -0000 Subject: ANN: RuPy 2008 Python & Ruby Conference Message-ID: <1190892679.411344.282060@w3g2000hsg.googlegroups.com> RuPy 2008 Python & Ruby Conference Poznan, Poland April 12-13, 2008 -- Call for speakers RuPy is a Ruby and Python conference. Held for the first time in April 2007 it gathered enthusiasts from Poland and other countries. The idea behind the conference was to liven up the Ruby and Python community and make these technologies more popular in Europe. The first conference was a middle-sized one but came out as a huge success. We believe it was a great experience for both attendees and speakers. RuPy 2008 committee is looking for speakers willing to present a Ruby/Python related subject. If you have an interesting talk in mind go ahead and submit a talk proposal. The talk proposal should include a talk title, brief introduction and your short resume/biography. To our invited speakers we offer free accommodation, full board and possibility to interact with a very lively IT community. You are also free to participate in all the extra events - last year's 'Geek party' turned out great! You can also support us by linking to this site and informing all your friends about the event and the possibility to submit a talk proposal. Potential presenters should submit an abstract to: talks at rupy.eu by December, 31th 2007 for consideration. If you have any special presentation needs, let us know. For more details check our site: http://www.rupy.eu Best regards, -- Jakub P. Nowak RuPy Committee From kyosohma at gmail.com Fri Sep 21 13:42:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 21 Sep 2007 17:42:49 -0000 Subject: TRying to import files from my folder not pythons lib folder In-Reply-To: <1190395964.541835.114350@50g2000hsm.googlegroups.com> References: <1190395964.541835.114350@50g2000hsm.googlegroups.com> Message-ID: <1190396569.732154.234270@r29g2000hsg.googlegroups.com> On Sep 21, 12:32 pm, "tedpot... at gmail.com" wrote: > Hi, > > I'm trying to create my own lib of functions, but it seems like I can > only import them if they are in pythons lib folder. > > Example > I have a folder called > K:\mypython > > Now in the interactive python shell I type > Import k:\mypython\listall > And get a error on : > > If I store listall.py in pythons lib folder and type > Limport listall > > It works fins. > > Can I create my own library of functions and store them in a separate > dir???? > > Also I try to creat a folder in pythomns lib folder and that did not > work > > Help > -Ted One workaround is to do to this: import sys sys.path.append(r'K:\mypython') import listall You can also add your path to the .pth file, but I've never done that, so I can't tell you how. Hope that helps! Mike From deets at nospam.web.de Wed Sep 26 10:10:01 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Sep 2007 16:10:01 +0200 Subject: Packaging and dependencies References: <87ejgmklep.fsf@benfinney.id.au> <878x6ukkvq.fsf@benfinney.id.au> <5luhb0Faal8aU1@mid.uni-berlin.de> <87zlz9kfw3.fsf_-_@benfinney.id.au> Message-ID: <5lv7hpFak8ueU1@mid.uni-berlin.de> > Agreed, but until we reach the ideal situation where everybody is using > the same package dependency system what's your practical solution? > "Self-contained" has the merit that nobody else's changes are going to > bugger about with my application on a customer's system. The extra disk > space is a small price to pay for that guarantee. Couldn't have summed up that better. As much as I loathe Java for a variety of reasons, and as much as it's CLASSPATH-issues suck especially in larger projects that have _interproject-dependency-troubles_ (ever felt the joy of having the need for several XML-parsers to be available in your AppServer?) - the fact that one has to and can compose the CLASSPATH explicitly for each app is often an advantage. And I don't mind the extra diskspace - that's usually eaten by media files of dubious origins, not by _code_ that someone has written & packaged up... Diez From cjw at sympatico.ca Fri Sep 28 17:03:23 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 28 Sep 2007 17:03:23 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191007754.740566.137510@n39g2000hsh.googlegroups.com> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> Message-ID: <46FD6C1B.3010503@sympatico.ca> TheFlyingDutchman wrote: >> Or bind resources of these pocket protectors that otherwise would lead to >> answers for people that do seek enlightment... > > I don't think it would be correct to characterize my posts as not > seeking enlightenment. I do also happen to voice my opinion which > seems appropriate since this can be characterized as a discussion > group. It theoretically is possible for a discussion group to tolerate > opinions that diverge from the majority. +1 > > One issue I have with this group and that I encountered many years ago > in the Perl group is that there is no separate group > comp.lang.python.beginner where you can ask questions without getting > hit with RTFM! and the like. > From paul.hankin at gmail.com Fri Sep 21 03:48:42 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 21 Sep 2007 07:48:42 -0000 Subject: executing list of methods (and collecting results) In-Reply-To: References: Message-ID: <1190360922.144890.57800@19g2000hsx.googlegroups.com> On Sep 21, 12:26 am, Gerardo Herzig wrote: > def collect_validators(self): > v_dict = { 'is_really_a_number': is_really_a_number, > 'is_even': is_even, > 'is_greater_than_zero', is_greater_than_zero > } > > for name, meth in v_dict.items(): > result = meth() > if result: yield name Are these validators actually methods rather than functions? If so, you should write something like this: def collect_validators(self): methods = ['is_really_a_number', 'is_even', 'is_greater_than_zero'] return (m for m in methods if getattr(self, m)()) -- Paul Hankin From fakeaddress at nowhere.org Tue Sep 18 23:44:52 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 18 Sep 2007 20:44:52 -0700 Subject: The meaning of a = b in object oriented languages In-Reply-To: References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> Message-ID: Jim Langston wrote: > Assignment operators in C++ should attempt to prevent two pointers poining > to the same memory location. Consier a simple class (untested): > > class Foo > { > public: > char* Data; > int DataSize; > Foo( int Size ): DataSize( Size ) { Data = new char[Size]; } > ~Foo() { delete Data[]; } > }; [...] > Foo& operator=( const Foo& rhs ) > { > delete[] Data; > Data = new char[rhs.DataSize]; > memcpy( Data, rhs.Data, rhs.DataSize ); > DataSize = rhs.DataSize; > } > > You can see that we have to manually do some things. We have to delete[] > our pointer, new a new buffer, copy the cotents, copy the DataSize over, > none of which the default assignment operator would of done. [...] > Incidently, there may be errors in the code I've shown here if you attempt > to compile it. Be forewarned. There's the "self-assignment" bug. See the popular C++ FAQ. Follow-ups to comp.lang.c++ -- --Bryan From mfmorss at aep.com Fri Sep 14 10:31:47 2007 From: mfmorss at aep.com (Mark Morss) Date: Fri, 14 Sep 2007 07:31:47 -0700 Subject: subclass of integers In-Reply-To: <1189780201.692192.291010@k79g2000hse.googlegroups.com> References: <1189780201.692192.291010@k79g2000hse.googlegroups.com> Message-ID: <1189780307.186365.129480@19g2000hsx.googlegroups.com> On Sep 14, 10:30 am, Mark Morss wrote: > I would like to construct a class that includes both the integers and > None. I desire that if x and y are elements of this class, and both > are integers, then arithmetic operations between them, such as x+y, > return the same result as integer addition. However if either x or y > is None, these operations return None. > > It's simple enough to construct a subclass of integers that behave in > this way: > > class Nint(int): > def __add__(self,other): > if (other != None): > return self+other > else: > return None > def __radd__(self,other): > if (other != None): > return other+self > else: > return None > #...and so forth > > However I have not been able to figure out how to make it so that > None, as well as an integer, could be an element of my class. My > preliminary impression is that I have to override int.__new__; but I > am uncertain how to do that and have been unable to find anything on > the web explaining that. Indeed I haven't been able to find much > about __new__ at all. Overriding this method of built-in classes > seems to be quite unusual. > > I would very much appreciate anyone's help. I meant of course that arithmetic operations between integer elements would return the same result as the corresponding integer operations, not necessarily addition. From gagsl-py2 at yahoo.com.ar Fri Sep 28 00:23:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Sep 2007 01:23:25 -0300 Subject: comparing elements of a list with a string References: <1190734785.439839.303030@50g2000hsm.googlegroups.com> <1190889848.653434.178450@g4g2000hsf.googlegroups.com> Message-ID: En Thu, 27 Sep 2007 07:44:08 -0300, Shriphani escribi?: > def listAllbackups(filename): > list_of_backups = glob(home+'/Desktop/backupdir/*%s*'%filename) > for element in list_of_back: > if element.find(file) != -1: > date_components = element.split('-')[-4:-1] > date = str(date_components[0]) + ":" + str(date_components[1]) + > ":" + str(date_components[2]) > time = element.split('-')[-1] > yield (date, time) > print listAllbackups('fstab') > > > I ran it in the terminal and I got: > > > > Why does it do that and not just print out all the values of (date, > time) Because listAllbackups is a generator function: each time someone asks it the next value, it runs until the "yield" statement, and pauses. Next time execution continues from the same point. You have to iterate over it. Try: for date,time in listAllbackups('fstab'): print date,time or items = list(listAllbackups('fstab')) print items -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Sep 26 08:31:00 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 26 Sep 2007 14:31:00 +0200 Subject: Tracking memory usage and object life time. References: <1190808386.571152.103710@22g2000hsm.googlegroups.com> Message-ID: <5lv1nuFadb95U1@mid.individual.net> Berteun Damman wrote: > When I run a test, I disable the garbage collection during the > test run (as is adviced), but just before starting a test I > instruct the garbage collector to collect. Running the test > without disabling the garbage collect doesn't show any difference > though. Did you check the return value of gc.collect? Also, try using other "insight" facilities provided by the gc module. > Where possible I explicitly 'del' some of the larger data > structures that have been created after I don't need them anymore. You cannot "del" structures, you only "del" names. Objects are deleted when they are not bound to any names when and if the garbage collector "wants" to delete them. > I furthermore don't really see why there would be references to > these larger objects left. (I can be mistaken of course). Be sure to check for cyclic references, they can be a problem for the GC. Regards, Bj?rn -- BOFH excuse #343: The ATM board has run out of 10 pound notes. We are having a whip round to refill it, care to contribute ? From brown at esteem.com Thu Sep 6 18:36:44 2007 From: brown at esteem.com (Tom Brown) Date: Thu, 6 Sep 2007 15:36:44 -0700 Subject: why should I learn python In-Reply-To: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: <200709061536.45824.brown@esteem.com> On Thursday 06 September 2007 14:32, windandwaves wrote: > Can someone tell me why I should learn python? I am a webdeveloper, > but I often see Python mentioned and I am curious to find out what I > am missing out on. Ease of develpment. I write everything I can in python. If I can't do it in python, I throw a fit and find a way to do it in python. :) I developed in assembly, C, C++, Prolog and Delphi. Python has been by far the easiest to develop in. Some people might say it is not "real programming" because it is so easy. Whatever. If you wan't real programming, do it in assmebly. If you want to get a lot done while having a lot of fun doing it, do it in python. Tom From whamil1 at entergy.com Tue Sep 11 12:59:29 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 11 Sep 2007 11:59:29 -0500 Subject: Excel process still running after program completion. In-Reply-To: <1189525558.721174.198370@19g2000hsx.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB3E@LITEXETSP001.etrsouth.corp.entergy.com> > From: Chris > > I have a python script that is driving Excel and using the win32com > module. However, upon program completion there's still an Excel.exe > process running in the background that I must terminate through Task > Manager. Reading up on other threads indicate that maybe I still have > some Excel objects referenced within my code. Is this why the process > doesn't terminate? > > The related (I hope) parts of my code is here. > > x1App = Dispatch("Excel.Application") > Book1 = x1App.Workbooks.Open(ExcelLogPath+"\\outputLog-template.xls") > x1App.Visible = 1 > for sheets in Book1.Worksheets: > if sheets.Name == file_name: > sheetExists = True > if sheetExists != True: > activeSheet = > Book1.Worksheets.Add(After=Book1.Worksheets(1)) > activeSheet.Name = file_name > testNum[file_name] = 0 > Book1.Worksheets(file_name).Select() > Book1.ActiveSheet.Cells(1+(testNum[file_name]*20),1).Value = "Original > File Name" > Book1.ActiveSheet.Cells(2+(testNum[file_name]*20),1).Value = > file_name > Book1.ActiveSheet.Pictures().Insert(output).Select() > Book1.SaveAs(Filename=path) > x1App.ActiveWorkbook.Close(SaveChanges=0) > x1App.Quit() > del x1App > del Book1 > del activeSheet > > What am I missing? > In my Excel projects, I terminate it with: xlBook.Close() xlApp.Quit() I haven't had a problem with Excel staying open after the program ends. (On a tangent, I want to find the person who thought it was a good idea to use the same symbol in a font for 1, l, and I and do some unpleasant things.) -- -Bill Hamilton From gherron at islandtraining.com Thu Sep 27 13:38:39 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 27 Sep 2007 10:38:39 -0700 Subject: True of False In-Reply-To: <1b54228d0709271012h5658aef8rce2fbf40e6231a59@mail.gmail.com> References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> <1190912324.363127.26100@r29g2000hsg.googlegroups.com> <1b54228d0709271012h5658aef8rce2fbf40e6231a59@mail.gmail.com> Message-ID: <46FBEA9F.20103@islandtraining.com> Richard Thomas wrote: > On 27/09/2007, Casey wrote: > >> On Sep 27, 12:48 pm, "Simon Brunning" >> wrote: >> >>> On 9/27/07, kou... at hotmail.com wrote: >>> >>> >>>> I tried writing a true and false If statement and didn't get >>>> anything? I read some previous posts, but I must be missing >>>> something. I just tried something easy: >>>> >>>> a = ["a", "b", "c", "d", "e", "f"] >>>> >>>> if "c" in a == True: >>>> Print "Yes" >>>> >>>> When I run this, it runs, but nothing prints. What am I doing wrong? >>>> >>> Just use >>> >>> if "c" in a: >>> >>> and all will be well. The True object isn't the only truthy value in >>> Python - see . >>> >> I would recommend the OP try this: >> >> run the (I)python shell and try the following: >> >> >>>>> a = [x for x in "abcdefg"] >>>>> a >>>>> >> ['a','b','c','d','e','f','g'] >> >>>>> "c" in a >>>>> >> True >> >>>>> "c" in a == True >>>>> >> False >> >>>>> ("c" in a) == True >>>>> >> True >> >> The reason your conditional failed is that it was interpreted as "c" >> in (a == True) which is False. >> the "==" operator binds at a higher precedence level than the "in" >> operator, just as multiplication >> binds higher than addition >> >> > > Actually it evaluates '("c" in a) and (a == True)'. You can check like so: > > import dis > a = list("abcdef") > dis.dis(lambda: "c" in a == True) > > And just follow the bytecode operations. > Yikes. So I did that and you're correct. I've always looked at chained comparisons with mild suspicion. Now I guess that suspicion is justified. Interpreting a -- Richard. > > >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> From chris.olekas at gmail.com Tue Sep 11 11:45:58 2007 From: chris.olekas at gmail.com (Chris) Date: Tue, 11 Sep 2007 08:45:58 -0700 Subject: Excel process still running after program completion. Message-ID: <1189525558.721174.198370@19g2000hsx.googlegroups.com> I have a python script that is driving Excel and using the win32com module. However, upon program completion there's still an Excel.exe process running in the background that I must terminate through Task Manager. Reading up on other threads indicate that maybe I still have some Excel objects referenced within my code. Is this why the process doesn't terminate? The related (I hope) parts of my code is here. x1App = Dispatch("Excel.Application") Book1 = x1App.Workbooks.Open(ExcelLogPath+"\\outputLog-template.xls") x1App.Visible = 1 for sheets in Book1.Worksheets: if sheets.Name == file_name: sheetExists = True if sheetExists != True: activeSheet = Book1.Worksheets.Add(After=Book1.Worksheets(1)) activeSheet.Name = file_name testNum[file_name] = 0 Book1.Worksheets(file_name).Select() Book1.ActiveSheet.Cells(1+(testNum[file_name]*20),1).Value = "Original File Name" Book1.ActiveSheet.Cells(2+(testNum[file_name]*20),1).Value = file_name Book1.ActiveSheet.Pictures().Insert(output).Select() Book1.SaveAs(Filename=path) x1App.ActiveWorkbook.Close(SaveChanges=0) x1App.Quit() del x1App del Book1 del activeSheet What am I missing? From tomharding at inbox.com Tue Sep 18 08:03:41 2007 From: tomharding at inbox.com (Thomas Harding) Date: Tue, 18 Sep 2007 04:03:41 -0800 Subject: Using python to create windows apps that everyone can use? Message-ID: <7C008A37566.00000D2Atomharding@inbox.com> An HTML attachment was scrubbed... URL: From uymqlp502 at sneakemail.com Sun Sep 2 03:33:12 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Sun, 02 Sep 2007 00:33:12 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188709535.459572.22130@r34g2000hsd.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188709535.459572.22130@r34g2000hsd.googlegroups.com> Message-ID: <1188718392.682454.271110@k79g2000hse.googlegroups.com> On Sep 1, 10:05 pm, Russ wrote: > changing the language itself. Someone please correct me if I am wrong, > but I think PEP adds only to the libraries. I meant to write PEP 316, of course. From tim at timgolden.me.uk Thu Sep 6 13:41:49 2007 From: tim at timgolden.me.uk (Tim Golden) Date: Thu, 06 Sep 2007 18:41:49 +0100 Subject: Finding specific date ranges In-Reply-To: <1189099759.833051.253020@y42g2000hsy.googlegroups.com> References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> <1189099759.833051.253020@y42g2000hsy.googlegroups.com> Message-ID: <46E03BDD.1030403@timgolden.me.uk> > Thanks! I'll try it both ways and see if there's any appreciable > difference in speed, although since it will be packaged into an > executable, that may not be an issue anyway. > > Mike I honestly doubt there's any advantage to my approach, certainly not in terms of speed. It's really only if it happens to suit your mind better, or take advantage of structures you might already have in place, etc. TJG From hniksic at xemacs.org Wed Sep 19 07:16:08 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 19 Sep 2007 13:16:08 +0200 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> Message-ID: <87fy1a6h3b.fsf@mulj.homelinux.net> Michele Simionato writes: > On Sep 19, 12:36 pm, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >> The next class in the MRO *is* a superclass of the *instance*. Else it >> wouldn't be in the MRO !-) > > Bruno, there is no such a thing as a superclass in a multiple > inheritance world, and it is a very bad idea to continue to use that > terminology. Your arguments against the superclass term seem to assume that there is only a single superclass to a particular class. In the example you give in your essay, I would say that all of A, B, and T are superclasses of C, and Python's super correctly iterates over all of them. Wikipedia defines superclass as a "class from which other classes are derived", which seems perfectly valid for MI. From steve at holdenweb.com Thu Sep 27 08:27:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 08:27:50 -0400 Subject: URGENT REQUIREMENT FOR PYTHON DEVELOPERS In-Reply-To: <20070926221048.CD77B1E4009@bag.python.org> References: <20070926221048.CD77B1E4009@bag.python.org> Message-ID: <46FBA1C6.4020308@holdenweb.com> Krishna: You might want to consider reading http://www.python.org/community/jobs/howto/ and submitting these jobs to the Job Board. It's free. regards Steve kishore at mindriver-it.com wrote: > HI > > > > THIS IS KRISHNA KISHORE FROM MindRiver. We have an Urgent requirement > for Python Developers who have 5-7 YRS of EXP. > > > > SKILLS :PYTHON AND C/C++ > > > > WORK LOCATION : BANGALROE > > > > PLEASE REVERT US WITH YOUR UPDATED PROFILES. > > > > Thanks & Regards, > > Kishore Seethanraju |Senior Associate-People Consulting| MindRiver > Information Technologies Pvt. Ltd. > Suite# 512, 4th Floor and Suite # 104, Ground Floor ,Oxford Towers, 139, > Airport Road, Bangalore 560 008| Tel: +91.80.3052.1600 |Direct: > +91.80.3057.5799| Mobile: + 91.9901 96 1696 | Fax: +91.80.3057.5797| > Email: kishore at mindriver-it.com | Web > www.mindriver-it.com > > Information transmitted by this-mail is proprietary to MindRiver and / > or its Customers and is intended for use only by the individual or > entity to which it is addressed, and may contain information that is > privileged, confidential or exempt from disclosure under applicable law. > If you are not the intended recipient or it appears that this mail has > been forwarded to you without proper authority, you are notified that > any use or dissemination of this information in any manner is strictly > prohibited. In such cases, please notify us immediately at the above > mentioned telephone number or email to services at mindriver-it.com > and delete this mail from your > records. We believe this email to be virus free but do not warrant that > this is the case and we will not accept liability for any losses arising > from any virus being transmitted unintentionally by us' > > > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From hniksic at xemacs.org Mon Sep 17 18:56:02 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 18 Sep 2007 00:56:02 +0200 Subject: class that keeps track of instances References: Message-ID: <87myvkj3zx.fsf@mulj.homelinux.net> writes: > 1) New instance has to have a property called 'name' > 2) When instance is attemped to created, e.g., x=kls(name='myname'), and > there already exists an instance with obj.name =='myname', that > pre-existing instance is returned, instead of making new one. > 3) A class property 'all' for class gives me a list of all the > instances. So kls.all lets me iterates through all instances. > 4) When all the hard-link to an instance is deleted, the instance should > be deleted, just like an instance from any regular class does. class Meta(type): all = property(lambda type: type.cache.values()) class kls(object): __metaclass__ = Meta cache = weakref.WeakValueDictionary() def __new__(cls, name): if name in kls.cache: return kls.cache[name] self = object.__new__(cls) self.name = name kls.cache[name] = self return self >>> x = kls(name='foo') >>> x <__main__.kls object at 0xb7d5dc8c> >>> x is kls(name='foo') True >>> x is kls(name='bar') False >>> print kls.all # only one instance, 'bar' was short-lived [<__main__.kls object at 0xb7d5dc8c>] >>> x = 'somethingelse' >>> print kls.all [] > Assuming that I have to write it on my own, what should I do? I > tried to implement it using weakref.WeakValueDictionary and > metaclass, but instance doesn't disappear when I think it should > disappear. I am also wondering if it is easier to keeping > {name:id(obj)} would be a better solution. The problem is that, given just an ID, you have no way to get a hold of the actual object. From iclark at mail.ewu.edu Thu Sep 20 19:56:50 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Thu, 20 Sep 2007 16:56:50 -0700 Subject: HTTP Protocol Client In-Reply-To: <1190196612.082912.149690@v23g2000prn.googlegroups.com> References: <1190196612.082912.149690@v23g2000prn.googlegroups.com> Message-ID: welcomestocontact at gmail.com wrote: > h = httplib.HTTP('http://Google.com',80) This should be: h = httplib.HTTP('Google.com',80) And I certainly agree with the others, check out urllib*. Ian From gagsl-py2 at yahoo.com.ar Thu Sep 6 20:17:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Sep 2007 21:17:05 -0300 Subject: Getting original working directory References: <1658.1882-17889-1055570935-1189104422@seznam.cz> Message-ID: En Thu, 06 Sep 2007 15:47:02 -0300, rave247 rave247 escribi?: > If I could use os.getcwd() or save the value to some variable before > calling os.chdir() I would do it, believe me. However I can't because it > is the part of code where I can't do any changes. > > Also I do not agree that such thing is not possible because after python > script finishes its work, it naturally gets back into the original > location from where you started the script (in shell you are in the > original location after script finishes). So this information has to be > stored somewhere (probably in shell which runs the interpreter) and > there *must* be a way how to get it. Simply after calling os.chdir() > the original value doen't disappear, I think it just needs some nice > hack if python doesn't provide a way how to get it. The "current directory" is a per-process attribute managed by the OS. This is the greatest way to successfully remember the previous directory in a step by step recipe: - Setup a web service in a trusted server exposing an object implementing a queue-like interfase. Ensure your application has the right permissions to access the web service (you may have to open a port thru the firewall). This part is up to you. The poor man's solution is to use a SimpleXMLRPCServer daemon - that might be enough for starting, good because it's a full-Python solution but does not scale very well. - You will need a unique identifier. See this wikipedia article for some info . I'll assume you have a CreateGuid() function available (on Windows you can install the pywin32 package, get it from sourceforge). (A pid is not enough for use in a global service like this). - A few lines of code. Save as remember.py anywhere on your Python path (maybe lib/site-packages) from xmlrpclib import ServerProxy class Rememberer(object): _guid = _proxy = _queue = None def __init__(self, proxy_url): self.proxy_url = proxy_url def get_guid(self) "A GUID to to identify this rememberer" if self._guid is None: self._guid = CreateGuid() return self._guid guid = property(get_guid) def get_proxy(self) "xmlrpc proxy" if self._proxy is None: self._proxy = ServerProxy(self.proxy_url) return self._proxy proxy = property(get_proxy) def get_queue(self) """A queue object in the remote server, identified by self.guid""" if self._queue is None: self._queue = self.proxy.Queue(self.guid) queue = property(get_queue) def push(self, value): self.queue.push(value) def peek(self): return self.queue.peek() def make_remember(self, function, what_to_remember): @functools.wraps(function) def inner(*args, **kw): self.push(what_to_remember()) function(*args, **kw) return inner - The rememberer is globally accesible thru your url. You can use it with any process you wish, from anywhere in the world. Just make sure your GUID creator is good enough - as said on this recent post , you should arrange things to wait some time at system startup until the system has collected enough bits of entropy to generate a good identifier. - We are almost ready! The crucial part is to replace os.chdir with a wrapped version: import os, remember rememberer = remember.Rememberer("your.server.url") replacements = dict(chdir = ('make_remember', (os.chdir, os.getcwd)), prevdir = ('peek', None)) for attr, (fn, args) in replacements.iteritems(): if args: value = getattr(rememberer, fn)(*args) else: value = getattr(rememberer, fn) setattr(os, attr, value) Do that as early as possible; I'd put those lines in lib/sitecustomize.py (create that file if not already there). See http://docs.python.org/lib/module-site.html for info on the Python initialization sequence. - Now, you have a new function os.prevdir() which returns the directory that was current before the last call to os.chdir. The global web service holds a full stack of all the previous dirs, and you can extend the interfase to retrieve any value if you wish. Just remember the GUID used or you won't be able to retrieve anything. - Some bits are left as an exercise: there is no provision to remove items from the queue, no security enforced, and it's not thread safe (is it?). - The above code is untested, has no guarantees, standard disclaimers apply, use at your own risk, etc... Moreover, since all that mess can be replaced by a simple line like: original_dir = os.getcwd() or something similar near the top of your script, I would not even *attempt* to use it... -- Gabriel Genellina PS: Sorry! Could not resist... From erik at myemma.com Tue Sep 25 11:01:45 2007 From: erik at myemma.com (Erik Jones) Date: Tue, 25 Sep 2007 10:01:45 -0500 Subject: Confused about 'positive lookbehind assertion' In-Reply-To: <496954360709241938k6baf1009gc7cab215ad16b12f@mail.gmail.com> References: <496954360709241938k6baf1009gc7cab215ad16b12f@mail.gmail.com> Message-ID: On Sep 24, 2007, at 9:38 PM, Robert Dailey wrote: > Hi, > > I've been reading the python documentation on 'positive lookbehind > assertion' and I don't understand at all how it works. The python > docs give the following example: > > " (?<=abc)def will find a match in "abcdef", since the lookbehind > will back up 3 characters and check if the contained pattern matches." > > Can anyone emphasize more on what this RE operation does? Thanks. Have you actually tried it out? >>> import re >>> r = re.compile(r'(?<=abc)def') >>> m1 = r.search('aaaabcdeffff') >>> m1.group()'def' 'def' >>> m2 = r.search('bcdefff') >>> m2 == None True So, it matches 'def' but only if it is immediately preceded by 'abc'. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From rjagodic at gmail.com Mon Sep 24 11:48:07 2007 From: rjagodic at gmail.com (Ratko) Date: Mon, 24 Sep 2007 15:48:07 -0000 Subject: Can a base class know if a method has been overridden? In-Reply-To: <46f7d897$0$25150$426a74cc@news.free.fr> References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> <46f7d897$0$25150$426a74cc@news.free.fr> Message-ID: <1190648887.051630.168520@r29g2000hsg.googlegroups.com> > If your use case is to make sure a given ('abstract') method has been > overriden, the canonical solution is to raise NotImplementedError in the > base class's implementation I am not really interested in forcing the subclass to implement a method. I am interested in knowing *whether* it did implement it or not. > Else, this may be possible using a custom metaclass (or possibly just > specializing the __new__ method), but there may be better solutions > (depending on what you're really trying to do).. I have a base class EvtHandler that has methods defined to handle certain events. You then subclass from EvtHandler and override the methods for the events you want to receive. If a method has been overridden, the base class will automatically register for those events to make sure that they are even delivered to this handler (which is why I would need to know whether a method has been overridden or not). Of course, there are other ways of doing this which would require a bit more work from the subclass... I just thought this would be a neat "automatic" way of registering for events. For example: class EvtHandler: def __init__(self): if onKey is overridden: register_for_key_events() def onKey(self): pass class MyHandler(EvtHandler): def onKey(self): # do something here.... From kw at codebykevin.com Fri Sep 14 09:42:14 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 14 Sep 2007 09:42:14 -0400 Subject: Install Mac OS X - Idle doesn't show up In-Reply-To: References: Message-ID: <46EA8FB6.4040405@codebykevin.com> Dominique wrote: > Hello, > > Sorry bothering you with such a trivial problem. > > I installed python on a new mac at office. > It seems everything is fine: in the console, I access to python. > But I just can't start Idle. It seems to open but closes immediately (it appears > in the dock and closes immediately). > It is also impossible to open any .py file. > > I am sure some of you have a good idea of what to do (path,...). > > Thanks in advance > Dominique > How did you install/build Python? On the Mac, you really aren't supposed to start it from the terminal unless you are running it under X11 or are using a non-framework build. If you built it the standard Mac way, or if you use the binary installer from python.org, Idle is installed in /Applications/MacPython 2.5. Look there, and you should be able to drag the Idle icon to the dock. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From rjagodic at gmail.com Mon Sep 24 11:23:56 2007 From: rjagodic at gmail.com (Ratko) Date: Mon, 24 Sep 2007 15:23:56 -0000 Subject: Can a base class know if a method has been overridden? Message-ID: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> Hi all, I was wondering if something like this is possible. Can a base class somehow know if a certain method has been overridden by the subclass? I appreciate any ideas. Thanks, Ratko From bj_666 at gmx.net Sat Sep 22 02:26:39 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2007 06:26:39 GMT Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <46f45f02$0$15350$4c368faf@roadrunner.com> Message-ID: <5ljqsvF8gic1U1@mid.uni-berlin.de> On Fri, 21 Sep 2007 19:52:41 -0400, Carl Banks wrote: > First of all, let me say that I think "functions as first class data" is > helpful, but not crucial, to programming in Python, and there are many > people who simply don't need the lesson. Especially someone like an > engineer (in the classical sense), who isn't building versatile software > packages, won't need to resort to functional programming much. Of course you don't *need* functional programming as in "there's no way around it", but why are engineers such an exception!? I find the stuff in `itertools` very handy when it comes to filter, manipulate, group and aggregate data from large log files in ad hoc scripts. I'm not an engineer but I guess there are similar tasks with log files or measurement results. > For straightforward tasks, like sorting lists with a custom ordering, > functional progamming merely a convenience, and can be done without. ``for`` loops are just a convenience, you can do without. ;-) Ciao, Marc 'BlackJack' Rintsch From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Sep 13 14:59:06 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 13 Sep 2007 20:59:06 +0200 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <5ksoaoF5am8cU1@mid.individual.net> <1189701793.466307.93210@g4g2000hsf.googlegroups.com> Message-ID: <5ktfjqF5ctrvU2@mid.individual.net> TheFlyingDutchman wrote: > Here's a FAQ item where they refer to it as I think Python should > have done it - a special predefined variable: Maybe. Personally, I like it the way it is in Python. Why don't you make a preprocessor which accepts method declarations without "self" and fixes them? Regards, Bj?rn -- BOFH excuse #135: You put the disk in upside down. From ebgssth at gmail.com Mon Sep 17 01:08:46 2007 From: ebgssth at gmail.com (js) Date: Mon, 17 Sep 2007 14:08:46 +0900 Subject: A short question about non-ascii characters in list Message-ID: >>> print u"???" ??? >>> print [u"???"] [u'\xe4\xf6\xfc'] Python seems to treat non-ASCII chars in a list differently from the one in the outside of a list. I think this behavior is so inconvenient and actually makes debugging work harder. Is this an intentional? Is there any doc discussing about this? Thanks. From adurdin at gmail.com Tue Sep 25 18:01:06 2007 From: adurdin at gmail.com (Andrew Durdin) Date: Tue, 25 Sep 2007 23:01:06 +0100 Subject: Confused about 'positive lookbehind assertion' In-Reply-To: <1190753752.126335.205410@o80g2000hse.googlegroups.com> References: <496954360709241938k6baf1009gc7cab215ad16b12f@mail.gmail.com> <1190753752.126335.205410@o80g2000hse.googlegroups.com> Message-ID: <59e9fd3a0709251501o2102200fl1d137395d645aadf@mail.gmail.com> On 9/25/07, Karthik Gurusamy wrote: > > Any idea what this positive lookbehind achieves which can't be done > without it. > I remember cases where positive look-ahead is useful. > > In the above example, r.search('abcdef') does the job of ensuring > 'def' is preceded by 'abc'. AFAICT the only benefit I can see is that the lookbehind isn't captured, so (a) it's not included in match.group(n), and (b) match.start(), match.end(), and match.span() return the offsets of the bit you actually wanted to capture. OTOH, I often find the negative lookbehind (?!...) very useful indeed. Andrew From joel.hedlund at gmail.com Wed Sep 26 08:56:31 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 26 Sep 2007 14:56:31 +0200 Subject: Test-driven development and code size In-Reply-To: <87ejgmmgc2.fsf_-_@benfinney.id.au> References: <5ls95aF9pq3gU1@mid.uni-berlin.de> <87ejgmmgc2.fsf_-_@benfinney.id.au> Message-ID: > test-driven development merely means that you take that test case and > *keep it* in your unit test. Then, once you're assured that you will > find the bug again any time it reappears, go ahead and fix it. My presumption has been that in order to do proper test-driven development I would have to make enormous test suites covering all bases for my small hacks before I could getting down and dirty with coding (as for example in http://www.diveintopython.org/unit_testing). This of course isn't very appealing when you need something done "now". But if I understand you correctly, if I would formalize what little testing I do, so that I can add to a growing test suite for each program as bugs are discovered and needs arise, would you consider that proper test-driven development? (or rather, is that how you do it?) Thanks for taking the time! /Joel From anitnair at gmail.com Wed Sep 5 01:03:52 2007 From: anitnair at gmail.com (AniNair) Date: Tue, 04 Sep 2007 22:03:52 -0700 Subject: REGULAR EXPRESSION In-Reply-To: References: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> Message-ID: <1188968632.077355.199740@y42g2000hsy.googlegroups.com> On Sep 5, 4:35 am, Ricardo Ar?oz wrote: > Steve Holden wrote: > > AniNair wrote: > >> hi.. I am trying to match '+ %&/-' etc using regular expression in > >> expressions like 879+34343. I tried \W+ but it matches only in the > >> beginning of the string Plz help Thanking you in advance... > > > Perhaps you could give a few example of strings that should and > > shouldn't match? It isn't clear from your description what pattern you > > are trying to find. > > > regards > > Steve > > If it's operations between two numbers try : > r'([\d.]+?)\s*([-+/*%&])([\d.]+)' > It will give you 3 groups, first number, operation and second number > (caveat emptor). Hi.. Thanks alot for finding time to help a beginner like me. What I am trying to do is validate the input i get. I just want to take numbers and numbers only. So if the input is 23+1 or 2/3 or 9-0 or 7/0 , I want to find it using reg exp. I know there are other ways to do this... but i thought i will try this as i need to learn reg exp. I tried \D+ , \W+, and \D+|\W+ .. Thanks once again... From semenick at ix.netcom.com Fri Sep 14 10:00:23 2007 From: semenick at ix.netcom.com (PaulS) Date: Fri, 14 Sep 2007 10:00:23 -0400 Subject: where is help file? Message-ID: <13el4vvna6jildc@corp.supernews.com> new to Fedora7, typed python in interactive interpreter, then help(). Then modules to get a list of modules. Then module name to get info on a module but no help file. What is the help file name? Is there an environmental variable I have to set? Thanks, Paul From grante at visi.com Sat Sep 22 19:00:32 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 22 Sep 2007 23:00:32 -0000 Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> <13f99fediasg3ae@corp.supernews.com> <46f4c171$0$26367$4c368faf@roadrunner.com> <13fa49vie86ii1d@corp.supernews.com> <46f57841$0$15333$4c368faf@roadrunner.com> Message-ID: <13fb7kglt7har66@corp.supernews.com> On 2007-09-22, Carl Banks wrote: > On Sat, 22 Sep 2007 12:57:35 +0000, Grant Edwards wrote: >> On 2007-09-22, Carl Banks wrote: >>> Of course it would be. The reason I mention it is that automatic >>> convertibility is a key factor in whether a change can make it into >>> Python 3. >> >> It matters not whether fugly code is automatically generated or manually >> generated. It's still hard to read and maintain. > > By my understanding, it really doesn't matter that much. > > The transition tool's purpose is to allow a subset of 2.x code to run on > 3.x, so that developers don't have to maintain separate codebases to > support both. The 3.x code that is produced isn't intended to be read or > maintained. So no big deal if it's a little ugly. Eh? If you remove bitwise operators, then doing bitwise operations is going to be ugly, hard to write, and hard to read and maintain. I don't see what 2.x vs. 3.x vs. a "transition tool" has to do with it. -- Grant Edwards grante Yow! People humiliating at a salami! visi.com From jipksaman at gmail.com Mon Sep 24 03:48:45 2007 From: jipksaman at gmail.com (abdo911) Date: Mon, 24 Sep 2007 00:48:45 -0700 Subject: the AIM of LIFE Message-ID: <1190620125.417804.275690@g4g2000hsf.googlegroups.com> Allow me to share with you here some information about the AIM of LIFE . What is your purpose in life? What is the rationale behind our life? Why do we live in this life? These questions frequently intrigue people who try to find accurate answers. People provide different answers to these questions. Some people believe the purpose of life is to accumulate wealth. But one may wonder: What is the purpose of life after one has collected colossal amounts of money? What then? What will the purpose be once money is gathered? If the purpose of life is to gain money, there will be no purpose after becoming wealthy. And in fact, here lies the problem of some disbelievers or misbelievers at some stage of their life, when collecting money is the target of their life. When they have collected the money they dreamt of, their life loses its purpose. They suffer from the panic of nothingness and they live in tension and restlessness. Can Wealth Be an Aim? We often hear of a millionaire committing suicide, sometimes, not the millionaire himself but his wife, son, or daughter. The question that poses itself is: Can wealth bring happiness to one's life? In most cases the answer is NO. Is the purpose of collecting wealth a standing purpose? As we know, the five-year old child does not look for wealth: a toy for him is equal to a million dollars. The eighteen-year old adolescent does not dream of wealth because he is busy with more important things. The ninety-year old man does not care about money; he is worried more about his health. This proves that wealth cannot be a standing purpose in all the stages of the individual's life. Wealth can do little to bring happiness to a disbeliever, because he/ she is not sure about his fate. A disbeliever does not know the purpose of life. And if he has a purpose, this purpose is doomed to be temporary or self destructive. What is the use of wealth to a disbeliever if he feels scared of the end and skeptical of everything. A disbeliever may gain a lot of money, but will surely lose himself. Worshipping Allah as an Aim On the contrary, faith in Allah gives the believer the purpose of life that he needs. In Islam, the purpose of life is to worship Allah. The term "Worship" covers all acts of obedience to Allah. The Islamic purpose of life is a standing purpose. The true Muslim sticks to this purpose throughout all the stages of his life, whether he is a child, adolescent, adult, or an old man. Worshipping Allah makes life purposeful and meaningful, especially within the framework of Islam. According to Islam this worldly life is just a short stage of our life. Then there is the other life. The boundary between the first and second life is the death stage, which is a transitory stage to the second life. The type of life in the second stage a person deserves depends on his deeds in the first life. At the end of the death stage comes the day of judgment. On this day, Allah rewards or punishes people according to their deeds in the first life. The First Life as an Examination So, Islam looks at the first life as an examination of man. The death stage is similar to a rest period after the test, i. e. after the first life. The Day of Judgment is similar to the day of announcing the results of the examinees. The second life is the time when each examinee enjoys or suffers from the outcome of his behavior during the test period. In Islam, the line of life is clear, simple, and logical: the first life, death, the Day of Judgment, and then the second life. With this clear line of life, the Muslim has a clear purpose in life. The Muslim knows he is created by Allah. Muslims know they are going to spend some years in this first life, during which they have to obey God, because God will question them and hold them responsible for their public or private deeds, because Allah knows about all the deeds of all people. The Muslim knows that his deeds in the first life will determine the type of second life they will live in. The Muslim knows that this first life is a very short one, one hundred years, more or less, whereas the second life is an eternal one. The Eternity of the Second Life The concept of the eternity of the second life has a tremendous effect on a Muslims during their first life, because Muslims believe that their first life determines the shape of their second life. In addition, this determines the shape of their second life and this determination will be through the Judgment of Allah, the All just and Almighty. With this belief in the second life and the Day of Judgment, the Muslim's life becomes purposeful and meaningful. Moreover, the Muslim's standing purpose is to go to Paradise in the second life. In other words, the Muslim's permanent purpose is to obey Allah, to submit to Allah, to carry out His orders, and to keep in continues contact with Him through prayers (five times a day), through fasting (one month a year), through charity (as often as possible), and through pilgrimage (once in one's life). The Need for a Permanent Purpose Disbelievers have purposes in their lives such as collecting money and property, indulging in sex, eating, and dancing. But all these purposes are transient and passing ones. All these purposes come and go, go up and down. Money comes and goes. Health comes and goes. Sexual activities cannot continue forever. All these lusts for money, food and sex cannot answer the individual's questions: so what? Then What? However, Islam saves Muslims from the trouble of asking the question, because Islam makes it clear, from the very beginning, that the permanent purpose of the Muslim in this life is to obey Allah in order to go to Paradise in the second life. We should know that the only way for our salvation in this life and in the hereafter is to know our Lord who created us, believe in Him, and worship Him alone. We should also know our Prophet whom Allah had sent to all mankind, believe in Him and follow Him. We should, know the religion of truth which our Lord has commanded us to believe in, and practice it ... Those in search of truth Who have an open mind and heart, Islamic Education Foundation Welcome You. Objectives: - To Convey the message of Islam To Educate Muslims about Islam To keep in close contact with new Muslims. Activities: Offering Courses and presenting lectures about Islam in several languages. Teaching Islam and Arabic. Teaching new Muslims to receive the Holy Quran. Helping Non- Muslims embrace Islam and complete the required procedures I advise you visiting : http://www.islam-guide.com/ http://www.thetruereligion.org/ http://www.beconvinced.com/ http://www.plaintruth.org/ http://english.islamway.com/ http://www.todayislam.com/ http://www.prophetmuhammed.org/ http://www.islamtoday.net/english/ http://www.islamunveiled.org/ http://www.islamic-knowledge.com/ From kyosohma at gmail.com Fri Sep 7 09:35:58 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 07 Sep 2007 13:35:58 -0000 Subject: Finding specific date ranges In-Reply-To: References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> <1189122086.388859.146670@r34g2000hsd.googlegroups.com> Message-ID: <1189172158.598849.226000@o80g2000hse.googlegroups.com> On Sep 7, 2:47 am, Tim Golden wrote: > Zentrader wrote: > > On Sep 6, 7:56 am, kyoso... at gmail.com wrote: > >> December 31, 2006 January 13, 2007 # doesn't earn > >> January 14, 2007 January 27, 2007 # does earn > >> January 28, 2007 February 10, 2007 # doesn't > >> February 11, 2007 February 24, 2007 # does > > > Am I over simplifying if I say that since it appears to be a two week > > pay period, the date has to be greater than the 11th unless the first, > > or first and second, are on a weekend, in which case it would be > 12 > > or > 13? Or a reasonable facsimile thereof, depending on whether or > > not the two week period is Saturday through Friday. > > I think it's one of those things where the neatest answer > could well depend on the sort of heuristic you mention. As > a rule, when I come across this kind of requirement, I tend > to put the most general solution in place, unless a *real* > optimisation is clearly called for. In my experience, this > makes it much easier for the next person who looks at the > code, typically years later, even if that's me! > > (This is has just happened to me this week, having to review > a date-related calculation to do the repost frequency of the > adverts my company deals with. I wrote the original code five > years ago, and commented it intelligently, but I *still* had > to work through the code twice when we had a problem with a > particular cycle!) > > TJG I think it's foolish NOT to comment code unless it's very well self- documented. Even then, a couple lines of comments can be helpful. I've had to translate a bunch of Kixtart code into Python and none of it was commented and it wasn't well formed code either. And I've had the same thing happen with code that's only a year old. I'll read it and then go "what the?!" It's just not possible to remember every line of code you write. I wish it was. Mike From sergio.correia at gmail.com Mon Sep 3 19:13:43 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Mon, 3 Sep 2007 18:13:43 -0500 Subject: Can you use -getattr- to get a function in the current module? Message-ID: This works: # Module spam.py import eggs print getattr(eggs, 'omelet')(100) That is, I just call the function omelet inside the module eggs and evaulate it with the argument 100. But what if the function 'omelet' is in the module where I do the getattr (that is, in spam.py). If I do any of this print getattr(spam, 'omelet')(100) print getattr('','omelet')(100) print getattr('omelet')(100) It wont work. Any ideas? Thanks, Sergio From ncoghlan at gmail.com Mon Sep 24 10:59:14 2007 From: ncoghlan at gmail.com (NickC) Date: Mon, 24 Sep 2007 07:59:14 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <46f79c75$0$30457$426a34cc@news.free.fr> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <46f79c75$0$30457$426a34cc@news.free.fr> Message-ID: <1190645954.381931.187210@y42g2000hsy.googlegroups.com> On Sep 24, 9:16 pm, Bruno Desthuilliers wrote: > Matthew Woodcraft a ?crit : > > One reason for the different syntax is that functions, unlike most > > other objects, know their own names (which can be shown in tracebacks > > and the like). > > Nope. They know *one* of their names - the one they've been given when > first instanciated. Which may or not be the name used to get at them... That's exactly the point - a function may be given many names through the assignment statement, just like any other data value. However, the *first* name given to a function (the one in the def statement) is special, as that is the name the function knows *itself* by. While a function *can* be treated like any other piece of data once you have a reference to one, the original statement does a lot more than a normal assignment does: - being within the scope of a function significantly alters name binding and lookup - return statements and yield statements are meaningful only within the scope of a function - you can attach decorators to a function definition - you can include a docstring in a function definition For the original poster, I suggest trying some of the other suggestions in this thread, where you skip the def statement and instead look at manipulating standard library functions like math.sin and math.cos. Using a dictionary to select a function to run may be a good trick to illustrate the usefulness of this technique (e.g. passing in a command line argument to choose a function to call to generate a test sequence) From akm at theinternet.com.au Fri Sep 28 11:38:17 2007 From: akm at theinternet.com.au (Andrew Milton) Date: Sat, 29 Sep 2007 01:38:17 +1000 Subject: [Zope] how do I test for the current item in an iteration In-Reply-To: <005b01c801e5$600ad3c0$0200a8c0@design4> References: <005b01c801e5$600ad3c0$0200a8c0@design4> Message-ID: <20070928153817.GI4840@camelot.theinternet.com.au> +-------[ kamal hamzat ]---------------------- | Dear All, | | I have this error after i added the if statement Time for you to do some reading of your own. That's three in less than an hour... -- Andrew Milton akm at theinternet.com.au From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 7 03:42:37 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 07 Sep 2007 09:42:37 +0200 Subject: why should I learn python In-Reply-To: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: <46e100e7$0$16831$426a34cc@news.free.fr> windandwaves a ?crit : > Can someone tell me why I should learn python? Really, I cannot see any reason why you should do such a thing. > I am a webdeveloper, I've seen this label is applied to a wide range of effective jobs, from "building static web pages with a WYSWIG editor not even knowing html" to "writing a full-blown web application server". > but I often see Python mentioned and I am curious to find out what I > am missing out on. One of the best programming languages around, suitable for almost anything except low-level stuff (system, drivers etc). From DouhetSukd at gmail.com Fri Sep 14 03:47:31 2007 From: DouhetSukd at gmail.com (DouhetSukd at gmail.com) Date: Fri, 14 Sep 2007 00:47:31 -0700 Subject: "once" assigment in Python In-Reply-To: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> References: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> Message-ID: <1189756051.834305.120500@w3g2000hsg.googlegroups.com> Agree that what you are looking for may not be a good idea. So make sure you don't shoot yourself in the foot with it. You should probably look into your problem some more. >>> def once(obj,attrname,value): ... if hasattr(obj,attrname): ... return ... else: ... setattr(obj,attrname,value) ... >>> class Foo: ... pass ... >>> foo = Foo() >>> once(foo,"a",1) >>> foo.a 1 >>> once(foo,"b",2) >>> foo.a 1 >>> def m1(self): ... print "i am m1" ... >>> def m2(self): ... print "i am m2" ... >>> once(Foo,"mx",m1) >>> foo.mx() i am m1 >>> once(Foo,"mx",m2) >>> foo.mx() i am m1 >>> This is very generic code, but you could make it specific to a class and an attribute. If so look into properties. class Foo2: def _setMyAttr(self,value): if hasattr(self,"_myAttr"): return self._myAttr = value def _getMyAttr(self): if not hasattr(self,"_myAttr"): return "somedefaultvalue" return self._myAttr myAttr = property(_getMyAttr,_setMyAttr) Note also : stay away from __setattr__ until you know what you are doing and you know when to use self.__dict__ assignments. Painful personal experiences for me. From paddy3118 at googlemail.com Wed Sep 5 16:28:17 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 05 Sep 2007 13:28:17 -0700 Subject: Text processing and file creation In-Reply-To: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> Message-ID: <1189024097.175349.221210@w3g2000hsg.googlegroups.com> On Sep 5, 5:13 pm, "malibus... at gmail.com" wrote: > I have a text source file of about 20.000 lines.>From this file, I like to write the first 5 lines to a new file. Close > > that file, grab the next 5 lines write these to a new file... grabbing > 5 lines and creating new files until processing of all 20.000 lines is > done. > Is there an efficient way to do this in Python? > In advance, thanks for your help. If its on unix: use split. If its your homework: show us what you have so far... - Paddy. From marco at yafd.de Sun Sep 16 06:46:43 2007 From: marco at yafd.de (Marco) Date: Sun, 16 Sep 2007 12:46:43 +0200 Subject: Free Python Ebook In-Reply-To: <1189932765.100822.82720@r29g2000hsg.googlegroups.com> References: <1189932765.100822.82720@r29g2000hsg.googlegroups.com> Message-ID: <46ED0993.5090604@yafd.de> Hi George, > Please tell me from which website I will get the free Python Ebook. which one do you mean? I only know this one: http://diveintopython.org Bye, Marco PS: Sorry, hit the wrong button the first time ;-) From bg_ie at yahoo.com Mon Sep 10 05:28:57 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Mon, 10 Sep 2007 02:28:57 -0700 Subject: Enum class with ToString functionality Message-ID: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> Hi, I have the following class - class TestOutcomes: PASSED = 0 FAILED = 1 ABORTED = 2 plus the following code - testResult = TestOutcomes.PASSED testResultAsString if testResult == TestOutcomes.PASSED: testResultAsString = "Passed" elif testResult == TestOutcomes.FAILED : testResultAsString = "Failed" else: testResultAsString = "Aborted" But it would be much nicer if I had a function to covert to string as part of the TestOutcomes class. How would I implement this? Thanks, Barry From mensanator at aol.com Mon Sep 17 01:55:02 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 16 Sep 2007 22:55:02 -0700 Subject: Try this In-Reply-To: References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> Message-ID: <1190008502.986300.286280@22g2000hsm.googlegroups.com> On Sep 16, 9:27?pm, "Gabriel Genellina" wrote: > En Sun, 16 Sep 2007 21:58:09 -0300, mensana... at aol.com > escribi : > > >> I'm eagerly awaiting publication of your professional specification > >> for correctly detecting the encoding of an arbitrary stream of > >> bytes > > > The very presence of an algorithm to detect encoding is a bug. > > Files with they .txt extension should always be treated as ANSI > > even if they contain binary data. > > Why ANSI? Because that's the absence of encoding? > Because it's convenient to *you*? No, it's ANSI unless told otherwise. > What about the rest of the world that don't speak > English or even worse, don't use the Latin alpabet? When the rest of the world creates the next generation of computers, THEY can chosse the defaults. > What do you mean by "binary data"? 8-bit, ASCII is only 7-bit. > Notepad is not interpreting the file as > "binary", it's text, And will treat non-ASCII data as if it were ASCII. > but interpreted using the wrong encoding. So that's not a serious bug? To decide that a file is Unicode despite the absence of the appropriate markers? > > If you want to understand what happens here: The Unicode block for 'CJK > Unified Han' goes from U+4E00 to U+9FFF and is the largest block in the > basic plane, with more than 20000 code points. The previous block contains > the famous 64 hexagrams, and the previous block is 'CJK Unified Han > Extension A' ranging from U+3400 to U+4DBF. > Note that ASCII letters go from 0x41-0x5A and 0x61-7A, and the range > 0x4100-0x7AFF is totally contained inside the above Unicode blocks. > Reading a small phrase containing only ASCII letters as it were in UTF16 > would collapse each two letters into a single character, each character > being part of 'CJK Unified Han'. (Space and punctuation are allowed in odd > positions only, else the character would not belong to the Han blocks). > As every character goes into the same code block the heuristics concludes > that the text is some Estern language encoded in UTF16. But...but...Notepad doesn't have a UTF16 option. > This is the "Well you are speed" phrase interpreted as UTF16: > u'\u6557\u6c6c\u7920\u756f\u6120\u6572\u7320\u6570\u6465' How can you tell from that that it's UTF16? If there's something stored in addition to those 18 bytes, you're being misleading. > > > Notepad should never be > > allowed to try to decide what the encoding is if the the open > > dialog has the encoding set to ANSI. > > I'm using notepad.exe version 5.1.2600.2180 (XP SP2 fully updated) and > that's exactly what happens. I have to explicitely select Unicode in order > to see those Han characters. So which is worse, you having to tell it that it's Unicode or Notepad deciding on its own that a file is Unicode when it isn't. > > -- > Gabriel Genellina From grante at visi.com Mon Sep 3 11:18:41 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 03 Sep 2007 15:18:41 -0000 Subject: How do I get triangles from a vtkPolyData object? Message-ID: <13do9eh8dtqa236@corp.supernews.com> I posted this question to the vtk mailing list last week: I've been Googling and wandering through the class references most of the afternoon, but I can't figure out how to get the triangles out of the vtkPolyData that vtkDelaunay2D produces? I can get the vertex corredinates like this: delny = vtk.vtkDelaunay2D() delny.SetInput(profile) delny.SetTolerance(0.001) delny.Update() o = delny.GetOutput() vertexes = [o.GetPoint(i) for i in xrange(o.GetNumberOfPoints())] I can see that there are 84 triangles, and 'o' is a vtkPolyData object that has 84 cells and 84 polygons, so they obviously represent the triangles, but I can't figure out how to get something useful out of the cells or polys. I got multiple replies telling me that I need to make calls to o.GetNextCell(). The posters were even kind enough to include examples in C++ showing how to do a delaunay triangulation and retrieve the triangle info. However, the Python version of a vtkCellArray object (which is what's created as output from the Delaunay triangulation module) doesn't make the GetNextCell() (or GetCell()) method visible. It does have a GetNumberOfCells() object, and methods to set and insert cells, but how do I _get_ a cell? -- Grant Edwards grante Yow! .. I'll make you at an ASHTRAY!! visi.com From horpner at yahoo.com Thu Sep 13 12:01:48 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 13 Sep 2007 16:01:48 GMT Subject: recursion References: Message-ID: On 2007-09-13, Gigs_ wrote: > Can someone explain me this > > >>> def f(l): > if l == []: > return [] > else: > return f(l[1:]) + l[:1] # <= cant figure this, how is all sum at the end? In plain English, the above program says: The sum of the items in list l is zero if the list is empty. Otherwise, the sum is the value of the first item plus the sum of the rest of the items in the list. Well, it would say that if it weren't somewhat buggy. l[:1] doesn't evaluate to a number, but to a list containing one number, so the above program doesn't do what you say it does. It should read something like: def my_sum(seq): if len(seq) == 0: return 0 else: return seq[0] + my_sum(seq[1:]) The tough part of recursion is the leap of faith required to believe that it works. However, you can often use an inductive proof of correctness to help obviate the faith. Proof that my_sum(seq) computes the sum of the items in seq (this proof is modeled on proofs written by Max Hailperin, Barbara Kaiser, and Karl Knight, in _Concrete Abstractions_): Base case: my_sum(seq) terminates with value 0 when len(seq) is zero, because of the evaluation rules for if, len and ==. Induction hypothesis: Assume that my_sum(subseq) evaluates to the sum of all the items in subsequence of seq, where 0 <= len(subseq) < len(seq). Inductive step: Consider evaluating my_sum(seq) where the length of seq is greater than 0. This will terminate if my_sum(seq[1:]) terminates, and will have the value of seq[0] + my_sum(seq[1:]). Because seq[1:] evaluates to the subsequence of the rest of the items in seq (all except the first), and 0 <= len(subseq) < len(seq), we can assume by our induction hypothesis that my_sum(seq[1:]) does terminate, with a value equal to the sum of the the rest of the items in seq. Therefore, seq[0] + my_sum(seq[1:]) evaluates to seq[0] + the sum of all the items in seq[1:]. Because seq[0] + the sum of the rest of the items in seq equals the sum of all the items in seq, we see that my_sum(seq) does terminate with the correct value for any arbitrary length of seq, under the inductive hypothesis of correct operation for subsequences of seq. Conclusion: Therefore, by mathematical induction on the length of seq, my_sum(seq) terminates with the value of the sum of all the items in seq for any length of seq. But really I prefer the first first plain English version. ;) -- Neil Cerutti For those of you who have children and don't know it, we have a nursery downstairs. --Church Bulletin Blooper From steve at holdenweb.com Tue Sep 4 09:25:38 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Sep 2007 06:25:38 -0700 Subject: Setting Current Dir in Python In-Reply-To: <46DD5135.7060501@scivisum.co.uk> References: <000001c7eeec$d9341470$8b9c3d50$@net> <46DD5135.7060501@scivisum.co.uk> Message-ID: Tim Couper wrote: > "Non-ASCII character '\xef' in file" > > SandhirFileMonitor.py on line 356, > > This is reason for the failure .. you have a (probably accidentally placed) non-ascii (ie whose value is > 128) character on line 356, whose hex value is ef (decimal 259) . Solution: find that line and remove the character - or line. > Tim: You should know that any two-digit hexadecimal number is less than 255! >>> int("ef", 16) 239 regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From sjmachin at lexicon.net Fri Sep 14 08:53:07 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 14 Sep 2007 05:53:07 -0700 Subject: recursion In-Reply-To: <5kvbn3F5h7l3U1@mid.uni-berlin.de> References: <5kvbn3F5h7l3U1@mid.uni-berlin.de> Message-ID: <1189774387.132173.282890@r29g2000hsg.googlegroups.com> On Sep 14, 10:04 pm, Marc 'BlackJack' Rintsch wrote: > On Fri, 14 Sep 2007 13:40:17 +0200, Gigs_ wrote: > > sorry i think that i express wrong. having problem with english > > > what i mean is how python knows to add all thing at the end of recursion > > Because you have written code that tells Python to do so. ;-) > > > >>> def f(l): > > if l == []: > > return [] > > else: > > return f(l[1:]) + l[:1] > > > f([1,2,3]) > > > recursion1 f([2,3]) + [1] > > > recursion2 f([3]) + [2] or [2, 1]? > > > recursion3 f([]) + [3] or [3, 2, 1] > > Both alternatives in recursion 2 and 3 are wrong. You have to simply > replace the function invocation by its result which gives: > > f([1, 2, 3]) > r1 f([2, 3]) + [1] > r2 f([3]) + [2] + [1] > r3 f([]) + [3] + [2] + [1] > r4 [] + [3] + [2] + [1] > > And now the calls return: > > r3 [3] + [2] + [1] > r2 [3, 2] + [1] > r1 [3, 2, 1] > > > i dont get all this > > > >>> def f(l): > > if l == []: > > print l > > return [] > > else: > > return f(l[1:]) + l[:1] > > > >>> f([1,2,3]) > > [] > > [3, 2, 1] # how this come here? how python save variables from each > > recursion? > > There is not just one `l` but one distinct `l` in each call. > I reckon that what the OP wants is a simple explanation of how function calls use a stack mechanism for arguments and local variables, and how this allows recursive calls, unlike the good ol' FORTRAN IV of blessed memory. Perhaps someone could oblige him? I'd try but it's time for my beauty sleep :-) Good night all John From exhuma at gmail.com Tue Sep 18 03:33:11 2007 From: exhuma at gmail.com (exhuma.twn) Date: Tue, 18 Sep 2007 00:33:11 -0700 Subject: super, apply, or __init__ when subclassing? Message-ID: <1190100791.740269.62880@k79g2000hse.googlegroups.com> This is something that keeps confusing me. If you read examples of code on the web, you keep on seeing these three calls (super, apply and __init__) to reference the super-class. This looks to me as it is somehow personal preference. But this would conflict with the "There one way to do it" mind-set. So, knowing that in python there is one thing to do something, these three different calls must *do* domething different. But what exactly *is* the difference? ------------ Exampel 1: ----------------------------- class B(A): def __init__(self, *args): A.__init__(self, args) ------------ Exampel 2: ----------------------------- class B(A): def __init__(self, *args): apply( A.__init__, (self,) + args) ------------ Exampel 3: ----------------------------- class B(A): def __init__(self, *args): super(A,self).__init__(*args) From Shawn at Milochik.com Fri Sep 7 16:31:00 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Fri, 7 Sep 2007 16:31:00 -0400 Subject: Python and Cron In-Reply-To: References: Message-ID: <2dc0c81b0709071331v1718c84bj4a0bdda2ef7b79af@mail.gmail.com> Any chance your import statements aren't coming in properly due to something in your environment in Python that's not being inherited by your cron job? From simon at brunningonline.net Wed Sep 26 15:40:40 2007 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 26 Sep 2007 20:40:40 +0100 Subject: An Editor that Skips to the End of a Def In-Reply-To: <5lv3nnFacvnmU1@mid.individual.net> References: <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> <5lv3nnFacvnmU1@mid.individual.net> Message-ID: <8c7f10c60709261240j3e4b9df3w28f4265126d3d80b@mail.gmail.com> On 9/26/07, Bjoern Schliessmann > You definitely used the wrong languages :) > > http://worsethanfailure.com/Articles/The-Other-Kind-of-RPG.aspx Ah, but one edits RPG with SEU[1], Undo - who needs it? -- Cheers, Simon B. simon at brunningonline.net [1] http://tinyurl.com/yvra7l From zzbbaadd at aol.com Fri Sep 28 16:18:41 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 13:18:41 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <5m53aiFbfe3hU1@mid.uni-berlin.de> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> <5m53aiFbfe3hU1@mid.uni-berlin.de> Message-ID: <1191010721.990414.303520@22g2000hsm.googlegroups.com> On Sep 28, 12:34 pm, "Diez B. Roggisch" wrote: > TheFlyingDutchman wrote: > > >> Or bind resources of these pocket protectors that otherwise would lead to > >> answers for people that do seek enlightment... > > > I don't think it would be correct to characterize my posts as not > > seeking enlightenment. I do also happen to voice my opinion which > > seems appropriate since this can be characterized as a discussion > > group. It theoretically is possible for a discussion group to tolerate > > opinions that diverge from the majority. > > I would characterize > > """ > I like how someone here characterized decorators - those silly @ > things. They remind me of Perl. Not adding keywords for abstract and > static is like Perl not adding a keyword for class. > """ > > not as seeking enlightenment, but as pure trolling. Disqualifying features > without actually understanding them as "silly" certainly doesn't lie on one > of the many path's to enlightenment known man - which to my knowledge > usually require more humble approaches.... Some posts seek enlightenment, some voice opinions. Opinions aren't always voiced humbly. I don't think you will have to look far for examples of people other than myself not expressing opinions humbly. > > > One issue I have with this group and that I encountered many years ago > > in the Perl group is that there is no separate group > > comp.lang.python.beginner where you can ask questions without getting > > hit with RTFM! and the like. > > And I wish people that have no clue about the deeper workings of Python > wouldn't insist on commenting on these in inappropriate ways as above, but > instead try and _understand_ them before debunking them or suggesting > changes. > I will grant you that "silly" is too strong a word to use in a group of ardent users but I think it should be completely valid to gripe about the syntax at least once. From zzbbaadd at aol.com Thu Sep 27 21:29:28 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 27 Sep 2007 18:29:28 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: Message-ID: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> It seems that Python 3 is more significant for what it removes than what it adds. What are the additions that people find the most compelling? From steve at holdenweb.com Fri Sep 28 15:54:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 15:54:48 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191008702.579795.141180@r29g2000hsg.googlegroups.com> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> <1191008702.579795.141180@r29g2000hsg.googlegroups.com> Message-ID: <46FD5C08.7070603@holdenweb.com> George Sakkis wrote: > On Sep 28, 3:29 pm, TheFlyingDutchman wrote: > >> One issue I have with this group and that I encountered many years ago >> in the Perl group is that there is no separate group >> comp.lang.python.beginner where you can ask questions without getting >> hit with RTFM! and the like. > > Which shows once again that you're trying to break the world record of > being wrong in as many sentences as possible: > > http://mail.python.org/mailman/listinfo/tutor > > You would do yourself (and others) a favor by migrating there for a > few weeks or months. > > George > Hopefully with a side dish of alt.attitude.adjustment. It's not that we don't want you. it's just that you don't seem to realize how annoying you can be. n the other hand, if you *do* realize how annoying you can be then please leave now and never come back ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From thorsten at thorstenkampe.de Tue Sep 4 11:33:00 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 4 Sep 2007 16:33:00 +0100 Subject: FCGI app reloading on every request References: <46DCDE59.8060109@animats.com> Message-ID: * John Nagle (Mon, 03 Sep 2007 21:26:01 -0700) > I'm converting a web app from CGI to FCGI. The application works fine > under FCGI, but it's being reloaded for every request, which makes FCGI > kind of pointless. I wrote a little FCGI app which prints when the program is > loaded and when it gets a request. And indeed, the program gets reloaded for > each HTTP request. Something is probably misconfigured. But what? > [...] > On the Python side, I'm using Python 2.5 on Linux, with Alan > Saddi's "fcgi.py" module. Do you use fcgi.py or flup? Go for flup "What's the difference between flup's fcgi module and your previous fcgi.py? Feature-wise, very little, as I do try to keep both implementations in sync. The most significant difference is that flup's fcgi module uses thread pooling, fcgi.py simply starts a new thread for each connection/request. flup's code is refactored and modularized, to minimize duplicated code between all 6 servers." http://trac.saddi.com/flup/wiki/FlupFaq#Whatsthedifferencebetweenflups fcgimoduleandyourpreviousfcgi.py From orsenthil at gmail.com Sun Sep 16 06:05:23 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: 16 Sep 2007 10:05:23 GMT Subject: IPv6 name resolution using getaddrinfo Message-ID: Hi all, To get the hostname, I can use socket.gethostbyname() but that has an inherent limitation wherein does it not support IPv6 name resolution, and getaddrinfo() should be used instead. Looking up the socket.getaddrinfo() documentation, I come to know that The getaddrinfo() function returns a list of 5-tuples with the following structure: (family, socktype, proto, canonname, sockaddr) family, socktype, proto are all integer and are meant to be passed to the socket() function. canonname is a string representing the canonical name of the host. It can be a numeric IPv4/v6 address when AI_CANONNAME is specified for a numeric host. With this information, if I try something like this: >>> for res in socket.getaddrinfo('goofy.goofy.com', None, >>> socket.AI_CANONNAME): print res (2, 1, 6, '', ('10.98.1.6', 0)) (2, 2, 17, '', ('10.98.1.6', 0)) (2, 3, 0, '', ('10.98.1.6', 0)) In the output, I see the cannoname to be always blank ''. I am not getting the IPv4 or IPv6 address as a result of using getaddrinfo(). Am I making any mistake? What i am trying is a replacement function for socket.gethostbyname(hostname) which will work for both IPv4 and IPv6. # return hostbyname for either IPv4 or IPv6 address. Common function. def ipv6_gethostbyname(hostname): for res in socket.getaddrinfo(hostname,None, socket.AI_CANONNAME): fa, socktype, proto, canonname, sa = res return cannoname The above function does not seem to work. It returns blank value only. Any help/ pointers? -- O.R.Senthil Kumaran http://uthcode.sarovar.org From duncan.booth at invalid.invalid Thu Sep 27 05:13:42 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Sep 2007 09:13:42 GMT Subject: sorteddict PEP proposal [started off as orderedict] References: <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <1190805297.182232.116830@50g2000hsm.googlegroups.com> <1190815180.945099.248670@n39g2000hsh.googlegroups.com> <1190816657.574437.80980@g4g2000hsf.googlegroups.com> <1190820026.299569.110250@n39g2000hsh.googlegroups.com> <1190846656.770087.173230@19g2000hsx.googlegroups.com> <1190880801.795820.275070@50g2000hsm.googlegroups.com> Message-ID: Mark Summerfield wrote: > As for the license, while it is on PyPI, I'll leave it as GPL v 3. If > it was wanted for the standard library (and I can't see that ever > happening), I will happily change it to the one that is preferred for > Python modules. Ok, your choice, just be aware that by using such a restrictive license you will dissuade a lot of people from using your code. You've prevented your module being used in any existing projects with Python license, GPL v2, or probably any license other than GPL v3. From wgwigw at gmail.com Sun Sep 30 03:24:45 2007 From: wgwigw at gmail.com (momobear) Date: Sun, 30 Sep 2007 00:24:45 -0700 Subject: Balloon Taskbar Popup for Windows XP In-Reply-To: <1191062421.610473.13070@19g2000hsx.googlegroups.com> References: <1191062421.610473.13070@19g2000hsx.googlegroups.com> Message-ID: <1191137085.480380.296610@w3g2000hsg.googlegroups.com> On Sep 29, 6:40 pm, makko wrote: > Greetings, > I need to create a function that will produce a balloon popup in the > taskbar when called. Whats the shortest and easiest way to do this? > Thanks. > > regards, > Makko look at the website, maybe helpful to you. http://xoomer.alice.it/infinity77/main/freeware.html From bignose+hates-spam at benfinney.id.au Tue Sep 18 19:18:20 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Sep 2007 09:18:20 +1000 Subject: [ANN] Metatest 0.1.0 References: Message-ID: <87sl5by343.fsf@benfinney.id.au> Jonathan Fine writes: > Here's how to write some tests using Metatest. We can think of the > tests as an executable specification. > > from metatest.py.mymod import plus, Point > > # Function plus adds two numbers. > plus(2, 2) == 4 > plus(2, '', _ex=TypeError) This second example seems counterintuitive. Is '_ex' part of the public interface? If so, why does it follow the convention for "not part of the public interface" (i.e. it is named with an underscore)? -- \ "An eye for an eye would make the whole world blind." -- | `\ Mahatma Gandhi | _o__) | Ben Finney From aleax at mac.com Fri Sep 21 02:00:08 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 20 Sep 2007 23:00:08 -0700 Subject: Google and Python References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> Message-ID: <1i4rfyx.8vuc2j14j596uN%aleax@mac.com> Bryan Olson wrote: ... > TheFlyingDutchman asked of someone: > > Would you know what technique the custom web server uses > > to invoke a C++ app > > No, I expect he would not know that. I can tell you > that GWS is just for Google, and anyone else is almost > certainly better off with Apache. Or lighttpd, like YouTube (cfr ). > How does Google use Python? As their scripting-language > of choice. A fine choice, but just a tiny little piece. > > Maybe Alex will disagree with me. In my short time at > Google, I was uber-nobody. YouTube (one of Google's most valuable properties) is essentially all-Python (except for open-source infrastructure components such as lighttpd). Also, at Google I'm specifically "Uber Tech Lead, Production Systems": while I can't discuss details, my main responsibilities relate to various software projects that are part of our "deep infrastructure", and our general philosophy there is "Python where we can, C++ where we must". Python is definitely not "just a tiny little piece" nor (by a long shot) used only for "scripting" tasks; if the mutant space-eating nanovirus should instantly stop the execution of all Python code, the powerful infrastructure that has been often described as "Google's secret weapon" would seize up. The internal web applications needed to restore things, btw, would seize up too; as I already said I can't give details of the ones I'm responsible for (used by Google's network specialists, reliability engineers, hardware technicians, etc), but Guido did manage to get permission to talk about his work, Mondrian () -- that's what we all use to review code, whatever language it's in, before it can be submitted to the Google codebase (code reviews are a mandatory step of development at Google). Internal web applications are the preferred way at Google to make any internal functionality available, of course. Alex From http Sun Sep 9 13:09:51 2007 From: http (Paul Rubin) Date: 09 Sep 2007 10:09:51 -0700 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> <7xhcm4pl5m.fsf@ruckus.brouhaha.com> Message-ID: <7xsl5ndau8.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > > ... and it's to NSA's credit that SHA-1 held up for as long as it did. > But they have no convincing proposal for a successor. That means the gap > between the classified and non-classified state of the art has shrunk down > to insignificance. The successor is SHA-2. From bdesth.quelquechose at free.quelquepart.fr Sat Sep 8 13:00:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 08 Sep 2007 19:00:10 +0200 Subject: creating really big lists In-Reply-To: References: Message-ID: <46e59dcd$0$21897$426a74cc@news.free.fr> Delaney, Timothy (Tim) a ?crit : > Hrvoje Niksic wrote: > > >>Dr Mephesto writes: >> >> >>>I would like to create a pretty big list of lists; a list 3,000,000 >>>long, each entry containing 5 empty lists. (snip) > >>If you're building large data structures and don't need to reclaim >>cyclical references, I suggest turning GC off, at least during >>construction. > > This is good advice, but another question is whether you really want > such a list. You may well be better off with a database of some kind - > they're designed for manipulating large amounts of data. Hear hear... At least some sensible answer !-) From mcknight0219 at gmail.com Sun Sep 16 04:42:33 2007 From: mcknight0219 at gmail.com (Jimmy) Date: Sun, 16 Sep 2007 01:42:33 -0700 Subject: (wxPython) icon on panel Message-ID: <1189932153.859201.222370@o80g2000hse.googlegroups.com> hi,all! have you used 'dictionary' of linux, the program that rests on the panel as an icon, and when you click on the icon, it will display a window and do something. So i'm wondering how to achieve this. I guess it's a dialog window, right? but the crucial part is how to minimize the program to an icon on the panel and make it responsive to the click event. thanks in advance! From jorgen.maillist at gmail.com Fri Sep 7 12:49:12 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Fri, 7 Sep 2007 18:49:12 +0200 Subject: How to determine the bool between the strings and ints? In-Reply-To: <1189182688.290480.102350@o80g2000hse.googlegroups.com> References: <1189182688.290480.102350@o80g2000hse.googlegroups.com> Message-ID: <11e49df10709070949h185101c0gbec198a362b053e7@mail.gmail.com> Awesome! Thanks you! As for why caring if they are bools or not, I write True and False to the properties, the internal mechanism works like this so I need to make that distinction. Thanks again guys, - Jorgen ps. Sorry TheFlyingDutch for mailing you personally, I keep forgetting this mailinglist does not default back to the user list when replying ;-) From DustanGroups at gmail.com Sun Sep 16 13:35:51 2007 From: DustanGroups at gmail.com (Dustan) Date: Sun, 16 Sep 2007 17:35:51 -0000 Subject: where are the .pyc files? In-Reply-To: <1189963710.714191.74440@n39g2000hsh.googlegroups.com> References: <1189963710.714191.74440@n39g2000hsh.googlegroups.com> Message-ID: <1189964151.926924.104720@n39g2000hsh.googlegroups.com> On Sep 16, 12:28 pm, Summercool wrote: > so i have always heard of the .pyc files.... but for some reason i > don't see them on the Windows platform... when i have a program > called try.py and after running it for ages, i still don't have a > try.pyc file in my folder even if i turn the "show hidden file" to on. Try "import try". Ummm.... No, you can't. Rename the file to "exodomuzos.py", then "import exodomuzos". From bjorn.kempen at gmail.com Sat Sep 15 18:41:49 2007 From: bjorn.kempen at gmail.com (buffi) Date: Sat, 15 Sep 2007 22:41:49 -0000 Subject: problems using pythom tempfile module In-Reply-To: <1189894434.135052.283420@w3g2000hsg.googlegroups.com> References: <1189890699.807384.258580@o80g2000hse.googlegroups.com> <1189891458.583774.171030@22g2000hsm.googlegroups.com> <1189894434.135052.283420@w3g2000hsg.googlegroups.com> Message-ID: <1189896109.216802.125840@22g2000hsm.googlegroups.com> Pretend that you have a number that is always pointing somewhere in your temporary file. It starts a 0. If you then write "lalalala" (8 characters) it will point after these at position 8, so that you can write more stuff after your previous text later by calling write. The read method reads all the data from the current position of the "pointer" to the end of the file. If you simply call it after writing, you wont get anything since you are already at the end of the file. Therefore you "rewind" the pointer back to the start by calling seek which takes the position in the file to go to... your_file.seek(0) returns you to the start of the file to read all of its data - Bj?rn Kemp?n From conra2004 at yahoo.com Thu Sep 27 18:06:01 2007 From: conra2004 at yahoo.com (yadin) Date: Thu, 27 Sep 2007 15:06:01 -0700 Subject: developing an application Message-ID: <1190930761.625756.309830@50g2000hsm.googlegroups.com> hi! i was buiding an application using python...a program this was my first one...now that i got it working perfectly how can i put the bunch of files into one package? the user of the appliation will not know where to start? that is which file to click on in oder to start the program? thanks a lot From steve at holdenweb.com Tue Sep 18 12:14:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Sep 2007 12:14:33 -0400 Subject: can Python be useful as functional? In-Reply-To: <1190073045.618869.261290@k79g2000hse.googlegroups.com> References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Message-ID: Lorenzo Stella wrote: [...] > My question is: how can we call a language "functional" if it's major > implementation has a limited stack? Or is my code wrong? > So, which environment do you habitually use that provides an *unlimited* stack? You remind me of the conversation between the philosopher and an attractive lady whom he was seated next to at dinner. He asked her if she would sleep with him for a million dollars, to which she readily agreed. So he followed this by asking her if she'd sleep with him for a dollar. She replied: "No. Do you take me for a prostitutte?", to which his riposte was "We have already established that fact, and are now merely haggling about the price". You just don't like the specific limit that Python imposes. So increase it with sys.setrecursionlimit(). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From gheize at gmail.com Tue Sep 4 05:43:08 2007 From: gheize at gmail.com (Guillermo Heizenreder) Date: Tue, 04 Sep 2007 06:43:08 -0300 Subject: [pygtk] problem with TreeView + ListStore Message-ID: <1188898988.1080.0.camel@leinad-desktop> Hi list I'm developing a application for learn pygkt, and I need to know when a user selected or clicked one determinate row of my TreeView for shot another signal . Study the tutorial [1] I began to see the explanation that I see in the chapter 14.7. TreeView Signal and found one in particular "select-cursor-row", but I don't understood how implementing. Something like that. if user_selected_row: self.hbox_118.show() print "YES" NOTE: self.hbox_118 = wTree.get_widget("hbox118") Thank and Regard [1] http://www.pygtk.org/pygtk2tutorial/sec-TreeViewSignals.html P/D: my English it to bad, I'm a novice. -- Heizenreder Guillermo http://code.google.com/u/gheize/ From http Wed Sep 26 14:51:49 2007 From: http (Paul Rubin) Date: 26 Sep 2007 11:51:49 -0700 Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> <1190799759.367001.106400@r29g2000hsg.googlegroups.com> <87fy11lo22.fsf@mulj.homelinux.net> <1190804538.469582.96950@22g2000hsm.googlegroups.com> <1190814263.104358.158090@n39g2000hsh.googlegroups.com> Message-ID: <7xy7etnttm.fsf@ruckus.brouhaha.com> Mark Summerfield writes: > The sorteddict API that has emerged so far is (1) apart from the > constructor, everything is identical to dict, I don't see this as necessary, it's ok if it resembles dict as much as dbm does. > (2) the constructor takes the same args as sorted(), so if you want > to seed with a dict or with keywords you write > sorteddict(dict(a=1,b=2), ...), (or you could create a sorteddict > and use update() since that takes the same args as dict's > constructor). sorteddict could itself return a constructor: d = sorteddict(key=int).new((('12', 'a'), ('3', 'b'))) gives sorted version of {'3':'b', '12':'a'} From f.guerrieri at gmail.com Mon Sep 3 07:46:31 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 3 Sep 2007 13:46:31 +0200 Subject: So what exactly is a complex number? In-Reply-To: <46dbed49$0$30375$9b4e6d93@newsspool4.arcor-online.net> References: <451mq4-les.ln1@ozzie.tundraware.com> <46dbed49$0$30375$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <79b79e730709030446m1e02266doda061eef5415bbb9@mail.gmail.com> On 9/3/07, Wildemar Wildenburger wrote: > > Grzegorz S?odkowicz wrote: > > In fact, a proper vector in physics has 4 features: point of > > application, magnitude, direction and sense. > > > OK, help me out here: What 'direction' does |?> (a state-vector in > quantum mechanics) have? Also, doesn't sense directly follow from the > point of application. For instance, you can apply a force to a point and it can be "outward" or "inward". The direction of a state vector is completely specified by its decomposition (given finite norm and completeness of the basis), just like ordinary vectors. But since actually in quantum mechanics you are dealing with unit rays and everything is defined up to a phase (which could be relevant given the topic of this thread!)... I'd say that kets are not the most recommendable way to introduce the concept of vector, or of complex variables :-) francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sun Sep 16 11:49:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Sep 2007 11:49:15 -0400 Subject: Needless copying in iterations? In-Reply-To: <13epv3fnb6bak15@corp.supernews.com> References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> <13epv3fnb6bak15@corp.supernews.com> Message-ID: <46ED507B.2050106@holdenweb.com> Steven D'Aprano wrote: > On Sun, 16 Sep 2007 15:05:55 +1000, Ben Finney wrote: > >> Steven D'Aprano writes: >> >>> In *general* the compiler can't tell, but in specific cases it could. A >>> (hypothetical) optimizing compiler would tell the difference between: >>> >>> for item in alist[1:5]: >>> print item # no possible side-effects >> The 'print' statement converts the 'item' to a str. That conversion >> could, in a pathological case, have a side-effect (say, if the class of >> 'item' had an overridden '__str__' method with side effects), and the >> compiler can't know this isn't a pathological case. > > Fair enough... but I'm reminded of a rant by Joel Spolsky about GUI > design: > > '...programmers have tended to think that if users are allowed to resize > and move windows, they should have complete flexibility over where these > windows go, right down to the last pixel. After all, positioning a window > 2 pixels from the top of the screen is "equally likely" as positioning a > window exactly at the top of the screen.' > > http://www.joelonsoftware.com/uibook/fog0000000249.html > > (three quarters of the way down, in Chapter 7.) > > Maybe I'm being unfair, but it seems to me that the attitude is similar: > 'there's no point optimizing the common case of printing (say) ints > stored in a list, Just In Case the programmer wants the incredibly rare > case of setting sys.stdout to some wacky object that modifies the list > he's iterating over. It could happen.' > > *shrug* But apart from the occasional smart-alec who does it just to > demonstrate that it is possible, it probably never has. > > It seems to me that the "consenting adults" philosophy of Python doesn't > extend to the compiler, and perhaps it should. Maybe Python could > optimize common cases, and if developers wanted to do wacky things, let > them turn optimization off on a module-by-module basis. > > Or even function-by-function. Wouldn't it be nice to have decorators that > could optimize the functions they decorated? > No, it would be disastrous, unless you could manage to implement a mechanism that *told* you when the optimizations were playing havoc with your program's execution. The problem is that debugging only works if you can assume a deterministic environment. If you are going to put funky optimizations in that break determinism in "little-used" corner cases, then debugging the situations when the optimizations *do* affect program execution will be a complete pain. > >>> for item in alist[1:5]: >>> alist.append(item) # side-effects DON'T matter >> The compiler doesn't know that, at the time of invocation, >> 'alist.append' doesn't have side effects that matter. > > It might if it knows what type alist is, and how long it is (as Marc > Rintsch points out). That's why I used "alist" in my example rather than > "an_arbitrary_sequence". > But alist doesn't *have* a type, and static program analysis would have to be extensive to determine that it could only ever be of a specific type. > >> The compiler for a dynamic language like Python has very little absolute >> "no significant side-effect in these specific cases" guarantee of the >> kind you're assuming even in the cases you choose for contrast with the >> ones that *do* have significant side-effects. > > Yes, in general one might not be able to make those guarantees, but still > there are common cases where you can. That's how Psycho works. > Yes, but psycho doesn't use static program analysis but instead uses run-time environment examination to determine whether specific optimizations can be applied. > The point is rather moot, since CPython (and probably other Pythons) do > almost no optimizations. But just because Python is a dynamic language > doesn't mean there are no optimizations possible: Haskell is a dynamic > language, and there are optimizing compilers for it. Of course, it is > much simpler for Haskell, because of the type system it uses. > > The CPython compiler already does a couple of source-code optimizations > (ignores some unused strings; some constant folding) and at least one > runtime optimization (string concatenation is no longer _always_ slow): > > http://utcc.utoronto.ca/~cks/space/blog/python/ExaminingStringConcatOpt > > Because of its very nature, optimizing Python is hard. Even something as > simple as tail-call recursion optimization is verboten, because Guido > considers good stack traces more important than preventing stack > overflows in the first place: > > http://www.tratt.net/laurie/tech_articles/articles/tail_call_optimization > And who's to say he's wrong, especially since Python is intended to be an environment that's friendly to beginners. > Anyway, I'm not really complaining. I like Python, I'm grateful for the > work the Python-dev people have already done, and I'm in no position to > volunteer to write an optimizing compiler. And it may be that, regardless > of how smart you make the compiler, Python simply can't be optimized > because of design decisions made back in 1990-whatever when Guido first > started his grand plan. > There is some of that. The environment is so dynamic that even something as innocuous as attribute lookup can actually involve properties (for example) reading a relational database! I'm not saying that optimization under these circumstances is possible, but that it's much more difficult than is easily anticipated, and that the benefits to be gained might be less than you would think. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From software at ginstrom.com Fri Sep 14 01:27:46 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 14 Sep 2007 14:27:46 +0900 Subject: Setting stdout encoding In-Reply-To: References: <1189416350.069995.220250@w3g2000hsg.googlegroups.com><00e601c7f5fb$43d5ccf0$0203a8c0@MOUSE> Message-ID: <02dd01c7f68f$fc272ad0$0203a8c0@MOUSE> > On Behalf Of Gabriel Genellina > You should check that obj is an unicode object before calling > encode. > Strings should not be encoded. ... > __getattr__ is only called when the attribute has NOT been > found in the usual way, so checking for "write" is > unnecesary. Just return getattr(self.stdout, attr) always. Thanks a lot. Here is my modified class: import sys class OutStreamEncoder(object): """Wraps a stream with an encoder """ def __init__(self, outstream, encoding=None): self.out = outstream if not encoding: self.encoding = sys.getfilesystemencoding() else: self.encoding = encoding def write(self, obj): """Wraps the stream's output stream, encoding unicode strings with the specified encoding""" if isinstance(obj, unicode): self.out.write(obj.encode(self.encoding)) else: self.out.write(obj) def __getattr__(self, attr): """Delegate everything but write to the stream""" return getattr(self.out, attr) Regards, Ryan Ginstrom From zzbbaadd at aol.com Wed Sep 12 01:00:29 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 11 Sep 2007 22:00:29 -0700 Subject: Get the complete command line as-is In-Reply-To: <1189567985.089215.108250@k79g2000hse.googlegroups.com> References: <1189566000.793354.308420@19g2000hsx.googlegroups.com> <1189567985.089215.108250@k79g2000hse.googlegroups.com> Message-ID: <1189573229.875265.250340@d55g2000hsg.googlegroups.com> On Sep 11, 8:33 pm, TheFlyingDutchman wrote: > On Sep 11, 8:00 pm, wangzq wrote: > > > Hello, > > > I'm passing command line parameters to my browser, I need to pass the > > complete command line as-is, for example: > > > test.py "abc def" xyz > > > If I use ' '.join(sys.argv[1:]), then the double quotes around "abc > > def" is gone, but I need to pass the complete command line ("abc def" > > xyz) to the browser, how can I do this? > > > I'm on Windows. > > > Thanks. > > I'm on Solaris and this works for me: > > test.py '"abc def" xyz' > > print sys.arv[1] > > "abc def" xyz OK, now I'm on Windows XP and things aren't looking too good. It seems that \" will retain the quote marks but then the spaces get gobbled. But if you replace the spaces with another character: python.exe test.py \"abc#def\"#123 then: import sys commandLine = "".join(sys.argv[1:]) prints commandLine.replace('#',' ') gives: "abc def" 123 Don't know if you can use that technique or not. From bj_666 at gmx.net Mon Sep 24 15:02:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Sep 2007 19:02:51 GMT Subject: puzzled about floats References: Message-ID: <5lqfuqF95s07U6@mid.uni-berlin.de> On Mon, 24 Sep 2007 14:13:18 -0400, Neal Becker wrote: > from math import modf > > class nco (object): > def __init__ (self, delta): > self.delta = delta > self.phase = 0.0 > def __call__ (self): > self.phase += self.delta > f,i = modf (self.phase) > print modf (self.phase) > if (self.phase > 1.0): > self.phase -= 1.0 > return self.phase > > n = nco (0.1) > for x in xrange (100): > print '%.12f' % n() > > prints out > [...] > (0.99999999999999978, 0.0) <<< from modf > 1.000000000000 << from n() > > I'm baffled as to why 'print modf (self.phase)' prints out the first value, > but the result printed in the 2nd case is different. Without any precision > spec on the first print, an approximate float value was printed, but even > with %.12f, the second gives exactly 1.000.... Tuples are printed with calling `repr()` on the objects: In [144]: str(0.1) Out[144]: '0.1' In [145]: repr(0.1) Out[145]: '0.10000000000000001' In [146]: '%.12f' % 0.1 Out[146]: '0.100000000000' In [147]: '%.50f' % 0.1 Out[147]: '0.10000000000000000555111512312578270211815834045410' Ciao, Marc 'BlackJack' Rintsch From duncan.booth at invalid.invalid Sat Sep 29 07:39:23 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Sep 2007 11:39:23 GMT Subject: question about for cycle References: <1191062383.322949.55300@d55g2000hsg.googlegroups.com> Message-ID: Ant wrote: > On Sep 29, 11:04 am, "fdu.xia... at gmail.com" > wrote: > ... >> What should I do if I want the outer "for" cycle to continue or break >> ? If I put a "continue" or "break" in the inner cycle, it has no >> effect on the outer cycle. > ... > I guess to an extent it would depend on the exact situation as to > which of these is more suitable. Are there any other recommended > solutions to this? > I think the other Pythonic option you have missed is to convert the nested for loops into a single loop by writing a generator. def ranges(limit1, limit2): range1, range2 = range(limit1), range(limit2) for i in range1: for j in range2: yield i,j ... for i, j in ranges(10, 10): ... whatever ... if j==6: break From Bart.Peters at GEN.unimaas.nl Mon Sep 17 10:39:42 2007 From: Bart.Peters at GEN.unimaas.nl (Peters Bart (GEN)) Date: Mon, 17 Sep 2007 16:39:42 +0200 Subject: Simple elementtree question Message-ID: I have the exact same problem, rdf and elementtree -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.padoan at gmail.com Sat Sep 15 11:20:22 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Sat, 15 Sep 2007 12:20:22 -0300 Subject: How to avoid overflow errors In-Reply-To: <46eb6ad1$0$7493$4c368faf@roadrunner.com> References: <13em8vnr527rq20@corp.supernews.com> <7xmyvoag7j.fsf@ruckus.brouhaha.com> <46eb6ad1$0$7493$4c368faf@roadrunner.com> Message-ID: On 9/15/07, Carl Banks wrote: > On Fri, 14 Sep 2007 22:59:13 -0300, Eduardo O. Padoan wrote: > > > On 14 Sep 2007 18:08:00 -0700, Paul Rubin > > <"http://phr.cx"@nospam.invalid> wrote: > >> "Eduardo O. Padoan" writes: > >> > Not totally unrelated, but in Py3k, as it seems, overflows are really > >> > things of the past: > >> > > >> > > >> > Python 3.0a1 (py3k:58061, Sep 9 2007, 13:18:37) [GCC 4.1.3 20070831 > >> > (prerelease) (Ubuntu 4.1.2-16ubuntu1)] on linux2 Type "help", > >> > "copyright", "credits" or "license" for more information. > >> > >>> class MyInt(int): > >> > ... pass > >> > ... > >> > >>> import sys > >> > >>> MyInt(sys.maxint) > >> > 2147483647 > >> > >>> MyInt(sys.maxint+1) > >> > 2147483648 > >> > >> I'd be interested in knowing what happens in 3.0a1 with > >> > >> a = itertools.count(sys.maxint) > >> print a.next() > >> print a.next() > > > > > >>>> print(next(a)) > > Traceback (most recent call last): > > File "", line 1, in > > OverflowError: cannot count beyond PY_SSIZE_T_MAX > > > > Hum, you've got me there. it is the same as in 2.x. Maybe the message > > should be less crypt, at least - nothing that googling for > > PY_SSIZE_T_MAX cant help. > > This should demonstrate that OverflowError will not disappear entirely > even in Python 3. No one is denying that by now :) > Even if we were to get rid of all OverflowErrors resulting from integer > operations in Python, there are going to be some C extensions--including > some in the Python standard library--that will store 32-bit integers. > Modules such as array and struct will still raise it, and probably other > modules were a long integer sometimes doesn't make sense (socket, for > instance). itertools.count() should work for arbitrary integers, though. Agreed. I was lookind at itertoolsmodule.c, and even for my very limited C knowlegment, it does not seem to be too hard. Anyway: http://bugs.python.org/issue1165 > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From jcd at sdf.lonestar.org Thu Sep 27 16:02:01 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Thu, 27 Sep 2007 16:02:01 -0400 Subject: ValueError: too many values to unpack,>>> In-Reply-To: <46fc09ae$0$22333$426a74cc@news.free.fr> References: <5m24sfFatlbuU1@mid.uni-berlin.de> <46FBED79.6070207@comcast.net> <46fc09ae$0$22333$426a74cc@news.free.fr> Message-ID: <20070927200201.GA27262@sdf.lonestar.org> On Thu, Sep 27, 2007 at 09:50:26PM +0200, Bruno Desthuilliers wrote regarding Re: ValueError: too many values to unpack,>>>: > > Shawn Minisall a ?crit : > > Fredrik Lundh wrote: > > > >> Shawn Minisall wrote: > >> > >> > >> > >>> Sorry, it looks like it's on the fourth line with the 3 values on > >>> line 4...its reading line 3 fine > >>> > >>> Traceback (most recent call last): > >>> File "", line 1, in > >>> main() > >>> File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line > >>> 33, in main > >>> deposit1, deposit2, deposit3 = string.split(line, "\t") > >>> ValueError: too many values to unpack > >>> > >> > >> > >> instead of fumbling around in the dark, try inserting a print > >> statement before the offending line, so you can see what you're trying > >> to unpack: > >> > >> print string.split(line, "\t") # see what it is > >> deposit1, deposit2, deposit3 = string.split(line, "\t") > >> > >> > >> > > > > I did and it printed everything up until the 3rd line with 3 numbers for > > deposits. I have since figured it out...the teacher put in an extra tab > > after the last value so python thought it was 4 values for three. I > > went back into the file and deleted the extra tab after the 3rd number > > and saved it...now it's working fine. > > I'm going to kill her... > > You'd better learn how to deal with "this-cant-happen-here" situation, > because it's how it is in real-life. > And preferably learn how to deal with it in your code, not in the data that's given to you. I wouldn't be surprised if your teacher gave you that on purpose. There's an old maxim which I think applies here: "Be liberal in what you accept and conservative in what you produce." Note that you have *not* come up with code that handles the dataset given to you by your professor. Do not expect full marks on this homework assignment, unless you go back and modify your code to handle extraneous tabs at the end of the line. Cheers, Cliff From exhuma at gmail.com Tue Sep 18 08:58:17 2007 From: exhuma at gmail.com (exhuma.twn) Date: Tue, 18 Sep 2007 05:58:17 -0700 Subject: super, apply, or __init__ when subclassing? In-Reply-To: <46efc85f$0$17612$426a74cc@news.free.fr> References: <1190100791.740269.62880@k79g2000hse.googlegroups.com> <46efc85f$0$17612$426a74cc@news.free.fr> Message-ID: <1190120297.396213.312470@r29g2000hsg.googlegroups.com> On Sep 18, 2:45 pm, Bruno Desthuilliers wrote: > exhuma.twn a ?crit : > > > This is something that keeps confusing me. If you read examples of > > code on the web, you keep on seeing these three calls (super, apply > > and __init__) to reference the super-class. This looks to me as it is > > somehow personal preference. But this would conflict with the "There > > one way to do it" mind-set. > > apply is deprecated. Chances are that code using it is somewhat old. > super came with the new object model in Python 2.2.1 (IIRC), and is only > useful for some corner cases involving multiple inheritence . Directly > calling the superclass's method (__init__ or whatever) is the canonical > way in the most common cases. > > And BTW, the sentence is "there *should* be one - and *preferably* only > one - *obvious* way to do it" (emphasis is mine). In this case, there's > _at least_ one way do to do it, and only one (direct call) is really > obvious IMHO !-) > > > So, knowing that in python there is one thing to do something, these > > three different calls must *do* domething different. > > Indeed. But mostly because you managed to get 2 examples wrong !-) > > > But what exactly > > *is* the difference? > > > ------------ Exampel 1: ----------------------------- > > > class B(A): > > def __init__(self, *args): > > A.__init__(self, args) > > You want: > > class B(A): > def __init__(self, *args): > A.__init__(self, *args) Ah.. this was a typo in my original post. Oops ;) > > > ------------ Exampel 2: ----------------------------- > > > class B(A): > > def __init__(self, *args): > > apply( A.__init__, (self,) + args) > > is the same as the previous, using the deprecated apply function. > > > ------------ Exampel 3: ----------------------------- > > > class B(A): > > def __init__(self, *args): > > super(A,self).__init__(*args) > > You want: > > class B(A): > def __init__(self, *args): > super(B,self).__init__(*args) Hmmm... and suddenly it all makes sense! Great! Thanks all for clarifying this to a Java-Convert ;) From bignose+hates-spam at benfinney.id.au Wed Sep 26 04:03:21 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 26 Sep 2007 18:03:21 +1000 Subject: setuptools without unexpected downloads References: <87ejgmklep.fsf@benfinney.id.au> <878x6ukkvq.fsf@benfinney.id.au> <5luhb0Faal8aU1@mid.uni-berlin.de> Message-ID: <874phhlupi.fsf@benfinney.id.au> "Diez B. Roggisch" writes: > Ben Finney schrieb: > > To clarify: I want to retain the "assert the specified > > dependencies are satisfied" behaviour, without the "... and, if > > not, download and install them the Setuptools Way" behaviour. > > > > Instead, I just want the default "dependencies not satisfied" > > behaviour for my 'setup.py' program to be: complain the > > dependencies aren't met, and refuse to install. > > The problem here is that your favorite OS vendor/distributor not > necessarily offers the required meta-information - so setuptools > can't check the dependencies. Let's assume it does. How would I modify my 'setup.py' script so that its default behaviour, when dependencies are not met, is not "download and install dependencies via setuptools" but instead "exit with error message"? -- \ "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 p at ulmcnett.com Tue Sep 18 17:11:23 2007 From: p at ulmcnett.com (Paul McNett) Date: Tue, 18 Sep 2007 14:11:23 -0700 Subject: How do you limit the # of lines Read? In-Reply-To: <1190149187.799482.151320@19g2000hsx.googlegroups.com> References: <1190149187.799482.151320@19g2000hsx.googlegroups.com> Message-ID: <46F03EFB.808@ulmcnett.com> koutoo at hotmail.com wrote: > I am working on a loop for my code and was wondering if there is a way > to limit the number of lines read through? I'd hate to cut the test > file in order to run the code in the testing phase. Can you add a > value in the parenthesis of the readline() function? > > t = string.readline() # Limit this somehow? Assuming s is a file-like object: for idx, line in enumerate(s): if idx > 2: break print idx, line -- pkm ~ http://paulmcnett.com From bdesth.quelquechose at free.quelquepart.fr Fri Sep 7 12:33:51 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 07 Sep 2007 18:33:51 +0200 Subject: Organizing Code - Packages In-Reply-To: <1189280539.449868.169910@22g2000hsm.googlegroups.com> References: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> <46e17143$0$6189$426a74cc@news.free.fr> <1189183088.922537.18290@r34g2000hsd.googlegroups.com> <87r6laa0ir.fsf@rudin.co.uk> <46e1a0bc$0$7689$9b4e6d93@newsspool2.arcor-online.net> <1189280539.449868.169910@22g2000hsm.googlegroups.com> Message-ID: <46e412b7$0$21562$426a74cc@news.free.fr> xkenneth a ?crit : > On Sep 7, 2:04 pm, Wildemar Wildenburger > wrote: > >>Paul Rudin wrote: >> >>>xkenneth writes: >> >>>>>Ah, yes, a couple of things: >>>>>- avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens >>>> >>>>Yes but i find it hard to edit classes easily when I have more than >>>>one class per file. >> >>>Why? >> >>Scroll-Blindness would be a good reason. >> >>It would however be completely rediculous to create a file for every >>10-liner class you have (and I have found that Python classes tend to be >>rather short). >> >>/ > > > Yes I agree, "Scroll-Blindness" it just gets long and confusing. > Navigating isn't so bad (emacs) here. Don't you use ECB ? (Emacs Code Browser) ? But even without it, it's a problem of file size, not a problem of number of classes. (snip question about import, cf other answers) From m.n.summerfield at googlemail.com Wed Sep 26 02:59:41 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Wed, 26 Sep 2007 06:59:41 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190756003.292096.71130@o80g2000hse.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> Message-ID: <1190789981.385466.37870@57g2000hsv.googlegroups.com> On 25 Sep, 22:33, Paul Hankin wrote: > On Sep 25, 9:55 pm, Mark Summerfield > wrote: > > > ... > > class sorteddict(dict): > > > ... > > if self.__keys is None: > > self.__keys = sorted(dict.keys(self), cmp=self.__cmp, > > key=self.__key, > > reverse=self.__reverse) > > You'd be better defining __keys like this: > > def __getkeys(self): > if self.__keycache is None: > self.__keycache = dict.keys(self) > self.__keycache.sort(cmp=...) > return self.__keycache > > __keys = property(__getkeys) > > and where you have 'self.__keys = None', either replace with > 'self.__keycache = None' or more cleanly with a call to: > > def __invalidate_key_cache(self): > self.__keycache = None > > to improve the code quality. Yes, that's much better. As you've no doubt realised, this particular implementation gives best performance when the pattern of use is: lots of edits, lots of lookups, ..., and gives worst performance when the pattern of use is: edit, lookup, edit, lookup (in which case using a dict and sorted() is probably better). So there is lots of scope for someone to do a version that has good performance for all patterns of use:-) I've put a full version with doctests & docstrings on PyPI: http://pypi.python.org/pypi/sorteddict Here's the stripped version (just 92 lines): class sorteddict(dict): def __init__(self, iterable=None, cmp=None, key=None, reverse=False): if iterable is None: iterable = [] dict.__init__(self, iterable) self.__cmp = cmp self.__key = key self.__reverse = reverse self.__keycache = None @property def __keys(self): if self.__keycache is None: self.__keycache = dict.keys(self) self.__keycache.sort(cmp=self.__cmp, key=self.__key, reverse=self.__reverse) return self.__keycache def __invalidate_key_cache(self): self.__keycache = None def update(self, *args, **kwargs): self.__invalidate_key_cache() dict.update(self, *args, **kwargs) @classmethod def fromkeys(cls, iterable, value=None): dictionary = cls() for key in iterable: dictionary[key] = value return dictionary def copy(self): return sorteddict(dict.copy(self), cmp=self.__cmp, key=self.__key, reverse=self.__reverse) def clear(self): self.__invalidate_key_cache() dict.clear(self) def setdefault(self, key, value): self.__invalidate_key_cache() return dict.setdefault(self, key, value) def pop(self, key, value=None): if key not in self: return value self.__invalidate_key_cache() return dict.pop(self, key, value) def popitem(self): self.__invalidate_key_cache() return dict.popitem(self) def keys(self): return self.__keys[:] def values(self): return [self[key] for key in self.__keys] def items(self): return [(key, self[key]) for key in self.__keys] def __iter__(self): return iter(self.__keys) def iterkeys(self): return iter(self.__keys) def itervalues(self): for key in self.__keys: yield self[key] def iteritems(self): for key in self.__keys: yield key, self[key] def __delitem__(self, key): self.__invalidate_key_cache() dict.__delitem__(self, key) def __setitem__(self, key, value): self.__invalidate_key_cache() dict.__setitem__(self, key, value) def __repr__(self): raise NotImplementedError() def __str__(self): return "{%s}" % ", ".join( ["%r: %r" % (key, self[key]) for key in self.__keys]) From kw at codebykevin.com Fri Sep 28 17:27:41 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 28 Sep 2007 17:27:41 -0400 Subject: List search In-Reply-To: References: Message-ID: <76859$46fd71d5$4275d90a$5236@FUSE.NET> Robert Kern wrote: > line == 'x11' > D'oh! That was simple, wasn't it? *smacks head* That did the trick. Thanks! -- Kevin Walzer Code by Kevin http://www.codebykevin.com From frikimaster at gmail.com Tue Sep 11 00:58:24 2007 From: frikimaster at gmail.com (Antoni Villalonga) Date: Tue, 11 Sep 2007 06:58:24 +0200 Subject: urllib2: handle an error (302) Message-ID: <75eeb70e0709102158m2388e4h5988b0d6433f3bb3@mail.gmail.com> Hi! First of all sorry for my English, it's not my language... When urllib2 libs visit a URL with 302 error follow the location automatically. I need to get the location in order to get the full URL (not relative URL) parsing html code. You can see an example here: http://friki.org/302.php raises a "302 error" with => Location: "http://friki.cat/test.html" urllib2 follow the location In http://friki.cat/test.html i can read a relative link "/noticies/1.html" but it isn't http://friki.org/noticies/1.html it's http://friki.cat/noticies/1.html. I don't know that's the good way to handle this using these libs. There are any way to handle a 302 error? Can I parse http headers of the first petition (302 error+location url)? Sorry again for my English. And sorry if I'm too newbie for this list -_- Note: Be carefull: "friki.cat" != "friki.org" ;-) I just write an example code, it get an 404 error because "http://friki.org/noticia/1.html" don't exist. "http://friki.cat/noticia/1.html" is the correct link. 302_test.py: #!/usr/bin/python import re, cookielib, urllib2 HOST = "http://friki.org" #Get the homepage cj = cookielib.MozillaCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open(HOST+"/302.php") data= r.read() #Follow the link on http source p = re.compile('href=\"(.*)\"') m = p.search(data) LINK = m.group() LINK = LINK[6:(len(LINK)-1)] if ("http" != LINK[0:4]):#It just sucks LINK = HOST+LINK print "Visit: "+LINK r = opener.open(LINK) data= r.read() #<--- End of code ---> -- "Boring two-person multiplayer may turn friends into enemies." Antoni Villalonga i Noceras #Bloc# ~> http://friki.CAT #Jabber# ~> friki at bulmalug.net From pavlovevidence at gmail.com Sat Sep 1 22:31:57 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 1 Sep 2007 22:31:57 -0400 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <7xwsvcc9yz.fsf@ruckus.brouhaha.com> <1i3p8lm.19738kn1q0gkouN%aleax@mac.com> <1188587846.687895.69240@q5g2000prf.googlegroups.com> <38rmq4-cq.ln1@strongwill.g2ctech> <46d903db$0$19580$4c368faf@roadrunner.com> <46D98315.4030602@club-internet.fr> Message-ID: <46da2b31$1$6412$4c368faf@roadrunner.com> On Sat, 01 Sep 2007 17:19:49 +0200, Pierre Hanser wrote: > Carl Banks a ?crit : >> >> This is starting to sound silly, people. Critical is a relative term, >> and one project's critical may be anothers mundane. Sure a flaw in >> your flagship product is a critical problem *for your company*, but are >> you really trying to say that the criticalness of a bad web search is >> even comparable to the most important systems on airplanes, nuclear >> reactors, dams, and so on? Come on. > > 20 years ago, there was *no* computer at all in nuclear reactors. But they had electronic (analog) systems that were (supposedly) just as heavily regulated and scrutinized as the digital computers of today; and were a lot more scrutinized than, say, the digital computers that banks were using. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Thu Sep 13 18:26:24 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Sep 2007 22:26:24 -0000 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <5ksoaoF5am8cU1@mid.individual.net> <1189701793.466307.93210@g4g2000hsf.googlegroups.com> <5ktfjqF5ctrvU2@mid.individual.net> Message-ID: <13eje8gi4nt0j1e@corp.supernews.com> On Thu, 13 Sep 2007 20:59:06 +0200, Bjoern Schliessmann wrote: > TheFlyingDutchman wrote: >> Here's a FAQ item where they refer to it as I think Python should have >> done it - a special predefined variable: > > Maybe. Personally, I like it the way it is in Python. > > Why don't you make a preprocessor which accepts method declarations > without "self" and fixes them? If you look at the thread "parameter list notation" from ten days or so ago, TheFlyingDutchman has forked Python and is working on a very special new language, PIEthun 3.01B. I for one am looking forward to seeing all the very special features of PIEthun. -- Steven. From alexandre.badez at gmail.com Tue Sep 25 08:32:21 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Tue, 25 Sep 2007 12:32:21 -0000 Subject: Raw string printing In-Reply-To: References: <1190722082.406690.222540@57g2000hsv.googlegroups.com> Message-ID: <1190723541.848558.237890@d55g2000hsg.googlegroups.com> On Sep 25, 2:24 pm, Peter Otten <__pete... at web.de> wrote: > Alexandre Badez wrote: > > I would like to do something like: > > > s = r"a\tb\n" > > print unraw(s) # <= this is the "magic" function I'm searching for > > # result with > > a b > > n > > > Does any of you know how to do it properly ? > >>> print r"a\tb\nx".decode("string-escape") > > a b > x > > Peter THANKS :D From exhuma at gmail.com Wed Sep 19 09:26:46 2007 From: exhuma at gmail.com (exhuma.twn) Date: Wed, 19 Sep 2007 06:26:46 -0700 Subject: Keeping a database connection with a Singleton? Message-ID: <1190208406.041953.115580@g4g2000hsf.googlegroups.com> I remember reading about the Singleton pattern in python and how it's an unpythonic pattern and all. At the time I did not need the Singleton anyways, so I just glanced over the document. But, setting this aside: I have an application where I have a connection to a database. At some point in the application I open up a new window. The new windows resides in a different module. So I have a directory structure like this: - mainapp.py - newwindow.py So I import "newwindow" in "mainapp" so I can instantiate and display it. Meanwhile, the main-app has an open connection to the database. What's the cleanest way to hand this connection to the new window? I can see several possibilities: 1) Simply pass the connection as paramtere to the constructor of new- window. 2) Use the "Singleton" deisign pattern to keep a reference to the connection 3) Open up a completely new connection to the database in the new window. Now, option 1) is clearly the easiest to implement, however, I somehow tend to use option 2 (the singleton) as it's more flexible. Option 3 looks ugly to me. This is a stuation I run into many times. And I am always faced with the same choice. And I never know which one to chose. And now that I am getting more and more comfortable with the basics of python, I would like to know if I am missing something more "pythonic". So, what would you recommend? From aleax at mac.com Tue Sep 18 01:31:40 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 17 Sep 2007 22:31:40 -0700 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> Message-ID: <1i4lvsx.mhw5621jlsd53N%aleax@mac.com> Ben Finney wrote: > Am I mistaken in thinking that "superclass of foo" is equivalent to > "parent class of foo"? If so, I'd lay heavy odds that I'm not alone in > that thinking. "That thinking" (confusing "parent" with "ancestor") makes sense only (if at all) in a single-inheritance world. Python's super() exists to support MULTIPLE inheritance. In general, "a superclass of foo" means "a class X such that foo is a sublass of X" and thus applies to all parents, all parents of parents, and so on ("issubclass" does NOT mean "is a DIRECT AND IMMEDIATE subclass", but "is a subclass"; check the Python builtin function of that name). Alex From danfike at gmail.com Fri Sep 21 11:11:25 2007 From: danfike at gmail.com (danfike at gmail.com) Date: Fri, 21 Sep 2007 15:11:25 -0000 Subject: Building Python with VC8 on x64 Vista In-Reply-To: <1190299551.573204.322440@57g2000hsv.googlegroups.com> References: <1190299551.573204.322440@57g2000hsv.googlegroups.com> Message-ID: <1190387485.939915.171760@19g2000hsx.googlegroups.com> On Sep 20, 9:45 am, danf... at gmail.com wrote: > Hi all, > > So I'm working on a C++ application that will eventually embed or > extend Python using Boost.Python, but I first need to get Python > compiled correctly for my platform. I've got a Windows Vista 64-bit > machine with a Core 2 processor, and I'm compiling with a VC8. > > I downloaded the Python 2.5.1 source from python.org, and I opened the > Visual Studio solution file that was in the PCbuild8 directory. I > created a new x64 platform and managed to successfully compile the > 'pythoncore' and 'python' projects (both in Debug and Release > configurations), resulting in working executables. (Aside: When > launched, the python console says "Python 2.5.1 [MSC v.1400 64 bit > (AMD64)] on win32" up top. Does that seem right?) > > So, this program I'm writing with Boost.Python (that worked correctly > on x86 with home-built libraries) won't compile with these x64 > libraries. I keep getting 'unresolved external symbols.' But, I'm > certain I'm linking in the library correctly. Here's a snippet from > the output (with /verbose:lib) when compiling: > > 1>Searching libraries > 1> > 1> Searching ..\..\..\3rdParty\boost_1_34_0\lib_x64\libboost_python- > vc80-mt-gy-1_34.lib: > 1> > 1> Searching ..\..\..\3rdParty\Python25\libs_x64\python25_d.lib: > 1>Finished searching libraries > 1>py_dyn_test.obj : error LNK2001: unresolved external symbol > _Py_NoneStruct > 1>vector_py.obj : error LNK2001: unresolved external symbol > _Py_NoneStruct > 1>volume_py.obj : error LNK2001: unresolved external symbol > _Py_NoneStruct > 1>py_dyn_test.obj : error LNK2001: unresolved external symbol > _Py_RefTotal > 1>vector_py.obj : error LNK2001: unresolved external symbol > _Py_RefTotal > 1>volume_py.obj : error LNK2001: unresolved external symbol > _Py_RefTotal > 1>volume_py.obj : error LNK2001: unresolved external symbol > PyExc_IndexError > > If I switch to the Release configuration, I see fewer errors: > > 1>py_dyn_test.obj : error LNK2001: unresolved external symbol > _Py_NoneStruct > 1>volume_py.obj : error LNK2001: unresolved external symbol > PyExc_IndexError > > Note that none of my own code is Debug-specific. Also, the code in my > files is correct, because (as stated above), it worked fine for x86. > > Though I don't know how useful it is, I did open the python libraries > in wordpad, and though most of the file wasn't legible, I did find > strings "Py_NoneStruct," "Py_RefTotal," and "PyExc_IndexError." > > I suspect that I set up my "x64" platform configuration incorrectly, > or missed something. It's basically the same as the Win32 > configuration, except with the /MACHINE:X64 flag instead of / > MACHINE:X86. One of the things I'm noticing just now, as I post this, > is that the preprocessor flag "WIN32" is still defined in the x64 > configuration. Maybe if I change that to "WIN64," I'll have better > luck. > > Any advice you have on what the "correct" way to do this is would be > appreciated. > > -Dan I've tried re-building my libraries from the latest revision (58225), using the solution in the PCbuild8 folder. I had no problems getting the python25[_d].lib to compile, but I still get these symbol errors when I try to link with the library. -Dan From gagsl-py2 at yahoo.com.ar Thu Sep 27 02:17:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Sep 2007 03:17:36 -0300 Subject: Using closures and partial functions to eliminate redundant code References: Message-ID: En Wed, 26 Sep 2007 23:01:17 -0300, Matthew Wilson escribi?: > I wrote some code to create a user and update a user on a remote box by > sending emails to that remote box. When I was done, I realized that my > create_user function and my update_user function were effectively > identical except for different docstrings and a single different value > inside: I would have used an object with two methods... But this is just another example of the closure/object dichotomy. Some enlightment: http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html -- Gabriel Genellina From f.guerrieri at gmail.com Wed Sep 19 10:41:43 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Wed, 19 Sep 2007 16:41:43 +0200 Subject: Find the ID, but how to select/copy the whole string by ID? In-Reply-To: <1190209195.493784.133340@q3g2000prf.googlegroups.com> References: <1190209195.493784.133340@q3g2000prf.googlegroups.com> Message-ID: <79b79e730709190741i2deb95c8m2982b3201a3fc4be@mail.gmail.com> On 9/19/07, Leon wrote: > stringID = str(raw_input('Enter the string ID : ')) > file = open('strings.txt') > sourcefile = file.read() > file.close() > sourcefile.find (stringID) > > but how can I select and copy the specific string from to > with id I input? If the file you are parsing is in xml, there are many parser out there which can help you (this is discussed very often on this list, even today) . If the format is very simple and you really want to do it by hand, you could do something like: stringID = raw_input('Enter the string ID:') for line in open('strings.txt'): if line.find(stringID) > -1: print 'Found!' Note that find returns the index where the substring you look for is found, and it returns -1 if the substring is not found. The problem is that -1 is a valid index to refer to a character in a string (actually it refers to the last character of the string), so be careful with interpreting the results of the find method. francesco From martin at v.loewis.de Tue Sep 4 13:10:06 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 04 Sep 2007 19:10:06 +0200 Subject: Parse or Pass? In-Reply-To: References: <1188917032.271543.236420@d55g2000hsg.googlegroups.com> Message-ID: <46DD916E.4000201@v.loewis.de> > In general, "parsing" is analyzing the grammatical structure of a > string. People sometimes talk loosely about "parsing the command line". > but I don't think that's normally applied to providing the actual > arguments (corresponding to the definition's "formal parameters") when a > function is called - that's argument passing. I find that people often use "parsing" in contexts where my (non-native) language feeling says it should not be used. For example, people talk about "parsing" trees, meaning that they perform some processing on the tree with the objective of extracting certain information. In the same sense, I have seen people "parsing" lists - meaning they iterate over the list. If I extrapolate my experience with German IT language, I think people often use terminology they have not fully understood. I often ask my students what the difference between "eingeben", "ausgeben", "?bergeben" und "zur?ckgeben" is when they start saying that "die Funktion gibt das Ergebnis aus". Regards, Martin From wmcclain at salamander.com Thu Sep 20 09:29:47 2007 From: wmcclain at salamander.com (Bill McClain) Date: 20 Sep 2007 13:29:47 GMT Subject: Freetype bindings, finally? References: <1190225043.731294.7050@19g2000hsx.googlegroups.com> Message-ID: On 2007-09-19, Jason Yamada-Hanff wrote: > Hi all, > I'm working on a project that would benefit very much from Python > Freetype2 bindings (the Fonty Python project). I don't want to > duplicate efforts and wrap the library again if we don't have to. > Interestingly, it seems like there have been lots of attempts at doing > this. I would like a freetype library as well, but neither have I done Python/C interfaces. If you have time to put into this, I would suggest starting a mailing list on the project, as well as continuing the discussion here. I would certainly susbscribe, and contribute as time and talent permit. -Bill -- Sattre Press Tales of War http://sattre-press.com/ by Lord Dunsany info at sattre-press.com http://sattre-press.com/tow.html From kyosohma at gmail.com Wed Sep 12 09:17:53 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 12 Sep 2007 13:17:53 -0000 Subject: Basic GUI In-Reply-To: <1189569282.372083.264560@57g2000hsv.googlegroups.com> References: <1189569282.372083.264560@57g2000hsv.googlegroups.com> Message-ID: <1189603073.639193.193390@19g2000hsx.googlegroups.com> Don, On Sep 11, 10:54 pm, Don Hanlen wrote: > I'm writing a simple GUI that: > ..gets info via telnet protocol (and sends) > ..gets info via http (and sends) > ..gets user-info from (currently) > ...Tkinter Text windoze > ...Tkinter buttons and such > ..displays info in various Tkinter windoze > ...graphic AND text... > > I can accomplish all of these functions individually and now seem to > need to set up multi-processes to combine 'em. Back in my C days, I'd > have used fork/exec to do so, but I'm confused by the number of > modules available in Python. Is there a "best" for portability and > simplicity? (Or am I on the wrong track here?) > > I could solve my problems with the following psuedo-code made into > real code: > ---- > import blah > > t = blah.fork(runthisprogram.py) > > #OK still in main > t.sendinfo(info) > info = t.receiveinfo() > ---- > #runthisprogram.py > def sendinfobacktopapa(): > ? eventhere > def getinfofrompapa(): > ? eventhere > ---- > > It seems to me that propagating events *may* be the best way to > communicate. I'm wide open, including to non-multi-process solutions. > > Thanks for your comments, I searched old posts for a while, various > other Python info-sources, and couldn't find an answer. > -- > don You can also use threads, which is a little bit more portable than using Python's fork methodology, or so I've read. The concepts on this page can be applied to any GUI toolkit you choose: http://wiki.wxpython.org/LongRunningTasks I've used them with wxPython, but iirc, Lutz does something quite similar with Tkinter in his latest edition of "Programming Python". I think what Michele is referring to is the subprocess module, which is also useful. Mike From aleax at mac.com Sun Sep 16 15:14:47 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 16 Sep 2007 12:14:47 -0700 Subject: how to join array of integers? References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <13eos6ihf2mjg4a@corp.supernews.com> <87lkb6o4bx.fsf@rudin.co.uk> Message-ID: <1i4j87a.vzt23lrho9wbN%aleax@mac.com> Paul Rudin wrote: ... > Isn't it odd that the generator isn't faster, since the comprehension > presumably builds a list first and then iterates over it, whereas the > generator doesn't need to make a list? The generator doesn't, but the implementation of join then does (almost). See Objects/stringobject.c line 1745: seq = PySequence_Fast(orig, ""); As per , """ PyObject* PySequence_Fast(PyObject *o, const char *m) Return value: New reference. Returns the sequence o as a tuple, unless it is already a tuple or list, in which case o is returned. Use PySequence_Fast_GET_ITEM() to access the members of the result. Returns NULL on failure. If the object is not a sequence, raises TypeError with m as the message text. """ If orig is neither a list nor a tuple, but for example a generator, PySequence_Fast builds a list from it (even though its docs which I just quoted says it builds a tuple -- building the list is clearly the right choice, so I'd say it's the docs that are wrong, not the code;-)... so in this particular case the usual advantage of the generator disappears. PySequence_fast is called in 13 separate spots in 8 C files in the Python 2.5 sources, so there may a few more surprises like this;-). Alex From bj_666 at gmx.net Sat Sep 22 04:40:53 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2007 08:40:53 GMT Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> Message-ID: <5lk2olF8gic1U5@mid.uni-berlin.de> On Sat, 22 Sep 2007 00:47:37 -0700, Kay Schluehr wrote: > On 22 Sep., 08:56, Paul Rubin wrote: >> Kay Schluehr writes: >> > If you feel you can transform it into another unambigous grammar >> > mixing statements and expressions it's up to you. >> >> We got rid of the print statement for python 3.0. Why not get rid >> of the rest of them too? Just use expressions for everything, as >> works fine for plenty of other languages. > > One might create a new dynamic functional+OO programming language, > where small statements like print, assert, raise etc. all become > functions and statements like while, for, with etc. become anonymous > closures. Before someone starts to create such a thing he should take a look at Io which has just objects and methods. http://www.iolanguage.com/ Ciao, Marc 'BlackJack' Rintsch From jkn_gg at nicorp.f9.co.uk Wed Sep 12 07:06:40 2007 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Wed, 12 Sep 2007 04:06:40 -0700 Subject: Generating HTML In-Reply-To: References: <9e2f512b0709112133l41ce5ef1g815962a81becf6b9@mail.gmail.com> Message-ID: <1189595200.209044.267390@d55g2000hsg.googlegroups.com> I used to use Cheetah, but have switched recently to Jinja: http://jinja.pocoo.org/ Mainly this is because the syntax is similar to Django's templates, and eventually I plan on migrating to Django. jon N From arnodel at googlemail.com Sun Sep 2 10:53:29 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 02 Sep 2007 07:53:29 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> Message-ID: <1188744809.834366.22490@19g2000hsx.googlegroups.com> On Sep 2, 12:51 pm, jwrweather... at gmail.com wrote: [...] > The resulting executable takes 0.24 seconds to run. I'm not expecting > a scripting language to run faster than native code, but I was > surprised at how much slower it was in this case. Any ideas as to what > is causing python so much trouble in the above code? Sorry I didn't answer your question at all in my previous post (although my modified method gets the answer in about 6s on a measly PB G4 1GHz :). Your little code snippet is just about the worst bit of code for python to be compared to C. Three loops, only integer arithmetic: that's not going to make Python shine! Nevertheless as you optimise your C snippet (-O3), there are probably a few things that the compiler does for you: * as in the inner loop, a*a + b*b always remain the same, it is probably stored in a register once and for all * in the second loop, a*a remains the same so it might be calculated once and for all as well. It gives this: M = 1000 solutions = [0] * M def f1(): "Your original implementation" for a in xrange(1, M): for b in xrange(1, M - a): for c in xrange(1, M - a - b): if a**2 + b**2 == c**2: solutions[a+b+c] += 1 def f2(): "a*a + b*b precalculated" for a in xrange(1, M): a2 = a*a for b in xrange(1, M - a): s = a2 + b*b for c in xrange(1, M - a - b): if s == c*c: solutions[a+b+c] += 1 It doesn't make it as quick as C of course, but more than halves the execution time. -- Arnaud From lolu999 at gmail.com Sat Sep 8 14:02:44 2007 From: lolu999 at gmail.com (lolu999 at gmail.com) Date: Sat, 08 Sep 2007 11:02:44 -0700 Subject: How to insert in a string @ a index Message-ID: <1189274564.462664.131240@22g2000hsm.googlegroups.com> Hi; I'm trying to insert XYZ before a keyword in a string. The first and the last occurence of hello in the string t1 (t1="hello world hello. hello \nwhy world hello") are keywords. So after the insertion of XYZ in this string, the result should be t1 = "XYZhello world hello. hello \nwhy world XYZhello" The python doesn't supports t1[keyword_index]="XYZhello" (string object assignment is not supported). How do I get to this problem? Any sugguestions? -a.m. From saptarshi.guha at gmail.com Thu Sep 20 19:00:36 2007 From: saptarshi.guha at gmail.com (sapsi) Date: Thu, 20 Sep 2007 16:00:36 -0700 Subject: Python,SWIG and libjvm Message-ID: <1190329236.398635.226020@y42g2000hsy.googlegroups.com> Hello, I'm not sure if this the correct list but here goes (and sorry for the noise). I've been attempting to wrap python around libhdfs. So far so good (i've attached the SWIG template at the end). The compilation works without errors and the shared objects do have references to all the functions. However, when importing into python import pyhdfs i get the following error: Traceback (most recent call last): File "", line 1, in ? File "/home/sguha/tmp/b/hdfs.py", line 7, in ? import _hdfs ImportError: libjvm.so: cannot open shared object file: No such file or directory However, libjvm.so is located in /home/sguha/mine/jdk1.6.0_02/jre/lib/ amd64/server which is present in the PYTHONPATH and sys.path. I can understand it complaining while loading the libjvm.so but python doesn't locate it even when in the path. As an aside, the build command for hdfs.c has " -ljvm " - this should affect SWIG, right? Meaning if my program (e.g) links to a library and i want a wrapper around my program (to python) i need SWIG templates for my headers only and not for the linked library...right? ( I guess the answer is i dont otherwise that would be quite a nightmare of work) Thank you for your time Saptarshi Attachments: SWIG template %module pyhdfs %{ #include "hdfs.h" %} %include "hdfs.h" From pavlovevidence at gmail.com Sat Sep 22 07:04:46 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Sep 2007 07:04:46 -0400 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <46f45f02$0$15350$4c368faf@roadrunner.com> <7xps0bgq6p.fsf@ruckus.brouhaha.com> <46f4dd90$0$32490$4c368faf@roadrunner.com> <7x64232ggh.fsf@ruckus.brouhaha.com> Message-ID: <46f4f9b1$0$17119$4c368faf@roadrunner.com> On Sat, 22 Sep 2007 02:32:30 -0700, Paul Rubin wrote: > Carl Banks writes: >> That's it, lost me already. You ever see the kinds of programs >> mechanical engineers write? It isn't software. > > They do a lot of number crunching. Certainly they can appreciate higher > order functions like integrate(f, x0, x1) to integrate the function f > from x0 to x1; or diff(f, x0) to find the derivative of f at x0; etc. > Fortran had cheesy ways to do this as far back as the 1950's. Well, I appreaciate it, as do many other engineers, but for a lot of engineers functional programming might as well not exist, either because they don't about it or don't care about it. And it doesn't really affect them much, other than making them slightly less efficient then they could have been. That's the key here. Carl Banks From steven.bethard at gmail.com Tue Sep 25 14:58:36 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Sep 2007 12:58:36 -0600 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190744523.025029.227690@k79g2000hse.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> Message-ID: <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> Paul Hankin wrote: > On Sep 25, 12:51 pm, Mark Summerfield > wrote: >> On 25 Sep, 12:19, Paul Hankin wrote: >> >> >> >>> Recall sorted... >>> sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted >>> list >>> So why not construct sorteddicts using the same idea of sortedness? >>> sorteddict((mapping | sequence | nothing), cmp=None, key=None, >>> reverse=None) >>> Then we can specify the exact behaviour of sorteddicts: it's the same >>> as a regular dict, except when the order of keys is important they're >>> ordered as if they were sorted by sorted(keys, cmp=sd._cmp, >>> key=sd._key, reverse=sd._reverse). Here I imagine cmp, key and reverse >>> are stored in the new sorteddict as attributes _cmp, _key, _reverse - >>> obviously the actual implementation may differ. >>> This has the benefit of making sorteddict's behaviour explicit and >>> easy to understand, and doesn't introduce a new sorting API when we >>> already have a perfectly decent one. >>> The only problem here is the **kwargs form of the dict constructor >>> doesn't translate as we're using keyword args to pass in the sort >>> criterion. Perhaps someone has an idea of how this can be solved. If >>> nothing else, this constructor could be dropped for sorteddicts, and >>> sorteddict(dict(**kwargs), cmp=..., key=..., reverse=...) when that >>> behaviour is wanted. >>> I don't like the integral indexing idea or the slicing: indexing and >>> slicing are already part of python and it's bad to have different >>> syntax for the same concept on sorteddicts. I'd say it's not an >>> important enough for sorteddicts anyway. >>> -- >>> Paul Hankin >> This makes a lot of sense to me. But how do you envisage it would be >> implemented? > > Here's a first go. Sorting occurs when the keys are iterated over, > making it fast (almost as a dict) for construction, insertion, and > deletion, but slow if you're iterating a lot. You should look at some > use cases to decide if this approach is best, or if a sorted > datastructure should be used instead, but my instinct is that this is > a decent approach. Certainly, you're unlikely to get a simpler > implementation :) > > class sorteddict(dict): > "A sorted dictionary" > def __init__(self, arg=None, cmp=None, key=None, reverse=False): > if arg: > super(sorteddict, self).__init__(arg) > else: > super(sorteddict, self).__init__() > self._cmp = cmp > self._key = key > self._reverse = reverse > def keys(self): > return sorted(super(sorteddict, self).keys(), cmp=self._cmp, > key=self._key, reverse=self._reverse) > def iter_keys(self): > return (s for s in self.keys()) > def items(self): > return [(key, self[key]) for key in self.keys()] > def iter_items(self): > return ((key, self[key]) for key in self.keys()) > def values(self): > return [self[key] for key in self.keys()] > def iter_values(self): > return (self[key] for key in self.keys()) > def __str__(self): > return '{' + ', '.join('%s: %s' % (repr(k), repr(v)) > for k, v in self.iter_items()) + '}' > def __repr__(self): > return str(self) > def __iter__(self): > return self.iter_keys() With this is the implementation, I'm definitely -1. Not because it's a bad implementation, but because if the iteration is always doing a sort, then there's no reason for a separate data structure. Just use sorted() directly on a regular dict. That has the advantage of being much more obvious about where the expensive operations are:: for key in sorted(d, ...): ... whatever you want to do ... IMHO, the only reason to introduce a sorteddict() is if it minimizes the cost of sorting the keys. STeVe From http Wed Sep 5 01:01:47 2007 From: http (Paul Rubin) Date: 04 Sep 2007 22:01:47 -0700 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> Message-ID: <7xwsv53dtw.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > Right. The idea is that those attacks don't exist and therefore the > > output is computationally indistinguishable from random. > > It is a huge leap from what the man page says, that they don't exist in > the unclassified literature at the time the docs were written, to what > you're saying, that they don't exist. OK. /dev/random vs /dev/urandom is a perennial topic in sci.crypt and there are endless long threads about it there, so I tried to give you the short version, but will give a somewhat longer version here. There can't be an actual security proof without also proving P!=NP; however, the cryptographic part of /dev/urandom is designed pretty conservatively and seems to be in good shape even after all these years. > The man page is clear: there is a possible vulnerability in /dev/urandom. There is the theoretical possibility of such a vulnerability, however it also applies to /dev/random. Note that the man page is neither a kernel internals document nor a cryptography textbook, so it doesn't describe the algorithm or the theory behind it. For that you have to look at the source code and the cryptographic literature, respectively. For the random.c source code, see http://www.cs.berkeley.edu/~daw/rnd/linux-rand It's an old version but hasn't changed all that much since then AFAIK. There is a long comment at the top explaining how it works. Short version: /dev/random reads data from a bunch of stochastic sources around the system (e.g. things like mouse motion) and makes a seat-of-the-pants estimate of the amount of entropy coming from the sources. The sources are not considered to be uniform or uncorrelated; they're just supposed to contain entropy. The entropy is distilled through a cryptographic hash function before being sent out the API. /dev/random throttles its output so that the number of bits emitted is always lower than the estimated input entropy. /dev/urandom is the same but doesn't do this throttling. For the theory of what we hope (but have not proved) that these hash functions do, see for example the HMAC papers: http://www-cse.ucsd.edu/~mihir/papers/hmac.html > Any cryptographer worth his salt (pun intended) would be looking to close > that vulnerability BEFORE an attack is made public, and not just wait for > the attack to trickle down from the NSA to the script kiddies. The time > to close the stable door is _before_ the horse gets away. No really, these functions are very well studied, in fact there are known ways to construct collisions in the md5 compression function but that doesn't appear to be of any use against how random.c uses it. > I agree that this flaw doesn't sound like it will effect the application > being discussed, but a problem has already been found and a solution is > already known: block until there's enough entropy. That's what /dev/ > random does. No, having enough entropy does NOT guarantee indistinguishability from randomness. Think of a 60-40 biased coin. Each flip gives you 0.97 bits of entropy, so if you want 64 bits of entropy, 66 flips gives it to you. But it's very easy to spot the 60-40 bias and see that the flips are not drawn uniformly from {heads,tails}. Running the flips through MD5 experimentally appears to get rid of any correlation (except for some very tricky adversarial constructions based on controlling the input) so that is what /dev/random does. But that is the exact same thing that urandom does. It's possible that some as-yet-unknown attack can find correlations in the md5 output and also in SHA256 or whatever. More recently there's been some theoretical advances, see these: http://en.wikipedia.org/wiki/Extractor http://citeseer.ist.psu.edu/barak03true.html so maybe that stuff can be used in implementations. I haven't looked into it enough to know if it makes sense. Chapter 10 of Schneier and Ferguson's "Practical Cryptography" also discusses how to write these system-level PRNG's. > That doesn't follow. Antoon is specifically warning that /dev/urandom is > non-blocking. If you knew there was enough entropy available, you > wouldn't need /dev/random -- but how do you know there's enough entropy? /dev/urandom can in fact screw you if you try to use it before the system has gathered enough entropy to give good output, such as while the system is still booting up. That is not a cryptographic algorithm vulnerability. It could also screw you if your system is somehow leaking information about its entropy pool (say through electromagnetic emissions from the memory bus). That is also not a cryptographic algorithm vulnerability. /dev/random does protect you somewhat from both of these screws. /dev/random does NOT protect you against sufficiently strong hypothetical attacks against the crypto algorithm. Overall, the situation is: 1) /dev/urandom is slightly bogus because it can produce output when there's almost no entropy in the system, i.e. during boot or immediately after boot. But once the system has been running for a while, the urandom output (in a real PC) is pretty good. 2) /dev/random is somewhat more bogus because it blocks when it's capable of producing good (computationally secure) output. Note that /dev/random's entropy estimates could in fact be wrong--for example, in a virtual PC (say a simulated one), there might be ZERO actual entropy (restarting the simulation might get you back to exactly the same state). 3) /dev/random and /dev/urandom are in principle BOTH vulnerable to cryptographic attacks. Some people incorrectly assume that this doesn't apply to /dev/random. So from an information-theoretic point of view, /dev/random and /dev/urandom are both bogus, but from a computational security point of view, the algorithms look ok (as best as we can tell), and if anything is irreparably wrong with them then all of cryptography is in trouble, so really neither is bogus in this regard. 4) The man page is fairly seriously bogus because it doesn't explain the real situation with either /dev/urandom or /dev/random. 5) Really, these modern algorithms are much harder to attack than fans of pre-computer (e.g. WW2-era) cryptography seem to imagine. These algorithms are very fast on modern computers but wouldn't have been practical without computers. Computers have extended the capabilities of both attackers and defenders, but it looks like they've given a lot more to the defenders (see Kahn "The Codebreakers" 2nd ed. note at the end: it says something like "in the long-running battle between cryptographers and cryptanalysts, it looks like the cryptographers have won). 6) For a sort of philosophical note on how cryptography fits in with the P vs. NP problem, this article is pretty cool: http://www.cs.ucsd.edu/users/russell/average.ps A brief summary is at: http://weblog.fortnow.com/2004/06/impagliazzos-five-worlds.html > For this specific application, it probably doesn't matter -- using /dev/ > urandom is surely overkill, and on a single-user Linux desktop you're > unlikely to have vast numbers of applications reading /dev/urandom > without your knowledge. But why not use /dev/random? What's the downside? /dev/random is in fact quite slow, like a few bits per second, not practical for dealing zillions of poker hands or whatever this application was. Once you exhaust the stored pool (a few hundred bytes or whatever) it takes quite a long time to get any more output. Also, it doesn't give the theoretical guarantees that some people imagine that it does. Aside from that, it's indistinguishable from /dev/urandom once /dev/urandom has enough entropy to get started. The right way for /dev/*random to work is block after system boot until there is some reasonable fixed amount of entropy (say 256 bits) gathered, then produce unlimited output without ever blocking again. Some ongoing folding of new entropy into the entropy pool (see the Fortuna algorithm in Schneier and Ferguson) is a good practical precaution, but really high security applications should consider the whole PC memory and CPU buses to be an insecure broadcast medium anyway, so such applications generally do their most sensitive operations in dedicated secure hardware. Sorry to go on for so long but it connects to a never-ending source of bogosity on sci.crypt (the other newsgroup I mostly hang out in), where several times a year someone shows up selling some bogus one-time-pad product based on supposed information-theoretic security, they're misguided 100% of the time and get shot down, but it always takes a while. My guess is that one of them is responsible for the ongoing sci.crypt sporge attack. From wizzardx at gmail.com Tue Sep 11 07:29:29 2007 From: wizzardx at gmail.com (David) Date: Tue, 11 Sep 2007 13:29:29 +0200 Subject: Python Database Apps In-Reply-To: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> Message-ID: <18c1e6480709110429i73bf7b40n902e3ac4b7c13e86@mail.gmail.com> > What is your favorite python - database combination? I'm looking to > make an app that has a local DB and a server side DB. I'm looking at > python and sqlite local side and sql server side. > > Any suggestions???? I like to use elixir [1] on top of sqlalchemy [2] [1] http://elixir.ematia.de/ [2] http://www.sqlalchemy.org/ From ldo at geek-central.gen.new_zealand Tue Sep 4 23:11:42 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 05 Sep 2007 15:11:42 +1200 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <5jn9qgFdmbcU3@mid.uni-berlin.de> <1188886461.236237.168230@y42g2000hsy.googlegroups.com> Message-ID: In message <1188886461.236237.168230 at y42g2000hsy.googlegroups.com>, Jason wrote: > The reason why the exception is more Pythonic is that the return value > is always a guaranteed good index into the list. How do you explain dict.get, then? From siona at chiark.greenend.org.uk Mon Sep 10 09:19:08 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 Sep 2007 14:19:08 +0100 (BST) Subject: /dev/null as a file-like object, or logging to nothing References: <87k5r1jdzq.fsf@wilson.homeunix.com> <5kg48jF33dv5U3@mid.uni-berlin.de> <87fy1pjbpl.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: >Marc 'BlackJack' Rintsch writes: >> `os.devnull`? >Yes, but I wasn't really sure how portable it is, in particular, on >Windows. Windows has a NUL: device which behaves like /dev/null . os.devnull is a wrapper around whatever the system-provided null device is. I guess the documentation should reflect this, rather than just mentioning POSIX and Mac OS 9 and requiring you to note the "defined for all platforms" at the start of the section. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From andrew.lee at nymag.com Wed Sep 12 18:13:58 2007 From: andrew.lee at nymag.com (Andrew F) Date: Wed, 12 Sep 2007 15:13:58 -0700 Subject: Error in random module, bad installation? Message-ID: <1189635238.655642.233240@g4g2000hsf.googlegroups.com> I'm a linux user and I just upgraded from 2.1 to 2.5 and changed the location of a number of libraries and tools. So far I've tracked most errors, but this one has me scratching my head : $ which python /usr/local/bin/python $ echo $PYTHONPATH /usr/local/bin/python $ python Python 2.5.1 (r251:54863, Sep 5 2007, 09:48:37) [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import random Unexpected error: Traceback (most recent call last): File "", line 1, in File "random.py", line 10, in x = random.random() TypeError: 'module' object is not callable >>> $ find /usr/local/ -name random.py ./lib/python2.5/random.py ./lib/python2.3/random.py Do I need to clobber 2.3? ( If so, why???) TIA -- Andrew From ed at leafe.com Tue Sep 11 09:25:54 2007 From: ed at leafe.com (Ed Leafe) Date: Tue, 11 Sep 2007 09:25:54 -0400 Subject: Python Database Apps In-Reply-To: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> Message-ID: <8AFA4F37-F8E1-47C4-B50A-BF26A0FAAA43@leafe.com> On Sep 10, 2007, at 10:52 PM, darien.watkins at gmail.com wrote: > Kindof a poll, kindof curiosity... > > What is your favorite python - database combination? I'm looking to > make an app that has a local DB and a server side DB. I'm looking at > python and sqlite local side and sql server side. Are you asking for opinions on what sort of database engine to use? Or are you trying to get a feel for what people use to develop their apps? Are you looking for a web app, or a desktop app, or a non-UI app? -- Ed Leafe -- http://leafe.com -- http://dabodev.com From jstroud at mbi.ucla.edu Fri Sep 14 15:25:22 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 14 Sep 2007 12:25:22 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189753968.917636.310120@19g2000hsx.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> <1189753968.917636.310120@19g2000hsx.googlegroups.com> Message-ID: Mark Summerfield wrote: > So to clarify, here's the entire API I'm proposing for ordereddict. In > all cases the ordereddict is always in (and kept in) key order, and > any method that returns a list or iterator always returns that list or > iterator (whether of keys or values) in key order: > > ordereddict(dictionary=None) > The argument can be a dict or another ordereddict; all the dict() > initializer > approaches should also be supported. > > ordereddict.update(dictonary=None, **kwargs) > Same as dict.update()---except that key order is preserved (a > point I won't > repeat in the others when I say "same as dict", but which is true > throughout) > > @classmethod > ordereddict.fromkeys(cls, iterable, value=None) # Same as dict > > ordereddict.key(index : int) -> key > Returns the index-th item's key > > ordereddict.item(index : int) -> (key, value) > Returns the index-th item > > ordereddict.value(index : int) -> value > Returns the index-th item's value > > ordereddict.set_value(index : int, value) > Sets the index-th item's value to value; raises IndexError if > index is out of > range. If not expensive, maybe return the key. > > ordereddict.copy() # Same as dict. > ordereddict.clear() # Same as dict. > ordereddict.get(key, value=None) # Same as dict > ordereddict.setdefault(key, value) # Same as dict > ordereddict.pop(key, value) # Same as dict > ordereddict.popitem() # Same as dict > > ordereddict.keys(fromindex : int = None, uptoindex : int : None) -> > list of keys > Returns an ordered list of keys, or a slice of keys if one or two > indexes is given > > ordereddict.values() # Same as dict > ordereddict.items() # Same as dict > ordereddict.iterkeys() # Same as dict > ordereddict.itervalues() # Same as dict > ordereddict.iteritems() # Same as dict > ordereddict.has_key() # Same as dict > > Also the same as dict (and as always, working in key order): > > for key in d: pass > if key in d: pass > len(d) > del d[key] > d[key] > d[key] = value May I also make one more suggestion, to call it a "sort_ordered_dict" (or "sortordereddict", or even better a "sorteddict"--where the "ed" comes from "ordered")? Its hard for me to move past the established definition of "order", as we think of tuples being ordered--as in the first sentence of http://en.wikipedia.org/wiki/Tuple--to something that is preserving an order according to a comparison. The distinction is so firmly ingrained in my head that it took me a while to wake up to the fact that you were describing something completely different than an ordered dictionary (e.g. http://www.voidspace.org.uk/python/odict.html) even though you were being very unambiguous with your description. And I also think the ability to drop it in for a built-in dict is very valuable. James From bdesth.quelquechose at free.quelquepart.fr Mon Sep 17 18:44:15 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 00:44:15 +0200 Subject: can Python be useful as functional? In-Reply-To: <13f00gv3gl3n43d@corp.supernews.com> References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> <13f00gv3gl3n43d@corp.supernews.com> Message-ID: <46f0243b$0$32214$426a74cc@news.free.fr> Grant Edwards a ?crit : > On 2007-09-18, Steve Holden wrote: > >>Lorenzo Stella wrote: >>[...] >> >>>My question is: how can we call a language "functional" if >>>it's major implementation has a limited stack? Or is my code >>>wrong? >> >>So, which environment do you habitually use that provides an >>*unlimited* stack? > > Perhaps Lorenzo Stella is referring to Python's lack of > tail-recursion optimization? There are languages that > guarantee unlimited tail-recursion with a limited stack. > > That's a typical feature for a function language, right? > And also for some implementations of some purely procedural languages IIRC. From tec at knology.net Mon Sep 10 14:38:50 2007 From: tec at knology.net (Tim) Date: Mon, 10 Sep 2007 11:38:50 -0700 Subject: memcpy Message-ID: <1189449530.171049.323230@22g2000hsm.googlegroups.com> How do I memcpy from a pointer to an array of floats in python? I get errors: NameError: global name 'row' is not defined I want to be able to get the row[i] array element. In C I would normally place the address of row as the first argument. cdll.msvcrt.memcpy( row, pData, 256 ) If I define row as the following I also get the following error: row = ones( TOTAL_PARAMETER_ENTRIES, dtype=float ) ArgumentError: argument 1: : Don't know how to convert parameter 1 Thanks From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 21 03:39:44 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 21 Sep 2007 09:39:44 +0200 Subject: about __str__ In-Reply-To: References: Message-ID: <46f37540$0$16854$426a74cc@news.free.fr> Konstantinos Pachopoulos a ?crit : > Hi, > i have the following class: > =========================================== > class CmterIDCmts: def __init__(self,commiterID,commits): > self.commiterID_=long(commiterID) > self.commits_=long(commits) > > def __str__(self): > s="" > s+="<"+str(self.commiterID_)+":"+str(self.commits_)+">" > return s def __str__(self): return "<%s:%s>" % (self.commiterID_, self.commits_) From tdwdotnet at gmail.com Thu Sep 20 19:10:32 2007 From: tdwdotnet at gmail.com (Tim Williams) Date: Fri, 21 Sep 2007 00:10:32 +0100 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <9afea2ac0709201604i3a4510e1o8edc8fa01bcd5432@mail.gmail.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <9afea2ac0709201604i3a4510e1o8edc8fa01bcd5432@mail.gmail.com> Message-ID: <9afea2ac0709201610oc3d13d7n91d590fcdbb7e30b@mail.gmail.com> On 21/09/2007, Tim Williams wrote: > On 20/09/2007, Python Maniac wrote: > > I am new to Python however I would like some feedback from those who > > know more about Python than I do at this time. > > > > def scrambleLine(line): > > s = '' > > for c in line: > > s += chr(ord(c) | 0x80) > > return s > > > > def descrambleLine(line): > > s = '' > > for c in line: > > s += chr(ord(c) & 0x7f) > > return ''.join( [chr(ord(c) & 0x7f) for c in line] ) > > > > def scrambleFile(fname,action=1): > > if (path.exists(fname)): > > try: > > f = open(fname, "r") > > toks = fname.split('.') > > while (len(toks) > 2): > > toks.pop() > > fname = '.'.join(toks) > > if (action == 1): > > _fname = fname + '.scrambled' > > elif (action == 0): > > _fname = fname + '.descrambled' > > if (path.exists(_fname)): > > os.remove(_fname) > > ff = open(_fname, "w+") > > if (action == 1): > > for l in f: > > ff.write(scrambleLine(l)) > > elif (action == 0): > > for l in f: > > ff.write(descrambleLine(l)) > > except Exception, details: > > print 'ERROR :: (%s)' % details > > finally: > > f.close() > > ff.close() > > else: > > print 'WARNING :: Missing file "%s" - cannot continue.' % fname > > > > -- > > > def scrambleLine(line): > return ''.join( [chr(ord(c) | 0x80) for c in line] ) > > def descrambleLine(line): > return ''.join( [chr(ord(c) & 0x7f) for c in line] ) > > def scrambleFile(fname,action=1): > try: > f = open(fname, "r") > fname = '.'.join(fname.split('.')[:2]) > if action: > _fname = fname + '.scrambled' > else: > _fname = fname + '.descrambled' > ff = open(_fname, "w") > if action: > ff.write('\r\n.join([scrambleLine(l) for l in f ])) > else : > ff.write('\r\n.join([descrambleLine(l) for l in f ])) > f.close() > ff.close() > except Exception, details: > print 'ERROR :: (%s)' % details > > HTH :) > or maybe even this: Apologies for the self-reply, its late here ! (a couple of typos fixed too! ) def scrambleFile(fname,action=1): try: f = open(fname, "r") fname = '.'.join(fname.split('.')[:2]) if action: ff = open(fname + '.scrambled', "w") ff.write('\r\n'.join([scrambleLine(l) for l in f ])) else : ff = open(fname + '.descrambled', "w") ff.write('\r\n'.join([descrambleLine(l) for l in f ])) f.close() ff.close() except Exception, details: print 'ERROR :: (%s)' % details :) From bignose+hates-spam at benfinney.id.au Mon Sep 24 21:20:59 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 25 Sep 2007 11:20:59 +1000 Subject: Nested For and While Statements References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190666647.199890.174670@o80g2000hse.googlegroups.com> Message-ID: <874phjpmkk.fsf@benfinney.id.au> Roberto Bonvallet writes: > On Sep 24, 3:28 pm, kou... at hotmail.com wrote: > > [...] where I start getting some errors. > > I'm hoping I won't have to post my code > > "Doctor, I'm feeling bad. I hope I won't have to tell you my > symptoms. What do I have?" > > Please provide the actual errors and the actual code. It is easier, > less error prone and more useful to copy and paste them instead of > writing some pseudocode. Far better is to ask the querent to provide a minimal example that demonstrates the problem. "Minimal" in this case means "if I take away any part of this code, the described behaviour no longer occurs". While that's not true, keep whittling away at the example code until it *is* true, so we know that all the code is necessary to repeat the problem. Only then should you post the code ? if, of course, you haven't yet seen the solution with your own eyes. -- \ "Laurie got offended that I used the word 'puke.' But to me, | `\ that's what her dinner tasted like." -- Jack Handey | _o__) | Ben Finney From steve at holdenweb.com Fri Sep 14 08:47:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Sep 2007 08:47:18 -0400 Subject: recursion In-Reply-To: References: Message-ID: Gigs_ wrote: > sorry i think that i express wrong. having problem with english > > > what i mean is how python knows to add all thing at the end of recursion > > >>> def f(l): > if l == []: > return [] > else: > return f(l[1:]) + l[:1] > > > f([1,2,3]) > > recursion1 f([2,3]) + [1] > > recursion2 f([3]) + [2] or [2, 1]? > > recursion3 f([]) + [3] or [3, 2, 1] > > > i dont get all this > > >>> def f(l): > if l == []: > print l > return [] > else: > return f(l[1:]) + l[:1] > > >>> f([1,2,3]) > [] > [3, 2, 1] # how this come here? how python save variables from each recursion? > > > sorry again for first post > I think the thing you are missing is that the recursive call f(l[1:]) in the return statement causes the current call to be suspended until the recursive call is complete. The new call has its own value for l, which is the caller's l[1:]. Each new call creates a completely new namespace. A less complicated function might make it a little more obvious. def factorial(n): print "n =", n if n=0: return 1 else: return n * factorial(n-1) Try running that with a few different arguments to show you how the recursion works. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From jcd at sdf.lonestar.org Mon Sep 10 22:55:43 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 10 Sep 2007 22:55:43 -0400 Subject: Enum class with ToString functionality In-Reply-To: <1189478288.237609.25140@50g2000hsm.googlegroups.com> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <87bqca9hrw.fsf@benfinney.id.au> <1189472591.797327.189180@w3g2000hsg.googlegroups.com> <87sl5m7xxm.fsf@benfinney.id.au> <1189478288.237609.25140@50g2000hsm.googlegroups.com> Message-ID: <46E603AF.3050900@sdf.lonestar.org> TheFlyingDutchman wrote: > On Sep 10, 7:12 pm, Ben Finney > wrote: >> TheFlyingDutchman writes: >>>> >> (Please preserve attribution lines so it's clear who wrote what.) >> >> >>> Looking at the documentation it looks excellent. But I don't >>> understand the 0.4.2 version number, >> Note the tag that says the "Development Status" is "Beta". >> >>> particularly when you refer to it as robust. >> I assume you're referring to the short description, "Robust >> enumerated type support in Python". >> >> That refers to the implemented type as robust, not the state of >> the code. That is, the short description should be read as >> "Support, in Python, for robust enumerated types". It's a >> description of the package functionality. >> >> If, of course, the state of the code is not robust, that's a bug >> that needs to be fixed; but that's true for any package. >> >> -- \ "Try to become not a man of success, but try rather to >> become a | `\ man of value." >> -Albert Einstein | _o__) >> | Ben Finney > > What is the difference between this version and the 1.0 version? > Uh... The 1.0 version is vaporware? Cheers, Cliff From stef.mientki at gmail.com Sun Sep 9 17:06:19 2007 From: stef.mientki at gmail.com (stef mientki) Date: Sun, 09 Sep 2007 23:06:19 +0200 Subject: Modul (%) in python not like in C? In-Reply-To: <46E4466C.2030303@sdf.lonestar.org> References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> <46E4466C.2030303@sdf.lonestar.org> Message-ID: <46E4604B.4020301@gmail.com> J. Cliff Dyer wrote: > Dotan Cohen wrote: > >> FIrst of all, how is the % symbol (as in 70%6=4) called in English? >> >> Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or >> the other in error? Is this a known gotcha? I tried to google the >> subject however one cannot google the symbol %. Thanks in advance. >> >> Dotan Cohen >> >> > > The % operator is called "modulo" in English. I don't think the > difference in implementation is an error. It's just a difference of > calculation method. > > Python will always yield a number x = m%n such that 0 <= x < n, but > Turbo C will always yield a number such that if x = m%n -x = -m%n. That > is, since 111 % 10 = 1, -111 % 10 = -1. The two values will always > differ by n (as used above). > > I'm sure there are mathematicians on the list who can give you a more > technical, precise explanation of the reasons for the different results. > > It's a long time ago, but if I remember well, "modulo" was introduced as an operator in Galois fields theory, and Galois fields only exists of the whole numbers 0 .. N-1. So the Python implementation seems the only correct one. Most languages handle it wrong (I didn't know until now Python was so correct ;-) so you always have to add N (sometimes even more than once) manually (to get valid results) x = (N + (some kind of formula that can have a negative result) ) % N cheers, Stef From lorenzo.digregorio at gmail.com Mon Sep 17 19:10:20 2007 From: lorenzo.digregorio at gmail.com (Lorenzo Di Gregorio) Date: Mon, 17 Sep 2007 23:10:20 -0000 Subject: "once" assigment in Python In-Reply-To: <1uSdnaFGwMuICHPbnZ2dnUVZ_tijnZ2d@comcast.com> References: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> <1uSdnaFGwMuICHPbnZ2dnUVZ_tijnZ2d@comcast.com> Message-ID: <1190070620.926481.56620@k79g2000hse.googlegroups.com> On 17 Sep., 16:54, Larry Bates wrote: > > IMHO variables like what you describe are really data not program variables. > You might consider putting variables like these in a dictionary and then check > to see if the keys exist before assignment: > > var_dict={} > > # > # See if 'varname' initialized, if not it needs to be > # > if 'varname' not in var_dict: > var_dict[varname]=somevalue This is a good point! I could write something like: instantiate('component',function) and have instantiate() to conditionally do: instance['component']=Module(function) Of course this means using: instance['component'].method() instead of just: component.method() A more annoying difficulty is with the fact that, while the scope of ordinary variables is limited (function, package), the scope of 'component' would be global (the whole instance[]): having global names could be pretty annoying in modeling a hierarchy. Anyway, some scoping mechanism could be implemented over the global dictionary and this could be a good price to pay to avoid other tricks. Further suggestions? Thank you! Lorenzo From demoncleaner13 at hotmail.com Sat Sep 29 13:53:57 2007 From: demoncleaner13 at hotmail.com (dcleaner) Date: Sat, 29 Sep 2007 17:53:57 +0000 (UTC) Subject: xml modifications Message-ID: hi there...i'm a begginer level user and i've stumbbled upon a problem a bit beyond my knowledge. i hope that somebody will be able to help me with my problem... the problem is: i'm transforming an Access database to XML with some adjustements. basicaly i have one main table in which i have my main data and keys to other tables containing other relevant data. after exporting my main table to xml i have in some tags only keys to other tables. and now i want to change those keys to meaningful data. for instance: after exporting, i have a line like this: 1, and i want to change it to be just an opening tag for something else; .the data which must be written in attr1 and attr2 depends upon the number (in this case number 1) inside the tag (tagZ). From python at rcn.com Wed Sep 26 13:59:52 2007 From: python at rcn.com (Raymond Hettinger) Date: Wed, 26 Sep 2007 10:59:52 -0700 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190710402.481693.5110@50g2000hsm.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> Message-ID: <1190829592.800804.242260@50g2000hsm.googlegroups.com> [Mark Summerfield] > Below is a PEP proposal for a sorteddict. It arises out of a > discussion on this list that began a few weeks ago with the subject of > "An ordered dictionary for the Python library?" It is worth remembering that the long sought after datatype was a dict that could loop over keys in *insertion* order, not based on some function of the key itself. > If there is positive feedback I will submit the PEP to the reviewers, > so if you think it is a good idea please say so. As one who was submitted many PEPs, I can advise that the quickest way to irrevocably kill an idea is to submit a PEP to early (we almost didn't get genexps because the PEP was submitted pre-maturely). Instead, I advise posting an ASPN recipe so the details can be hammered-out and a fan club can be grown. For this particular idea, I am -1 on inclusion in the standard library. The PEP focuses mainly on implementation but is weakest in the rationale section. Its advantages over "for k in sorted(d)" are miniscule. To be considered for the collections module, there needs to be compelling use case advantages either in terms of usability or performance. After grepping through my accumulated code base for "sorted", I see remarkably few places where sortdict would have be preferred and in those few cases, the advantage was so slight that the code would not be worth changing. The majority of dictionary sorts are characterized by fully building a dictionary and then sorting it. In those cases, sortdict merely offers a different spelling and adds a small performance cost during key insertion. The sortdict has some potential in the comparatively rare case of a long lived dictionary where periodic sorted key requests are interleaved with operations that mutate the dictionary. In those cases, the separate tracking of added/removed keys may save some sorting effort; however, there is an offsetting cost of many __hash__/__cmp__ calls in the list comprehension update and the modest savings was in all cases trivialized by cost of whatever was initiating the dictionary mutations (user inputs or web updates). Also, there were cases when the sortdict was at a distinct disadvantage. In those cases, there were multiple key functions (key=record.name or key=record.date or key=record.size). There standard approach using sorted() creates three separate sorted lists and only one dict. In contrast, the sortdict approach would need three sortdicts each with their own dict and sorted list. IMHO, the collections module should be saved for something much more powerful and generic like a dictionary that generates a callback whenever it is mutated. A datatype like that would have it much easier for you to implement something like this sortdict or the long sought after dict that remembers its key insertion order. Raymond From gagsl-py2 at yahoo.com.ar Thu Sep 6 21:56:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Sep 2007 22:56:05 -0300 Subject: Using wild character References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> <1189058095.671230.262190@o80g2000hse.googlegroups.com> <5k9pjoF2mrncU1@mid.uni-berlin.de> <1189122511.231602.217710@w3g2000hsg.googlegroups.com> <1189127996.212274.281760@w3g2000hsg.googlegroups.com> Message-ID: En Thu, 06 Sep 2007 22:19:56 -0300, TheFlyingDutchman escribi?: > The Perl community has an expression "There is more than one way to do > it". As in, Perl is good because you have multiple choices (whether > it's a function/module/class/operator) of how to implement a > particular piece of logic. More choices is often good, but this can > lead to a problem in that you might be presented with more things to > learn and or you come across less common ways of doing something that > you are not familiar with in code you are trying to understand. > > Does the Python community have a position regarding duplicate ways in > the language to achieve something in your code? Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> import this -- Gabriel Genellina From fredrik at pythonware.com Thu Sep 27 14:17:00 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Sep 2007 20:17:00 +0200 Subject: ValueError: too many values to unpack,>>> In-Reply-To: <46FBED79.6070207@comcast.net> References: <5m24sfFatlbuU1@mid.uni-berlin.de> <46FBED79.6070207@comcast.net> Message-ID: Shawn Minisall wrote: > Sorry, it looks like it's on the fourth line with the 3 values on line > 4...its reading line 3 fine > > Traceback (most recent call last): > File "", line 1, in > main() > File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line 33, > in main > deposit1, deposit2, deposit3 = string.split(line, "\t") > ValueError: too many values to unpack instead of fumbling around in the dark, try inserting a print statement before the offending line, so you can see what you're trying to unpack: print string.split(line, "\t") # see what it is deposit1, deposit2, deposit3 = string.split(line, "\t") From earnloads007 at gmail.com Fri Sep 14 16:37:34 2007 From: earnloads007 at gmail.com (earnloads007 at gmail.com) Date: Fri, 14 Sep 2007 20:37:34 -0000 Subject: Make money to share your videos Message-ID: <1189802254.119448.78620@r29g2000hsg.googlegroups.com> Goodtolove.com is sharing their 50% adsense revenue with you to post videos of anything. Just keep up logging in and start posting now to make money... From steve at REMOVE-THIS-cybersource.com.au Sat Sep 15 20:07:08 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 00:07:08 -0000 Subject: Can You Program? References: <1189679878.271415.88700@w3g2000hsg.googlegroups.com> <1189865720.546424.155860@d55g2000hsg.googlegroups.com> Message-ID: <13eostc9kfukl9e@corp.supernews.com> On Sat, 15 Sep 2007 14:15:20 +0000, brus stoc at gmail dot com wrote: [snip spam] > Hey, thanks for spamming our group. You know, there are probably millions of people who never received the original spam because their Usenet provider does a good job of filtering out crud, and they wouldn't even know it existed, except that YOU decided you had to be a big man by engaging the spammer in conversation. Did you really think even for a millisecond that the spammer actually hangs around long enough to read replies to his spam? All I can say is, thank goodness for automated Baysian filters, because now your email address is associated with spam in thousands of filters across the world, reducing the chances of us seeing posts from you. I think that's a good thing. -- Steven. From hat at se-162.se.wtb.tue.nl Mon Sep 10 09:48:44 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 10 Sep 2007 15:48:44 +0200 Subject: Using a time duration to print out data where every 2 seconds is a pixel References: <1189427545.322679.260970@r29g2000hsg.googlegroups.com> Message-ID: On 2007-09-10, cjt22 at bath.ac.uk wrote: > I want to be able print out the Steps as a visual representation so > that I can show > 1. The order the steps started > 2. The duration of the steps > > i.e. a print out such as: > > > [ a ] > [ b ] > [ c ] This graph is commonly known as a Gantt Chart. The most common use case of such charts is project planning. The newest GNU plot program has support for these charts afaik. > Another related question is that I can't seem to do arithmetic when > the variables are in String format > of %H:%M:%S or converted to type struct_time True (but you already detected that). Either convert your struct_times to floats (time.mktime), or use a date/time module specialized in computing with dates and times. (I have seen references to a module called datetime, but I have never used such a module so no idea what it is or where to get it). Sincerely, Albert From ajmacd at ns.sympatico.ca Wed Sep 19 12:19:38 2007 From: ajmacd at ns.sympatico.ca (Aaron J. M.) Date: Wed, 19 Sep 2007 09:19:38 -0700 Subject: Deserializing specific objects from a file In-Reply-To: <5lbu7aF78tegU1@mid.uni-berlin.de> References: <1190156558.313252.31000@y27g2000pre.googlegroups.com> <5lbu7aF78tegU1@mid.uni-berlin.de> Message-ID: <1190218778.852249.167280@y27g2000pre.googlegroups.com> That's exactly what I needed. Thank you. Aaron J. M. From m.n.summerfield at googlemail.com Fri Sep 14 06:56:55 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Fri, 14 Sep 2007 10:56:55 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> <1189753968.917636.310120@19g2000hsx.googlegroups.com> Message-ID: <1189767415.814718.312870@k79g2000hse.googlegroups.com> On 14 Sep, 10:49, Antoon Pardon wrote: > On 2007-09-14, Mark Summerfield wrote: > > > > > On 14 Sep, 02:35, J?rgen Urner wrote: > >> Puh, what a discussion... most common use case I can think of is > > >> >> d = {'a': 1, 'b': 2, 'c': 3} > >> >> for key in d: > >> >> # do something that relies on order of keys as specified in the constructor > > >> It's a bit tireing having to type > > >> >> for key in sorted(d.keys()): > >> >> do_somethig_with(d[key]) > > >> instead of a trustfully > > >> >> for value in d.values(): > >> >> do_somethig_with(value) > > >> As far as I can see much cleaner. No black magic needed ++ sort the > >> dict > >> to another order and rely on the sort order being stable would be a > >> really > >> a nice thing to have. > > >> My 2 cents, J?rgen > > > What I envisage is: > > > d = ordereddict(a=1, x=20, b=35, m=4) > > # some time later > > d["e"] = 15 > > # later still > > d["b"] = 70 > > d.keys() # returns ['a', 'b', 'e', 'm', 'x'] > > d.values() # returns [1, 70, 15, 4, 20] > > which seems to be exactly what my avltree module mentioned earlier > provides. > > >>> from avltree import Tree > >>> d=Tree(a=1, x=20, b=35, m=4) > >>> d["e"] = 15 > >>> d["b"] = 70 > >>> d.keys() > > ['a', 'b', 'e', 'm', 'x']>>> d.values() > > [1, 70, 15, 4, 20] Antoon, Your AVL tree looks impressive (although it has five times the lines of my ordereddict), but it does not appear to support dict.update()'s API (which was extended in 2.4), so you can't do: avl.update({'g': 20}, a=9, b=22). Also, it does not provide the key(), value(), and item() methods that the API I proposed can support (because in an ordereddict, index positions make sense). If there was consensus on an API and you, me, and others had different implementations, we could always come up with some tests to compare their relative performance, and put the fastest one(s) forward in a PEP. (I don't care if my own code is used or not, it is the functionality in Python's standard library that I want, whoever's code it is.) From cjw at sympatico.ca Fri Sep 28 17:03:23 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 28 Sep 2007 17:03:23 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191007754.740566.137510@n39g2000hsh.googlegroups.com> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> Message-ID: <46FD6C1B.3010503@sympatico.ca> TheFlyingDutchman wrote: >> Or bind resources of these pocket protectors that otherwise would lead to >> answers for people that do seek enlightment... > > I don't think it would be correct to characterize my posts as not > seeking enlightenment. I do also happen to voice my opinion which > seems appropriate since this can be characterized as a discussion > group. It theoretically is possible for a discussion group to tolerate > opinions that diverge from the majority. +1 > > One issue I have with this group and that I encountered many years ago > in the Perl group is that there is no separate group > comp.lang.python.beginner where you can ask questions without getting > hit with RTFM! and the like. > From hg at nospam.org Sat Sep 8 08:34:49 2007 From: hg at nospam.org (hg) Date: Sat, 08 Sep 2007 05:34:49 -0700 Subject: ANN: Load binary application into a BasiCard from Python Message-ID: Hi, Based on the already released SCF, the code is there: http://snakecard.com/Source/Applications/SCF/Load_BC.zip. hg From JohnRoth1 at jhrothjr.com Fri Sep 14 17:58:43 2007 From: JohnRoth1 at jhrothjr.com (John Roth) Date: Fri, 14 Sep 2007 14:58:43 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: <1189618530.872819.136450@57g2000hsv.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> Message-ID: <1189807123.163995.104180@g4g2000hsf.googlegroups.com> On Sep 12, 11:35 am, TheFlyingDutchman wrote: > On Sep 12, 4:40 am, Bjoern Schliessmann wrote: > > Ivan Voras wrote: > > > What does "self" have to do with an object model? It's an > > > function/method argument that might as well be hidden in the > > > compiler without ever touching the role it has (if not, why?). I > > > agree that it's needless noise in a language. > > > If this was needless, why do C++ and Java have the "this" pointer? > > "this" in C++ and Java is not shown in the parameter list, which was > what he was > complaining about. He wants > > class MyClass: > def SomeFunction(someParameter): > self.someParameter = someParameter > > not > > class MyClass: > def SomeFunction(self, someParameter): > self.someParameter = someParameter > > The confusing way about the current Python method when you first > encounter it is > why is "self" being passed in when you write the function but not > when you call it. If the compiler is smart enough to know that > > a = MyClass() > a.SomeFunction(12) > > SomeFunction() has a "self" implicitly added to the parameter list, it > seems that it should be smart enough to know that a function defined > in a class has a "self" implicitly added to the parameter list. Pretty close. This is one of the things that's always puzzled me about the discussion. Making self and cls keyword pseudo-constants that get the current instance and class from the stack frame (or raise an exception) would eliminate them from the method header. It would ALSO eliminate a whole level of indirection in method invocation and get rid of the instancemethod, classmethod and staticmethod wrapper classes. This would be a significant simplification. If it had been done earlier, it would have eliminated most of the justification for method attributes (those silly @ things), thus showing that unneeded complexity breeds more unneeded complexity. John Roth From sjmachin at lexicon.net Fri Sep 14 18:04:01 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 14 Sep 2007 15:04:01 -0700 Subject: recursion In-Reply-To: References: <5kvbn3F5h7l3U1@mid.uni-berlin.de> Message-ID: <1189807441.524993.15070@50g2000hsm.googlegroups.com> On Sep 15, 3:06 am, "Terry Reedy" wrote: > > There have been languages, for instance, Fortran IV, where local variables > were part of the function 'object' and which therefore prohibited recursion > because of the very problem you alluded to in your question. (My guess is > the functions had an InUse flag that was checked when the function was > called.) No way. Waste of space for instructions to check the flag at the start and reset it at the end. Waste of CPU time. Divide by zero? Subroutine calls itself? Drive against the traffic flow on the freeway? Expected outcome: crash or other unwanted result. Simple: don't do that! Why bother checking? No self-respecting FORTRAN programmer would want to use recursion anyway. And mixed case in a variable name? Sheesh. From steven.bethard at gmail.com Fri Sep 28 00:33:47 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Sep 2007 22:33:47 -0600 Subject: Numeric command-line options vs. negative-number arguments In-Reply-To: <87ejgj4lpy.fsf_-_@benfinney.id.au> References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <0a6dnQmBPIzuqmHbnZ2dnUVZ_vihnZ2d@comcast.com> <87ejgj4lpy.fsf_-_@benfinney.id.au> Message-ID: Ben Finney wrote: > Steven Bethard writes: > >> In most cases, argparse (http://argparse.python-hosting.com/) >> supports negative numbers right out of the box, with no need to use >> '--': >> >> >>> import argparse >> >>> parser = argparse.ArgumentParser() >> >>> parser.add_argument('-a', type=int) >> >>> parser.add_argument('b', type=int) >> >>> args = parser.parse_args('-a -42 -123'.split()) >> >>> args.a >> -42 >> >>> args.b >> -123 > > That would be irritating. I've used many programs which have numbers > for their options because it makes the most sense, e.g. 'mpage' to > indicate number of virtual pages on one page, or any number of > networking commands that use '-4' and '-6' to specify IPv4 or IPv6. Did you try it and find it didn't work as you expected? Numeric options seem to work okay for me:: >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('-1', dest='one', action='store_true') >>> args = parser.parse_args(['-1']) >>> args.one True Argparse knows what your option flags look like, so if you specify one, it knows it's an option. Argparse will only interpret it as a negative number if you specify a negative number that doesn't match a known option. STeVe From gagsl-py2 at yahoo.com.ar Fri Sep 21 18:15:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Sep 2007 19:15:47 -0300 Subject: elementtree question References: Message-ID: En Fri, 21 Sep 2007 11:49:53 -0300, Tim Arnold escribi?: > Hi, I'm using elementtree and elementtidy to work with some HTML files. > For > some of these files I need to enclose the body content in a new div tag, > like this: > >

> original contents... >
> > > I figure there must be a way to do it by creating a 'div' SubElement to > the > 'body' tag and somehow copying the rest of the tree under that > SubElement, > but it's beyond my comprehension. import xml.etree.ElementTree as ET source = """Test original contents... 2&3 some text

Another paragraph

""" tree = ET.XML(source) body = tree.find("body") newdiv = ET.Element('div', {'class':'remapped'}) newdiv.append(body) bodyidx = tree.getchildren().index(body) tree[bodyidx]=newdiv ET.dump(tree) -- Gabriel Genellina From bh at izb.knu.ac.kr Sun Sep 30 09:52:43 2007 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Sun, 30 Sep 2007 22:52:43 +0900 Subject: Can you please give me some advice? In-Reply-To: <13fuv0gh7342r27@corp.supernews.com> References: <13fuv0gh7342r27@corp.supernews.com> Message-ID: <1191160363.2127.21.camel@viola.izb.knu.ac.kr> On Sun, 2007-09-30 at 10:36 +0000, Steven D'Aprano wrote: [...snip...] > Sorry about the English. That's alright. I am always struggling against English. It is not strange now. Thank you for your kindness. Byung-Hee From tjreedy at udel.edu Tue Sep 18 19:27:58 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Sep 2007 19:27:58 -0400 Subject: The meaning of a = b in object oriented languages References: <1190094057.976729.285120__39064.8685548969$1190094417$gmane$org@n39g2000hsh.googlegroups.com> Message-ID: "Summercool" wrote in message news:1190094057.976729.285120__39064.8685548969$1190094417$gmane$org at n39g2000hsh.googlegroups.com... In Python, names are names. They get associated with or bound to objects. b= means associate name b with the object resulting from evaulating the expression. So b = a means associate b with the object 'currently' bound to a. Your discussion of pointers, bytes, and integer-addressed memory locations is correct as to the CPython implementation of Python. But these are not part of the semantics of Python itself as an algorithm language. Unlike with C, we humans can read, understand, and execute Python code without mentally simulating a linear-memory computer. That is part of what makes it easier to read. Terry Jan Reedy From f.braennstroem at gmx.de Sat Sep 15 12:57:27 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sat, 15 Sep 2007 16:57:27 +0000 Subject: extract text from log file using re In-Reply-To: References: Message-ID: Hi to all, thanks for your help. The approach print '\r\n'.join([x.strip() for x in open('c:/flutest.txt') if 'e-0' in x]) works quite well :-) Greetings! Fabian Fabian Braennstroem schrieb am 09/13/2007 09:09 PM: > Hi, > > I would like to delete a region on a log file which has this > kind of structure: > > > #------flutest------------------------------------------------------------ > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > reversed flow in 1 faces on pressure-outlet 35. > > Writing > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.cas"... > 5429199 mixed cells, zone 29, binary. > 11187656 mixed interior faces, zone 30, binary. > 20004 triangular wall faces, zone 31, binary. > 1104 mixed velocity-inlet faces, zone 32, binary. > 133638 triangular wall faces, zone 33, binary. > 14529 triangular wall faces, zone 34, binary. > 1350 mixed pressure-outlet faces, zone 35, binary. > 11714 mixed wall faces, zone 36, binary. > 1232141 nodes, binary. > 1232141 node flags, binary. > Done. > > > Writing > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.dat"... > Done. > > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 > 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 > > reversed flow in 2 faces on pressure-outlet 35. > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > #------------------------------------------------------------------ > > I have a small script, which removes lines starting with > '(re)versed', '(i)teration' and '(t)urbulent' and put the > rest into an array: > > # -- plot residuals ---------------------------------------- > import re > filename="flutest" > reversed_flow=re.compile('^\ re') > turbulent_viscosity_ratio=re.compile('^\ tu') > iteration=re.compile('^\ \ i') > > begin_of_res=re.compile('>\ \ \ i') > end_of_res=re.compile('^\ ad') > > begin_of_writing=re.compile('^\Writing') > end_of_writing=re.compile('^\Done') > > end_number=0 > begin_number=0 > > > n = 0 > for line in open(filename).readlines(): > n = n + 1 > if begin_of_res.match(line): > begin_number=n+1 > print "Line Number (begin): " + str(n) > > if end_of_res.match(line): > end_number=n > print "Line Number (end): " + str(n) > > if begin_of_writing.match(line): > begin_w=n+1 > print "BeginWriting: " + str(n) > print "HALLO" > > if end_of_writing.match(line): > end_w=n+1 > print "EndWriting: " +str(n) > > if n > end_number: > end_number=n > print "Line Number (end): " + str(end_number) > > > > > > n = 0 > array = [] > array_dummy = [] > array_mapped = [] > > mapped = [] > mappe = [] > > n = 0 > for line in open(filename).readlines(): > n = n + 1 > if (begin_number <= n) and (end_number > n): > # if (begin_w <= n) and (end_w > n): > if not reversed_flow.match(line) and not > iteration.match(line) and not > turbulent_viscosity_ratio.match(line): > m=(line.strip().split()) > print m > if len(m) > 0: > # print len(m) > laenge_liste=len(m) > # print len(m) > mappe.append(m) > > > #--end plot > residuals------------------------------------------------- > > This works fine ; except for the region with the writing > information: > > #-----writing information > ----------------------------------------- > Writing "/home/fb/fluent-0500.cas"... > 5429199 mixed cells, zone 29, binary. > 11187656 mixed interior faces, zone 30, binary. > 20004 triangular wall faces, zone 31, binary. > 1104 mixed velocity-inlet faces, zone 32, binary. > 133638 triangular wall faces, zone 33, binary. > 14529 triangular wall faces, zone 34, binary. > 1350 mixed pressure-outlet faces, zone 35, binary. > 11714 mixed wall faces, zone 36, binary. > 1232141 nodes, binary. > 1232141 node flags, binary. > Done. > # -------end writing information ------------------------------- > > Does anyone know, how I can this 'writing' stuff too? The > matchingIt occurs a lot :-( > > Regards! > Fabian > From rcdailey at gmail.com Tue Sep 25 10:50:44 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 25 Sep 2007 09:50:44 -0500 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> Message-ID: <496954360709250750p5d409806ga5914e8c7ad38cf1@mail.gmail.com> Awesome description. This was more than helpful. I'm really grateful that you took the time to outline that for me. I really understand it now. However, as I mentioned in the lxml mailing list, I'm starting to learn more towards regular expressions being a very LAST resort to solving problems like this. In my specific case, I have a better choice which is the etree parser. It does all of this for me (as you so kindly stated before). I hope this is the correct attitude to have. Being a C++ developer, I normally don't admire unmanageable and unreadable code (this is especially true with regular expressions). They're very useful, but again I believe it should be a last resort. Thanks again for your help. On 9/24/07, Gabriel Genellina wrote: > > En Mon, 24 Sep 2007 23:51:57 -0300, Robert Dailey > escribi?: > > > What I meant was that it's not an option because I'm trying to learn > > regular > > expressions. RE is just as built in as anything else. > > Ok, let's analyze what you want. You have for instance this text: > "" > which should become > "" > > You have to match: > (opening angle bracket)(any word)(closing angle bracket)(opening angle > bracket)(slash)(same word as before)(closing angle bracket) > > This translates rather directly into this regular expression: > > r"<(\w+)>" > > where \w+ means "one or more alphanumeric characters or _", and being > surrounded in () creates a group (group number one), which is > back-referenced as \1 to express "same word as before" > The matched text should be replaced by (opening <)(the word > found)(slash)(closing >), that is: r"<\1/>" > Using the sub function in module re: > > py> import re > py> source = """ > ... > ... > ... > ... > ... """ > py> print re.sub(r"<(\w+)>", r"<\1/>", source) > > > > > > > Now, a more complex example, involving tags with attributes: > --> > > You have to match: > (opening angle bracket)(any word)(any sequence of words,spaces,other > symbols,but NOT a closing angle bracket)(closing angle bracket)(opening > angle bracket)(slash)(same word as before)(closing angle bracket) > > r"<(\w+)([^>]*)>" > > [^>] means "anything but a >", the * means "may occur many times, maybe > zero", and it's enclosed in () to create group 2. > > py> source = """ > ... > ... > ... """ > py> print re.sub(r"<(\w+)([^>]*)>", r"<\1\2 />", source) > > > > > Next step would be to allow whitespace wherever it is legal to appear - > left as an exercise to the reader. Hint: use \s* > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Sep 3 05:41:05 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 03 Sep 2007 19:41:05 +1000 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1188803759.498517.198900@g4g2000hsf.googlegroups.com> Message-ID: <87tzqc9jda.fsf@benfinney.id.au> Michele Simionato writes: > On Sep 3, 2:21 am, llothar wrote: > > I'm afraid that the GIL is killing the usefullness of python for > > some types of applications now where 4,8 oder 64 threads on a chip > > are here or comming soon. > > This is FAQ. You will find thousands of discussion on the net about > that. > My personal opinion (and I am not the only one in the Python > community) is that if you want to scale the way to go is to use > processes, not threads, so removing the GIL would be a waste of > effort anyway. Yes. Processes are cheap on well-designed operating systems, and using processes to subdivide your processor usage encourages simple, modular interfaces between parts of a program. Threads, while also cheap, are much more difficult and fiddly to program correctly, hence are rarely an overall win. One common response to that is "Processes are expensive on Win32". My response to that is that if you're programming on Win32 and expecting the application to scale well, you already have problems that must first be addressed that are far more fundamental than the GIL. -- \ "Pinky, are you pondering what I'm pondering?" "Umm, I think | `\ so, Brain, but three men in a tub? Ooh, that's unsanitary!" -- | _o__) _Pinky and The Brain_ | Ben Finney From bignose+hates-spam at benfinney.id.au Wed Sep 19 01:48:08 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Sep 2007 15:48:08 +1000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <13f196qktorgc88@corp.supernews.com> Message-ID: <873axbxl2f.fsf@benfinney.id.au> Dennis Lee Bieber writes: > Try to interpret it as: My point exactly. If a function is named 'super' and operates on classes, it's a pretty strong implication that it's about superclasses. Any explanation that begins "Try to interpret it as" and then goes on to explain that it's to do with MRO, *not* superclasses, is evidence that the function is *badly named*. I'm not interested in documenting this function, because as I said I don't see why I would want to use it. My objection is that, as currently named, it's an *obstacle* when a programmer goes looking for a way to get a superclass. Possibly the name 'next_in_mro', while ugly, would at least match the actual behaviour of this function. At least then the next person who goes looking for "how do I get the superclass of A?" won't be misled into trying to use *the wrong function for that purpose*. -- \ "If you can't annoy somebody there is little point in writing." | `\ -- Kingsley Amis | _o__) | Ben Finney From fakeaddress at nowhere.org Sat Sep 22 12:50:20 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Sep 2007 09:50:20 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190411282.060772.289270@y42g2000hsy.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> Message-ID: chris.monsanto at gmail.com wrote: > There are already anonymous functions in Python. > > lambda x, y, z: x + y + z > > is the same as: > > def _(x, y, z): return x + y + z They are the same only in special cases: The special identifier "_" is used in the interactive interpreter to store the result of the last evaluation; it is stored in the __builtin__ module. When not in interactive mode, "_" has no special meaning and is not defined. [Python Reference Manual; 2.3.2 Reserved classes of identifiers. http://docs.python.org/ref/id-classes.html] -- --Bryan From Summercoolness at gmail.com Tue Sep 18 02:57:36 2007 From: Summercoolness at gmail.com (Summercool) Date: Tue, 18 Sep 2007 06:57:36 -0000 Subject: The meaning of a = b in object oriented languages In-Reply-To: References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> Message-ID: <1190098656.030658.66380@57g2000hsv.googlegroups.com> On Sep 17, 11:04 pm, Lloyd Linklater wrote: > SpringFlowers AutumnMoon wrote: > > Is that the case: if a is an object, then b = a is only copying the > > reference? > > That and it adds a counter. > > a = ["foo", "bar"] > b = a > b[0] = "bite me" > p a, b > > a = "different" > p a, b > > *** > > In the first print, we get > ["something else", "bar"] > ["something else", "bar"] > > showing that changing b changes a, as expected. However, if we change > a, b is NOT changed as seen in the second print. > > "different" > ["something else", "bar"] > > That means that there is a counter inside that says to separate the two > or b would have changed with a as a changed with b initially. i think the line a = "different" means a is now set to a pointer to the String object with content "different". or that "a is now a reference to the String object." and b is still a reference to the Array object. so that's why a and b print out different things. they point to different objects. i think: whenever in Ruby, Python, and Java, a is never an object. a is always a "reference to an object"... this will solve a lot of puzzles when we don't understand some code behaviors. when a writing or a book reads "a is a Hash object; a is an Array object; or a is an Animal object" it is just a short form to say that "a is a reference to that object." b = a means "whatever a is referencing to, now b is referencing it too". so that's why a[1] = "foobar" will change what b will display, but a = "foobar" will not change what b will display. (because a[1] = "foobar" says "what is a referencing? go there and change its content that has the index 1" and when b goes there to see it, it is also changed.) From saptarshi.guha at gmail.com Thu Sep 20 20:22:03 2007 From: saptarshi.guha at gmail.com (sapsi) Date: Thu, 20 Sep 2007 17:22:03 -0700 Subject: Python,SWIG and libjvm In-Reply-To: <1190329236.398635.226020@y42g2000hsy.googlegroups.com> References: <1190329236.398635.226020@y42g2000hsy.googlegroups.com> Message-ID: <1190334123.039404.318860@d55g2000hsg.googlegroups.com> On Sep 20, 7:00 pm, sapsi wrote: > Hello, > I'm not sure if this the correct list but here goes (and sorry for the > noise). I've been attempting to wrap python around libhdfs. > So far so good ( I should point out that libhdfs is a c library to Hadoop Distributed FileSystem. Thank you Saptarshi From kyosohma at gmail.com Wed Sep 12 09:54:44 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 12 Sep 2007 13:54:44 -0000 Subject: Is the wxPython list down? In-Reply-To: <591b7$46e7e900$83aef404$14417@news2.tudelft.nl> References: <1189602607.803546.180320@w3g2000hsg.googlegroups.com> <591b7$46e7e900$83aef404$14417@news2.tudelft.nl> Message-ID: <1189605284.161378.291240@r29g2000hsg.googlegroups.com> On Sep 12, 8:26 am, stef wrote: > kyoso... at gmail.com wrote: > > Hi, > > > Does anyone know if the wxPython mailing list is having issues? I > > Yes the server has hardware problems, > Robin Dunn (moderator), is informed about it. > > cheers, > Stef Mientki And to think, we're always told that that doesn't happen with RAID5. Guess I should have checked the website. Thanks Stef and Frank. Mike From namesagame-usenet at yahoo.com Fri Sep 28 13:48:58 2007 From: namesagame-usenet at yahoo.com (gamename) Date: Fri, 28 Sep 2007 10:48:58 -0700 Subject: C Source Code Generator For Test Cases Message-ID: <1191001738.456766.176050@n39g2000hsh.googlegroups.com> Hi, Can anyone recommend a good method of using python to generate c source code? I have tables of test cases to use as input to a process which would generate the test's source code. The Cheetah tool looks interesting. Has anyone used it? Any other suggestions? TIA, -T From horpner at yahoo.com Mon Sep 3 00:58:57 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 03 Sep 2007 04:58:57 GMT Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> Message-ID: On 2007-09-02, Martin v. L?wis wrote: >>> (2) it is a interpretation language >> Not quite. It's compiled to byte-code - just like Java (would >> you call Java an 'interpreted language' ?) > > Python is not implemented like Java. In Java (at least in > HotSpot), the byte code is further compiled to machine code > before execution; in Python, the byte code is interpreted. > > Whether this makes Python an interpreter or a compiler, I don't > know. I'd call it an integrated compiler and virtual machine--a classic combination. -- Neil Cerutti From evan at yelp.com Wed Sep 12 03:36:55 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 12 Sep 2007 00:36:55 -0700 Subject: Generating HTML In-Reply-To: <9e2f512b0709112133l41ce5ef1g815962a81becf6b9@mail.gmail.com> References: <9e2f512b0709112133l41ce5ef1g815962a81becf6b9@mail.gmail.com> Message-ID: <1189582615.7859.10.camel@thinkpad> On Wed, 2007-09-12 at 01:33 -0300, Sebastian Bassi wrote: > Hello, > > What are people using these days to generate HTML? I still use > HTMLgen, but I want to know if there are new options. I don't > want/need a web-framework a la Zope, just want to produce valid HTML > from Python. It's not applicable for everything, but if you're planning on using Python to generate web pages you should really be using Cheetah templates. Very simple to use template system that is also very powerful, and you don't need to use it in conjunction with a heavy web application framework. See http://www.cheetahtemplate.org/ -- Evan Klitzke From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 18 10:12:07 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 16:12:07 +0200 Subject: super() doesn't get superclass In-Reply-To: <87zlzkzgu2.fsf@benfinney.id.au> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> Message-ID: <46efdcaf$0$14241$426a74cc@news.free.fr> Ben Finney a ?crit : > Evan Klitzke writes: > >> On Tue, 2007-09-18 at 14:15 +1000, Ben Finney wrote: >>> Why does the documentation of 'super' say that it returns the >>> superclass when *that's not true*? It doesn't return the >>> superclass, it returns the next class in the MRO, whether that's a >>> superclass or not. >> The next class in the MRO _is_ a superclass. Maybe not the way >> you've defined it in your own code, but certainly of the new class >> you created with MI. > > If I define a class hierarchy as follows:: > > class A(object): pass > class B(object): pass > class C(A): pass > class D(B): pass > > is it true to say that "D is a superclass of A"? Obviously not. > How about this: > > class E(C, D): pass > > In this instance, the MRO now has D following A; but the superclass of > 'A' is still 'object'. Yes. And ? > > You seem to be saying that now suddenly D *is* a superclass of > A. I don't see such an assertion in Evan's answer. Chapter and verse ??? > That's certainly not what users will think of when they think > "superclass" though. If a class X is in the MRO of call Y, then X is a superclass of Y. I agree that the documentation for super is somewhat misleading (and obviously wrong), but it still *give access to* (at least one of) the superclass(es). >>> Actually, even that's not true. The error message "AttributeError: >>> 'super' object has no attribute 'bazfunc'" makes it clear that >>> 'super' actually returns not the superclass, but a 'super' object, >>> whatever that's supposed to be. The 'super' object is a wrapper around a class and an object. It delegates attribute lookups to appropriate superclass. >>> After reading the rest of the article, I'm amazed that 'super' as >>> currently implemented is in Python at all. If you have a better solution for handling multiple inheritence, please share with us. FWIW, after all the articles I've read explaining why Python is badly designed, badly implemented, and totally flawed, I do wonder why this language exists at all !-) > I don't want to break the inheritance chain. I want the superclass, A soon as you have either multiple inheritence and/or an inheritence tree with depth > 1, there's no such thing as "the" superclass. wrt/ your exemple, object, A, B, C and D are *all* superclasses of E. > not the "next class in the MRO". The next class in the MRO is (usually and AFAICT) the most direct superclass. > Orthogonally to that, I think it's madness to write a function for > "return the next class in the MRO for 'type'" and document it as > "return the superclass of 'type'". I wouldn't use such an extreme word as 'madness', but I totally agree that this should be corrected. Care to submit a doc patch ? From mstepnicki at gmail.com Mon Sep 24 02:43:08 2007 From: mstepnicki at gmail.com (=?iso-8859-2?q?Marcin_St=EApnicki?=) Date: Mon, 24 Sep 2007 06:43:08 +0000 (UTC) Subject: scope, modyfing outside object from inside the method Message-ID: Hello. I thought I understand this, but apparently I don't :(. I'm missing something very basic and fundamental here, so redirecting me to the related documentation is welcomed as well as providing working code :). Trivial example which works as expected: >>> x = {'a':123, 'b': 456} >>> y = x >>> x['a']=890 >>> y {'a': 890, 'b': 456} Now, let's try something more sophisticated (it's not real world example, I've made up the problem which I think illustrates my issue). Let's say I've got such a structure: results = [ {'a': 12, 'b': 30 }, {'a': 13, 'b': 40 } ] I'd like to have each row and column in separate object of self-made classes.: class mycolumn(): def __init__(self, resultset, row, col): self.value = resultset[row][col] def __str__(self): return 'Column value: %s' % self.value class myrow(): def __init__(self): self.container = {} def __str__ (self): return self.container results = [ {'a': 12, 'b' :30 }, {'a': 13, 'b' :40 } ] mystruct = [] for row in results: mystruct.append ( myrow() ) for col in row: mystruct [len(mystruct)-1].container[col] = \ mycolumn(results, results.index(row), col) print mystruct[0].container['b'] # 12 results[0]['b'] = 50 # print mystruct[0].container['b'] # also 12 :/ In other words, I'd like to "map" the results to myrow and mycolumn objects, and have these new objects' values changed when I change "results". I hope I explained it well enough :). Thank you for your time. -- | And Do What You Will be the challenge | http://apcoln.linuxpl.org | So be it in love that harms none | http://biznes.linux.pl | For this is the only commandment. | http://www.juanperon.info `---* JID: Aragorn_Vime at jabber.org *---' http://www.naszedzieci.org From carsten at uniqsys.com Wed Sep 19 09:28:58 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 19 Sep 2007 09:28:58 -0400 Subject: Puzzled in the coding of Chinese In-Reply-To: <200709191357069843001@126.com> References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> , , , <871wcvlwly.fsf@rudin.co.uk> <200709191357069843001@126.com> Message-ID: <1190208538.3371.23.camel@dot.uniqsys.com> On Wed, 2007-09-19 at 13:57 +0800, Xing wrote: > Dear list members, > I am a newcomer in the world of Python. But I am attracted by > Python's power in handling text! Now I apply it to handle Chinese but > the Chinese character cann't be displayed on the screen. What > displayed on the screen is the 16bits codes. I am so puzzled! I > believe this is an easy question to most of python users and an > important question to me. Thanks a lot to your help! You are not giving us any background information for troubleshooting this. Your problem could be caused by a million different things, and there is not point in us guessing. Please start by answering the following questions: 1) What operating system are you using? 2) Can any programs on your computer display Chinese characters? 3) Where are you trying to display Chinese characters? Python command line, in IDLE, in some GUI window? 4) Where are the Chinese characters you're trying to display coming from? Are they hard-coded in your script, are they read from the keyboard, from a file, from a database, from a web page? -- Carsten Haese http://informixdb.sourceforge.net From randy.tucker7 at gmail.com Thu Sep 27 09:45:57 2007 From: randy.tucker7 at gmail.com (randy.tucker7 at gmail.com) Date: Thu, 27 Sep 2007 13:45:57 -0000 Subject: Translating Event.time from pyhook Message-ID: <1190900757.719106.305800@d55g2000hsg.googlegroups.com> I use pyhook to monitor user usage of keyboard and mouse. According to pyhook specs, event.time hold the number of seconds since the epoch. However, when I use the example source code I get numbers like 358054093, which translates to 07 May 1981.. Can anyone explain to me what am I doing wrong? Thanks. From zzbbaadd at aol.com Mon Sep 10 21:03:11 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 10 Sep 2007 18:03:11 -0700 Subject: Enum class with ToString functionality In-Reply-To: <87bqca9hrw.fsf@benfinney.id.au> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <87bqca9hrw.fsf@benfinney.id.au> Message-ID: <1189472591.797327.189180@w3g2000hsg.googlegroups.com> > > I'd like to know if the Cheeseshop package 'enum' is useful to > you. Any constructive feedback would be appreciated. > > Looking at the documentation it looks excellent. But I don't understand the 0.4.2 version number, particularly when you refer to it as robust. From prudek at bvx.cz Mon Sep 10 16:20:37 2007 From: prudek at bvx.cz (Milos Prudek) Date: Mon, 10 Sep 2007 22:20:37 +0200 Subject: Why zlib not included in Python tarball? Message-ID: <200709102220.37853.prudek@bvx.cz> I need to install my own Python. I compiled Python 2.4.4 from sources. zlib did not compile - it's not in the lib-dynload directory. I did not have this problem with any of my earlier Python compiles. I routinely compile Python from source. What is the correct procedure for installing zlib from source into Python? -- Milos Prudek From andres.j.new at gmail.com Sun Sep 30 22:04:21 2007 From: andres.j.new at gmail.com (andresj) Date: Mon, 01 Oct 2007 02:04:21 -0000 Subject: Using fractions instead of floats In-Reply-To: <87ir5rzju5.fsf@benfinney.id.au> References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <87ir5rzju5.fsf@benfinney.id.au> Message-ID: <1191204261.346282.269460@y42g2000hsy.googlegroups.com> On Sep 30, 6:48 pm, Ben Finney wrote: > andresj writes: > > The problem arises when you try to represent some number, like 0.4 in > > a float. > > Which is really a specific case of the general problem that, for any > given number base, some non-integer numbers cannot be exactly > represented as fractions. Yes. That's what I meant to say, by giving an example. > > Secondly, what happens if I need to sum 1/3 and 0.4? I could use > > Decimal to represent 0.4 precisely, but what about 1/3? > > What about the sum of (pi) and 2 (sqrt(2))? Mm... To be honest I hadn't thought of that in the moment I wrote the last post... But I think then, that I'll be more specific, so that my proposal only deals with *rational numbers*, not irrationals. > > > So the solution I think is using a fraction type/class > > As explained above, a fractional-number class only shifts the "exact > representation" problem, it doesn't solve it. I don't understand completely what you said, but I think you are saying that it doesn't solve the problem with irrational numbers. Which is exactly what this proposal doesn't solve. (Mainly because I do not know of any way of doing it in "normal" math). (While I write this, my mind reminds me of operating with roots " 2 (sqrt(2))", which I think could be solved in another similar way, although it has some more specific use cases... But in any case, that's not in the scope of this proposal, as they are irrational numbers.) From carsten at uniqsys.com Tue Sep 4 00:43:26 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 4 Sep 2007 00:43:26 -0400 Subject: list index() In-Reply-To: <1188874564.111842.87750@57g2000hsv.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <46d674c2$0$417$426a34cc@news.free.fr> <878x7te9h4.fsf@benfinney.id.au> <1188874564.111842.87750@57g2000hsv.googlegroups.com> Message-ID: <20070904043441.M52954@uniqsys.com> On Mon, 03 Sep 2007 19:56:04 -0700, TheFlyingDutchman wrote > [...] my fork of Python 3, which I am > pleased to announce now, is called Python 3.01 while in development, > and will be known as Python 3000 or Python 3K when it gets to a productional > release. I hope you're joking. -Carsten From wizzardx at gmail.com Tue Sep 11 14:42:43 2007 From: wizzardx at gmail.com (David) Date: Tue, 11 Sep 2007 20:42:43 +0200 Subject: Help With PyParsing of output from win32pdhutil.ShowAllProcesses() In-Reply-To: <1189534321.833098.114700@g4g2000hsf.googlegroups.com> References: <1189534321.833098.114700@g4g2000hsf.googlegroups.com> Message-ID: <18c1e6480709111142m700414d7qf6d49d381c7e0f1a@mail.gmail.com> On 9/11/07, Steve wrote: > Hi All (especially Paul McGuire!) > > Could you lend a hand in the grammar and paring of the output from the > function win32pdhutil.ShowAllProcesses()? > > This is the code that I have so far (it is very clumsy at the > moment) : Any particular reason you need to use pyparsing? Seems like an overkill for such simple data. Here's an example: import pprint X="""Process Name ID Process,% Processor Time,% User Time,% Privileged Time,Virtual Bytes Peak,Virtual Bytes PyScripter 2572 0 0 0 96370688 96370688 vmnetdhcp 1184 0 0 0 13942784 13942784 vmount2 780 0 0 0 40497152 38400000 ipoint 260 0 0 0 63074304 58531840""" data = [] for line in X.split('\n')[1:]: # Skip the first row split = line.split() row = [split[0]] # Get the process name row += [int(x) for x in split[1:]] # Convert strings to int, fail if any aren't. data.append(row) pprint.pprint(data) # Output follows: # #[['PyScripter', 2572, 0, 0, 0, 96370688, 96370688], # ['vmnetdhcp', 1184, 0, 0, 0, 13942784, 13942784], # ['vmount2', 780, 0, 0, 0, 40497152, 38400000], # ['ipoint', 260, 0, 0, 0, 63074304, 58531840]] # From robin at reportlab.com Wed Sep 19 08:20:38 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 19 Sep 2007 13:20:38 +0100 Subject: Odd files; just left behind? Message-ID: <46F11416.4020506@chamonix.reportlab.co.uk> I see a folder .python-eggs in my home directory on one of our servers with various .so files ~/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so are these just left behind from some install process? -- Robin Becker From santi_anti at yahoo.com Wed Sep 12 10:52:16 2007 From: santi_anti at yahoo.com (susanti marsol) Date: Wed, 12 Sep 2007 07:52:16 -0700 (PDT) Subject: calculate matrik Message-ID: <948344.40034.qm@web63110.mail.re1.yahoo.com> how to calculate the matrik? can u give me the sintax code? thanks so much before. --------------------------------- Be a better Globetrotter. Get better travel answers from someone who knows. Yahoo! Answers - Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Sep 17 16:31:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 17 Sep 2007 13:31:19 -0700 Subject: Extracting xml from html Message-ID: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> Hi, I am attempting to extract some XML from an HTML document that I get returned from a form based web page. For some reason, I cannot figure out how to do this. I thought I could use the minidom module to do it, but all I get is a screwy traceback: Traceback (most recent call last): File "\\mcisnt1\repl$\Scripts\PythonPackages\Development\clippy \xml_parser.py", line 69, in ? inst = ApptParser(url) File "\\mcisnt1\repl$\Scripts\PythonPackages\Development\clippy \xml_parser.py", line 19, in __init__ xml = self.getXml(url) File "\\mcisnt1\repl$\Scripts\PythonPackages\Development\clippy \xml_parser.py", line 30, in getXml doc = xml.dom.minidom.parse(f) File "C:\Python24\lib\xml\dom\minidom.py", line 1915, in parse return expatbuilder.parse(file) File "C:\Python24\lib\xml\dom\expatbuilder.py", line 928, in parse result = builder.parseFile(file) File "C:\Python24\lib\xml\dom\expatbuilder.py", line 207, in parseFile parser.Parse(buffer, 0) ExpatError: mismatched tag: line 1, column 357 Here's a sample of the html: lots of screwy text including divs and spans 1126264 Mitsubishi Mirage DE What's the best way to get at the XML? Do I need to somehow parse it using the HTMLParser and then parse that with minidom or what? Thanks a lot! Mike From svenn.bjerkem at googlemail.com Thu Sep 27 15:40:37 2007 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Thu, 27 Sep 2007 19:40:37 -0000 Subject: Script to extract text from PDF files In-Reply-To: <1190843416.313377.13700@w3g2000hsg.googlegroups.com> References: <1190746968.162359.39890@r29g2000hsg.googlegroups.com> <1190747931.415834.75670@n39g2000hsh.googlegroups.com> <1190839750.537205.193110@d55g2000hsg.googlegroups.com> <1190843416.313377.13700@w3g2000hsg.googlegroups.com> Message-ID: <1190922037.922012.193760@57g2000hsv.googlegroups.com> On Sep 26, 11:50 pm, byte8b... at gmail.com wrote: > On Sep 26, 4:49 pm, Svenn Are Bjerkem > wrote: > > > I have downloaded this package and installed it and found that the > > text-extraction is more or less useless. Looking into the code and > > comparing with the PDF spec show a very early implementation of text > > extraction. Luckily it is possible to overwrite the textextraction > > method in the base class without having to fiddle with the original > > code. I tried to contact the developer to offer some help on > > implementing text extraction, but he didn't answer my emails. > > -- > > Svenn > > Well, feel free to send any ideas or help to me! It seems simple... Do > a binary read. Find 'stream' and 'endstream' sections. > zlib.decompress() all the streams. Find BT and ET markers (Begin Text > & End Text) and finally locate the parens within those and string the > text together. This works great on 3 out of 10 PDF documents, but my > main issue seems to be the zlib compressed streams. Some of them don't > seem to be FlateDecodeable (although they claim to be) or the header > is somehow incorrect. But, once I get a good stream and decompress it, > things are OK from that point on. Seriously, if you have ideas, please > let me know. I'll be glad to share what I've got so far. So far I have found that extracting text from the IEEE journal papers is not as simple as described above. The IEEE journals are typesetting things in typical journal style with two columns body text and one column abstract and a blob of header and author information. Take figures and formulas and footnotes and spread them around in the journal and you are basically using all block text layout commands there is in PDF. I wanted to to get the pdftotext from xpdf package to see what that tool does to the IEEE pdfs in order to see if I should dive into the sources to see what they do to get things right. So far I have not got this far. Purpose of my work was to extract the abstract of each paper to put into a database for later search, but IEEE also has a search engine on their journal DVD => postpone python work. Got my gentoo machine back on track so that may maybe change again...... -- Svenn From shriphanip at gmail.com Thu Sep 27 06:44:08 2007 From: shriphanip at gmail.com (Shriphani) Date: Thu, 27 Sep 2007 10:44:08 -0000 Subject: comparing elements of a list with a string In-Reply-To: References: <1190734785.439839.303030@50g2000hsm.googlegroups.com> Message-ID: <1190889848.653434.178450@g4g2000hsf.googlegroups.com> Hello, Would that mean that if I wanted to append all the (date, time) tuples to a list, I should do something like: for file in list_of_backup_files: some_list.append(file) By the way I did this: def listAllbackups(filename): list_of_backups = glob(home+'/Desktop/backupdir/*%s*'%filename) for element in list_of_back: if element.find(file) != -1: date_components = element.split('-')[-4:-1] date = str(date_components[0]) + ":" + str(date_components[1]) + ":" + str(date_components[2]) time = element.split('-')[-1] yield (date, time) print listAllbackups('fstab') I ran it in the terminal and I got: Why does it do that and not just print out all the values of (date, time) Regards, Shriphani Palakodety From prudek at bvx.cz Mon Sep 10 16:17:04 2007 From: prudek at bvx.cz (Milos Prudek) Date: Mon, 10 Sep 2007 22:17:04 +0200 Subject: uninstall In-Reply-To: <1189432555.060384.194820@50g2000hsm.googlegroups.com> References: <1189432555.060384.194820@50g2000hsm.googlegroups.com> Message-ID: <200709102217.06094.prudek@bvx.cz> > If you're installing from sources "manually", you might want to > consider checkinstall to give you the option of an uninstall for those > software distributions which don't support "make uninstall": I know about checkinstall and I often use it. If I remember correctly, Python failed to work with it. I admit I did not try to use checkinstall this time. -- Milos Prudek From duncan.booth at invalid.invalid Tue Sep 25 06:51:42 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Sep 2007 10:51:42 GMT Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> Message-ID: Mark Summerfield wrote: > When handling collections of key-value data, it is often > convenient to access the data in key order. One way to do this is > to use an unsorted data structure (e.g., a Python dict), and then > sort the keys as needed. Another way is to use a sorted data > structure (e.g., a sorteddict as proposed in this PEP), and simply > access the keys, knowing that they are always in sorted order. Please define 'sorted order' and make sure it is customisable. > keys(firstindex : int = None, secondindex : int = None) -> > list of keys I don't really see the point of this, but general support for slicing might be interesting: sd[start:end] -> list of values for all keys such that start <= key < end (using the appropriate definition of 'sorted order'). > key(index : int) -> value > > item(index : int) -> (key, value) > > value(index : int) -> key I'm confused: the key method returns a value and the value method returns a key??? > > set_value(index : int, value) > > delete(index : int) All of those can of course be replaced with a single method that returns the key at a specified index and then using that key. Yes that would be less efficient, but I'd rather have as close to a standard dictionary interface as possible. > Examples > > To keep a collection of filenames on a case-insensitive file > system in sorted order, we could use code like this: > > files = collections.sorteddict.sorteddict() > for name in os.listdir("."): > files[name.lower()] = name > > We can add new filenames at any time, safe in the knowledge that > whenever we call files.values(), we will get the files in > case-insensitive alphabetical order. I don't see this as a terribly useful example since you don't explain why we need to keep filenames in case-insensitive alphabetical order at all. If we want to print a list of filenames we can sort them once when printing them, why do we need to keep them 'always sorted'? > To be able to iterate over a collection of data items in various > predetermined orders, we could maintain two or more sorteddicts: > > itemsByDate = collections.sorteddict.sorteddict() > itemsByName = collections.sorteddict.sorteddict() > itemsBySize = collections.sorteddict.sorteddict() > for item in listOfItems: > itemsByDate["%s\t%17X" % (item.date, id(item))] = item > itemsByName["%s\t%17X" % (item.name, id(item))] = item > itemsBySize["%s\t%17X" % (item.size, id(item))] = item I think perl might make you use strings as keys, fortunately Python doesn't. What I really don't like about this is that you've copied the date, so if you mutate item.date the itemsByDate are no longer sorted. Again it sounds like sorting for printing will be less overhead that keeping them always sorted. You need to come up with examples where there is an actual benefit to not sorting for output. > Here we have used the item IDs to ensure key uniqueness. If you are going to do this then it really does need to be: itemsByDate = sorteddict(items, key=lambda self, k: self[k].date) so that you can maintain sorted order when mutating an item. How the dictionary knows that its contents have been mutated is another question entirely. > > Now we can iterate in date or name order, for example: > > for item in itemsByDate: > print item.name, item.date Which we can do just as well with an ordinary dictionary: for item in sorted(items, key=byDate): ... given an appropriate definition of byDate. The cases I can think of where a sorteddict might be useful would be things like collecting web server statistics and maintaining a regularly updated display of the top n pages. You need a combination of factors for this to be useful: frequent updates, and frequent extraction of sorted elements + the requirement to access elements as a dictionary. Also, none of your use cases target any of the additional fripperies you threw into your proposal. From timr at probo.com Sat Sep 15 02:05:40 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 15 Sep 2007 06:05:40 GMT Subject: smtp debugging methods References: Message-ID: Sean Nakasone wrote: > >I'm having trouble with sending smtp mail. It's hanging after the >smtplib.SMTP() line. It doesn't works from home but not from work. What's >the best way to debug this? It's quite possible that your network at work has a firewall blocking these ports. Many employers allow outgoing connections only on ports 25, 80, and 443. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sjmachin at lexicon.net Wed Sep 5 09:00:29 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 05 Sep 2007 06:00:29 -0700 Subject: Looping through File Question In-Reply-To: <1188995195.932117.111440@k79g2000hse.googlegroups.com> References: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> <1188992047.858695.174790@r34g2000hsd.googlegroups.com> <1188995195.932117.111440@k79g2000hse.googlegroups.com> Message-ID: <1188997229.977198.23100@22g2000hsm.googlegroups.com> On Sep 5, 10:26 pm, planetmatt wrote: > On 5 Sep, 12:34, John Machin wrote: > > > > > On Sep 5, 8:58 pm, planetmatt wrote: > > > > I am a Python beginner. I am trying to loop through a CSV file which > > > I can do. What I want to change though is for the loop to start at > > > row 2 in the file thus excluding column headers. > > > > At present I am using this statement to initiate a loop though the > > > records: > > > > for line in f.readlines(): > > > > How do I start this at row 2? > > > The quick answer to your literal question is: > > for line in f.readlines()[1:]: > > or, with extreme loss of elegance, this: > > for lino, line in enumerate(f.readlines()): > > if not lino: > > continue > > > But readline and readlines are old hat, and you wouldn't want to read > > a file of a few million lines into a big list, so a better answer is: > > > _unused = f.next() > > for line in f: > > > But you did say you were reading a CSV file, and you don't really want > > to do your own CSV parsing, even if you think you know how to get it > > right, so best is: > > > import csv > > rdr = csv.reader(f) > > heading_row = rdr.next() > > for data_row in rdr: > > > HTH, > > John > > Thanks so much for the quick response. All working now. > > I had looked at the CSV module but when I ran into another problem of > trying to loop through all columns, I was given a solution in another > forum which used the readlines() method. Antique advice which still left you doing the CSV parsing :-) > > I have looked at the CSV documentation but didn't see any mention of > heading_row or data_row. Ummm ... 'heading_row' and 'data_row' are identifiers of the kind that you or I would need to make up in any language; why did you expect to find them in the documentation? > Is there a definitive Python documentation > site with code examples like MS's MSDN? The definitive Python documentation site is (I suppose) http://www.python.org/doc/ I don't know what "code examples like MS's MSDN" means. I avoid MSDN like I'd avoid a nurse carrying a bottle of Dettol and a wire brush :-) Here's an example of sucking your data into a list of lists and accessing it columnwise: rdr = csv.reader(f) whatever_you_want_to_call_the_heading_row = rdr.next() data = list(rdr) sum_col_5 = sum(float(row[5]) for row in data) print "The value in row 3, column 4 is", data[3][4] HTH, John From ivanwangcn at gmail.com Sun Sep 2 10:28:19 2007 From: ivanwangcn at gmail.com (Ivan Wang) Date: Sun, 02 Sep 2007 07:28:19 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <1188740716.423349.304370@y42g2000hsy.googlegroups.com> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> Message-ID: <1188743299.664137.194760@d55g2000hsg.googlegroups.com> On Sep 2, 9:45 pm, jwrweather... at gmail.com wrote: > [snip code] > > Thanks for that. I realise that improving the algorithm will speed > things up. I wanted to know why my less than perfect algorithm was so > much slower in python than exactly the same algorithm in C. Even when > turning off gcc's optimiser with the -O0 flag, the C version is still > > > > > 100 times quicker.- Hide quoted text - > > - Show quoted text - Maybe Python is the slowest programming language in the world. So there is a joke: some python hater said that "python" can only crawl rather than run. :) Python is slow because: (1) dynamic binding (2) it is a interpretation language For example, in C code, an interger expression "a+b" will directly generate an assembly code "add" for x86 processors. A python interpreter, on the other side, need detect the type of a and b first, then choose the right "+" operation for them and use a evaluation stack to get the result. Psyco is a JIT compiler with just in time specialization which can somehow solve these two problems From ldo at geek-central.gen.new_zealand Sun Sep 9 02:53:32 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 09 Sep 2007 18:53:32 +1200 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> <7xhcm4pl5m.fsf@ruckus.brouhaha.com> Message-ID: In message <7xhcm4pl5m.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Lawrence D'Oliveiro writes: > >> Except that the NSA's reputation has taken a dent since they failed to >> anticipate the attacks on MD5 and SHA-1. > > NSA had nothing to do with MD5 ... Nevertheless, it was their job to anticipate attacks on it. After all, they call themselves the "National _Security_ Agency", don't they? > ... and it's to NSA's credit that SHA-1 held up for as long as it did. But they have no convincing proposal for a successor. That means the gap between the classified and non-classified state of the art has shrunk down to insignificance. From s.mientki at id.umcn.nl Wed Sep 26 03:49:34 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 26 Sep 2007 09:49:34 +0200 Subject: ANN: PyPE 2.8.7 In-Reply-To: <1190782415.470011.226800@w3g2000hsg.googlegroups.com> References: <1190782415.470011.226800@w3g2000hsg.googlegroups.com> Message-ID: <38f8f$46fa0f10$83aef404$19681@news1.tudelft.nl> thebjorn wrote: > On Sep 25, 12:46 pm, stef wrote: > >> Another problem, >> I tried to run PyPE in my "old IDE", >> > > instead of double-clicking on the PyPE.exe file? Why? > to get the traceback. cheers, Stef From bbxx789_05ss at yahoo.com Sat Sep 15 18:50:23 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 15 Sep 2007 15:50:23 -0700 Subject: (wxPython) wx.ProgressDialog - how to cancel out of? In-Reply-To: References: Message-ID: <1189896623.369696.233870@57g2000hsv.googlegroups.com> Terry Carroll wrote: > I'm trying to use wx.ProgressBar, and the cancel button is not > responding. > > Here is a simple program that exhibits the problem: > > ######################################################### > import wx > import time > > max = 10 > app = wx.PySimpleApp() > dlg = wx.ProgressDialog("Progress dialog example", > "variables to be shown here", > maximum = max, > style = wx.PD_CAN_ABORT > | wx.PD_CAN_SKIP > #| wx.PD_APP_MODAL > | wx.PD_ELAPSED_TIME > | wx.PD_ESTIMATED_TIME > | wx.PD_REMAINING_TIME > ) > > keepGoing = True > skip = False > count = 0 > > while keepGoing and count < max: > count += 1 > wx.MilliSleep(1000) > #time.sleep(1) > newtext = "(before) count: %s, keepGoing: %s, skip: %s " % \ > (count, keepGoing, skip) > print newtext > (keepGoing, skip) = dlg.Update(count, newtext) > newtext = "(after) count: %s, keepGoing: %s, skip: %s " % \ > (count, keepGoing, skip) > print newtext > dlg.Destroy() > ######################################################### > > The dialog looks right when this runs, but.... > > What's right: I get a progress bar; it includes "Skip" and "Cancel" > buttons; it shows 10 seconds of progress, and updates once per second > with the variables' values on each iteration. > > What's wrong is that I can't get clicking on the "Skip" or "Cancel" > buttons to have any effect. Instead, as soon as the dialog displays, > I get an hourglass, and it doesn't matter what I click on. Here's > what the print statements display, consistently, regardless of what I > try to click or whether I click nothing at all: > > I:\python>test1.py > (before) count: 1, keepGoing: True, skip: False > (after) count: 1, keepGoing: True, skip: False > (before) count: 2, keepGoing: True, skip: False > (after) count: 2, keepGoing: True, skip: True > (before) count: 3, keepGoing: True, skip: True > (after) count: 3, keepGoing: True, skip: True > (before) count: 4, keepGoing: True, skip: True > (after) count: 4, keepGoing: True, skip: True > (before) count: 5, keepGoing: True, skip: True > (after) count: 5, keepGoing: True, skip: True > (before) count: 6, keepGoing: True, skip: True > (after) count: 6, keepGoing: True, skip: True > (before) count: 7, keepGoing: True, skip: True > (after) count: 7, keepGoing: True, skip: True > (before) count: 8, keepGoing: True, skip: True > (after) count: 8, keepGoing: True, skip: True > (before) count: 9, keepGoing: True, skip: True > (after) count: 9, keepGoing: True, skip: True > (before) count: 10, keepGoing: True, skip: True > (after) count: 10, keepGoing: True, skip: True > > Two oddities here: > > 1) As I read the docs, the keepGoing variable should be set to True, > unless I click on "Cancel," in which case it should be set to False > (which would end the loop). That doesn't happen. This is really what > I'm most concerned here with. > > 2) The variable "skip: set to False on the first iteration, and then > set to True on subsequent iterations? Note that this happens even if > no buttons are selected. This is just a weirdness to me, and not my > main concern, but I thought I'd mention it in case it's relevant. > > You can see some variations in the commented-out code that I tried; > they did not help. > > Relevant software and releases: > > OS: Windows XP Home Edition, Version 2002, SP2 > Python: ActivePython 2.5.0.0 > wxPython: 2.8.1.1 (msw-unicode) > > Any help appreciated. Or, if you want the progress dialog to start when your app starts-- rather than after a user clicks on a button--you can use a short timer: import wx app = wx.PySimpleApp() win = wx.Frame(None, -1, "Test Progress Dialog") timer = wx.Timer(win) #win.Bind(wx.EVT_TIMER, on_timer_expiry, timer) def on_timer_expiry(evt): max = 10 dialog = wx.ProgressDialog( "Loading", "progress:", max, style = wx.PD_CAN_ABORT |wx.PD_ELAPSED_TIME |wx.PD_ESTIMATED_TIME |wx.PD_REMAINING_TIME ) keep_going = True skip = False count = 0 while keep_going and (count < max): count += 1 wx.MilliSleep(1000) (keep_going, skip) = dialog.Update(count) print skip dialog.Destroy() timer.Stop() win.Bind(wx.EVT_TIMER, on_timer_expiry, timer) timer.Start(1000) win.Show() app.MainLoop() From steve at REMOVE-THIS-cybersource.com.au Sat Sep 15 01:35:23 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 15 Sep 2007 05:35:23 -0000 Subject: How to avoid overflow errors References: <13em8vnr527rq20@corp.supernews.com> Message-ID: <13emror796r4vae@corp.supernews.com> On Fri, 14 Sep 2007 21:43:38 -0300, Eduardo O. Padoan wrote: >> How do I subclass int and/or long so that my class also auto-converts >> only when needed? > > What about just subclassing long - is this not an option? Of course it's an option. As it turned out, that was the easiest way for me to proceed. I was a little concerned that the overhead of using longs might have been excessive, but for values close to zero (and by close I mean < millions) there's no significant time difference between arithmetic with ints and longints. -- Steven. From michele.simionato at gmail.com Sat Sep 1 12:44:11 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 01 Sep 2007 16:44:11 -0000 Subject: metaclasses: timestamping instances In-Reply-To: References: Message-ID: <1188665051.107414.61200@50g2000hsm.googlegroups.com> On Sep 1, 6:07 pm, Steve Holden wrote: > > Debugging with Wing IDE and examining the classes at a breakpoint shows > this to be true (even after Y's __metaclass__ assignment is commented out): > > >>> X.__metaclass__ > > >>> Y.__metaclass__ > > >>> For the benefit of the readers I will just point out that in order to determine the metaclass of a class it is far better NOT to relay on the __metaclass__ attribute. The right thing to to is to look at the __class__ attribute, or to use type. Here is a (made up) example where .__metaclass__ gives the wrong result: In [9]: class M(type): pass ...: In [10]: class B: __metaclass__ = M ....: In [11]: B.__metaclass__ = None # now the hook is set to None, but the metaclass does not change In [12]: B.__class__ Out[12]: Michele Simionato From zzbbaadd at aol.com Wed Sep 12 13:35:30 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 12 Sep 2007 10:35:30 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: <5kq1hgF4r90oU1@mid.individual.net> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> Message-ID: <1189618530.872819.136450@57g2000hsv.googlegroups.com> On Sep 12, 4:40 am, Bjoern Schliessmann wrote: > Ivan Voras wrote: > > What does "self" have to do with an object model? It's an > > function/method argument that might as well be hidden in the > > compiler without ever touching the role it has (if not, why?). I > > agree that it's needless noise in a language. > > If this was needless, why do C++ and Java have the "this" pointer? > "this" in C++ and Java is not shown in the parameter list, which was what he was complaining about. He wants class MyClass: def SomeFunction(someParameter): self.someParameter = someParameter not class MyClass: def SomeFunction(self, someParameter): self.someParameter = someParameter The confusing way about the current Python method when you first encounter it is why is "self" being passed in when you write the function but not when you call it. If the compiler is smart enough to know that a = MyClass() a.SomeFunction(12) SomeFunction() has a "self" implicitly added to the parameter list, it seems that it should be smart enough to know that a function defined in a class has a "self" implicitly added to the parameter list. From goon12 at gmail.com Wed Sep 12 07:55:59 2007 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 12 Sep 2007 07:55:59 -0400 Subject: How can I work on VIM for python code such as cscope for C code? In-Reply-To: <1189585041.556933.77350@22g2000hsm.googlegroups.com> References: <1189585041.556933.77350@22g2000hsm.googlegroups.com> Message-ID: <6a2ccd190709120455j428e6f51v60f6f824540f677f@mail.gmail.com> On 9/12/07, Evan wrote: > Hi, guys ~~ > > How can i work on VIM for python code? I use cscope plugin on VIM for > C code before, it helps me to different function and search C > variable where it is defined. Change to the top level directory that contains your python source files, and do find -name '*.py' > cscope.files cscope -b Then it should work. > Do I need to downlaod other software/plugin? You might, if do you not have the cscope_maps.vim plugin. If not you can get it http://cscope.sourceforge.net/cscope_vim_tutorial.html and just put it in your vim plugins directory. From george.sakkis at gmail.com Fri Sep 14 18:51:25 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 14 Sep 2007 22:51:25 -0000 Subject: Python 3K or Python 2.9? In-Reply-To: <1189618530.872819.136450@57g2000hsv.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> Message-ID: <1189810285.757220.9310@19g2000hsx.googlegroups.com> On Sep 12, 1:35 pm, TheFlyingDutchman wrote: > On Sep 12, 4:40 am, Bjoern Schliessmann wrote: > > Ivan Voras wrote: > > > What does "self" have to do with an object model? It's an > > > function/method argument that might as well be hidden in the > > > compiler without ever touching the role it has (if not, why?). I > > > agree that it's needless noise in a language. > > > If this was needless, why do C++ and Java have the "this" pointer? > > "this" in C++ and Java is not shown in the parameter list, which was > what he was > complaining about. He wants > > class MyClass: > def SomeFunction(someParameter): > self.someParameter = someParameter > > not > > class MyClass: > def SomeFunction(self, someParameter): > self.someParameter = someParameter If one *really* wants this, it is doable in python too: http://www.voidspace.org.uk/python/weblog/arch_d7_2006_12_16.shtml#e583 George From Summercoolness at gmail.com Sun Sep 16 21:23:20 2007 From: Summercoolness at gmail.com (Summercool) Date: Mon, 17 Sep 2007 01:23:20 -0000 Subject: where are the .pyc files? In-Reply-To: <5l57t1F655kfU5@mid.uni-berlin.de> References: <1189963710.714191.74440@n39g2000hsh.googlegroups.com> <5l57t1F655kfU5@mid.uni-berlin.de> Message-ID: <1189992200.860524.58620@w3g2000hsg.googlegroups.com> On Sep 16, 10:36 am, Marc 'BlackJack' Rintsch wrote: > > The `*.pyc` files are usually only created when you import a module, not > when a module is run directly. how come a program that runs directly doesn't need to be optimized into bytecode first? Or... is it that the interpreter will just run the program as it goes by, without ever generating a .pyc file? So what if you have a program that you only update every few weeks... then you can ask a .pyc to be generated so that it runs faster every time? From bj_666 at gmx.net Fri Sep 7 10:21:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2007 14:21:38 GMT Subject: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute References: <1189173455.525144.326300@y42g2000hsy.googlegroups.com> Message-ID: <5kd53iF31i6hU6@mid.uni-berlin.de> On Fri, 07 Sep 2007 06:57:35 -0700, cjt22 wrote: > I have a step class and store in a list step instances > A step instance contains variables: name, startTime etc and startTime > is stored as a string %H:%M:%S > > What I would like to do is to be able to sort this list of objects > based on the startTime object so that the first item in the list is > the object with the earliest Start time and last item is the object > with the last Start time. > > I belive my key has to be = strpTime(step.sTime, "%H:%M:%S") > But don't know how to create the comparison funciton. > > Any help on how I can perform this whole operation would be much > appreciated. This should be enough:: steps.sort(key=lambda s: s.startTime) If you sort strings of the form 'hh:mm:ss' the represented times are sorted chronological. No need to convert them to a number first. If the "natural" sort criterion for `Step` objects is the start time you might override `__cmp__()` of `Step`\s instead:: def __cmp__(self, other): return cmp(self.startTime, other.startTime) Now you can just sort the list with ``steps.sort()``. Ciao, Marc 'BlackJack' Rintsch From joemystery123 at gmail.com Sat Sep 22 22:39:43 2007 From: joemystery123 at gmail.com (crybaby) Date: Sat, 22 Sep 2007 19:39:43 -0700 Subject: newb: glob on windows os.renames creates many nested folders Message-ID: <1190515183.389916.92240@19g2000hsx.googlegroups.com> when I do this in my python code and run it in windows xp, it creates ctemp/..../.../.../../ so on and creates file t. Not file starting with the name complist and ending with .txt (complist*.txt). Any idea why this may be? glob only works in *nix not on windows? os.renames(glob.glob('complist*.txt') [0],r'temp/'.join(glob.glob('complist*.txt')[0])) From __peter__ at web.de Mon Sep 24 08:01:09 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Sep 2007 14:01:09 +0200 Subject: sorting a list numbers stored as strings References: <1190632366.863711.100680@y42g2000hsy.googlegroups.com> Message-ID: aine_canby wrote: > I have the following list - > > ["1", "11", "2", "22"] > > how do I sort it like this - > > ["1", "2", "11", "22"] >>> items = ["1", "11", "2", "22"] >>> items.sort(key=int) >>> items ['1', '2', '11', '22'] This is more efficient than Amit's compare function and even Bruno's decorate-sort-undecorate (DSU) -- which of course only matters if the list becomes a bit larger. Peter From mail at microcorp.co.za Sat Sep 1 03:52:03 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 1 Sep 2007 09:52:03 +0200 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net><1188551958.728836.137370@x35g2000prf.googlegroups.com> Message-ID: <01f401c7ec71$4c2e22a0$03000080@hendrik> "Steve Holden" wrote: > Paddy wrote: > > My accent is probably from the East Midlands of the UK, but is not > > pronounced. > > > If your accent isn't pronounced how do we know what it sounds like? > When he says pronounced, he doesn't mean pronounced, he means pronounced! - To shamelessly paraphrase the Master - (Plum of course) ; - ) - Hendrik From http Fri Sep 7 22:17:44 2007 From: http (Paul Rubin) Date: 07 Sep 2007 19:17:44 -0700 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> <7x3axq7a8a.fsf@ruckus.brouhaha.com> <13e3us269f59s7a@corp.supernews.com> Message-ID: <7xd4wt99yv.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > unique_id = itertools.count(1234567890) > > Sweet! > > I really must make itertools second-nature. I always forget it. Beware that count() output (like enumerate) is always <= sys.maxint. It raises an exception if it overflows. IMO this is a bug. > > def unique_id(): > > return os.urandom(10).encode('hex') > > Any time I see something using a random number to generate IDs, I worry > about collisions. Am I being paranoid? (But even paranoids write code > with bugs...) Well, the idea is to make the string long enough (I shouldn't have picked 10 bytes) to make the probability of collisions acceptably low. The probability is about exp(-k**2/(2*N)) where k is the number of id's you use and N is the number of possible ID's. So with os.urandom(20), if you use 1 billion (= approx 2**30) id's, the probability is about exp(-(2**60 / 2*2**160)) = 1/exp(2**101) which is extremely small. Using random strings is probably safer from collisions than maintain keep distinct initial counters across multiple runs of a program, on multiple computers, etc. The classic example is ethernet cards. Each one is supposed to have a unique hardware 48-bit MAC address, with routers etc. relying on the uniqueness. Some organization is supposed to assign a unique code to each manufacturer, and then the manufacturer uses that code as a prefix and assigns addresses in sequence within that space. That works fine until sales go up, manufacturers start opening multiple factories operating out of the same space, low-rent manufacturers start making up their own codes, etc. So companies that buy large numbers of cards often find multiple cards with the same address, causing various hassles. If they just assigned 128-bit MAC addresses at random it's very unlikely that there would ever be a collision. > Here's something which is a little less predictable than a straight > counter: It's still very easy to generate valid id's from that, or guess the next one with non-negligible probability. IMO it's almost never worth messing with a "little less predictable". If you're trying to prevent an actual opponent from guessing something, use full-strength cryptography. You could try something like this: import sha, os, itertools radix = 2**32 # keep this == 2**(some even number <= 80) secret_key = os.urandom(20) def prp(key, n): # pseudo-random permutation (8-round Feistel network) # transform n to a unique number < radix**2 assert 0 <= n < radix**2 def F(i,x): return int(sha.new('%s,%x,%x'%(key,i,x)).hexdigest(), 16) % radix a,b = divmod(n, radix) for i in xrange(8): a ^= F(i,b) a,b = b,a return radix*a + b unique_id = (prp(secret_key, i) for i in itertools.count()) It should be pretty secure and (unless I made an error) is a permutation from [0:radix**2] to [0:radix**2], similar to DES. It's invertible if you know the secret key (I'll leave that as an exercise). 8 rounds is probably overkill for radix 2**32. From michael at stroeder.com Tue Sep 4 06:22:20 2007 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 04 Sep 2007 12:22:20 +0200 Subject: FCGI app reloading on every request In-Reply-To: References: <46DCDE59.8060109@animats.com> <46DCE052.40708@v.loewis.de> Message-ID: John Nagle wrote: > > What's actually happening is that FCGI isn't running at all. > My .fcgi file is being executed by Apache's CGI handler, and > "fcgi.py" recognizes this, then reads the parameters as if > a CGI program. So it works just like a CGI program: one > load per request. Not sure why Apache is doing that yet. > I'm looking at Apache configuration files now. Are you running mod_fastcgi oder mod_fcgid? Disclaimer: I don't claim to be an expert in that. My web2ldap source distribution contains two examples configuration files for each of the modules above for FastCGI over Unix Domain Socket( see directory /etc/httpd/, comments of sample-mod_fcgid.conf misleading). web2ldap can also be deployed as (multi-threaded) FastCGI-server. Ciao, Michael. From bj_666 at gmx.net Sun Sep 16 13:36:33 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Sep 2007 17:36:33 GMT Subject: where are the .pyc files? References: <1189963710.714191.74440@n39g2000hsh.googlegroups.com> Message-ID: <5l57t1F655kfU5@mid.uni-berlin.de> On Sun, 16 Sep 2007 17:28:30 +0000, Summercool wrote: > so i have always heard of the .pyc files.... but for some reason i > don't see them on the Windows platform... when i have a program > called try.py and after running it for ages, i still don't have a > try.pyc file in my folder even if i turn the "show hidden file" to on. The `*.pyc` files are usually only created when you import a module, not when a module is run directly. Ciao, Marc 'BlackJack' Rintsch From aleax at mac.com Fri Sep 28 11:16:28 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 28 Sep 2007 08:16:28 -0700 Subject: Python 3.0 migration plans? References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <%q0Li.725$ih1.539@nlpi068.nbdc.sbc.com> Message-ID: <1i555ag.9ez4uvf4583jN%aleax@mac.com> John Nagle wrote: > TheFlyingDutchman wrote: > > It seems that Python 3 is more significant for what it removes than > > what it adds. > > > > What are the additions that people find the most compelling? > > I'd rather see Python 2.5 finished, so it just works. And I'd rather see peace on Earth and goodwill among men than _either_ Python 3 or your cherished "finished" 2.5 -- the comparison and implied tradeoff make about as much sense as yours. > All the major third-party libraries working and available with > working builds for all major platforms. That working set > of components in all the major distros used on servers. > The major hosting companies having that up and running on > their servers. Windows installers that install a collection > of components that all play well together. > > That's what I mean by "working". I.e., you mean tasks appropriate for maintainers of all the major third-party libraries, distros, and hosting companies -- great, go convince them, or go convince all warmongers on Earth to make peace if you want an even harder tasks with even better potential impact on the state of the world, then. Alex From jjl at pobox.com Sun Sep 23 08:18:17 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 23 Sep 2007 12:18:17 GMT Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87odfxjgjy.fsf@pobox.com> <7x4phpt9nf.fsf@ruckus.brouhaha.com> <87wsuj4152.fsf@pobox.com> <7xabrf2gmh.fsf@ruckus.brouhaha.com> Message-ID: <87k5qhd186.fsf@pobox.com> Paul Rubin writes: > jjl at pobox.com (John J. Lee) writes: >> > I think mousing takes more mental work than typing, >> I'm not sure this is a matter for debate, as much as physical >> measurement. > > I don't know of any way to physically measure mental work. fMRI is one. That won't "directly" answer the question of course -- but then physical measurement and scientific progress are never "direct", theory is always involved. John From kyosohma at gmail.com Thu Sep 13 09:30:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 13 Sep 2007 06:30:35 -0700 Subject: wxstyledtextctrl and xml markup In-Reply-To: <4abcb$46e93adc$83aef404$31489@news2.tudelft.nl> References: <1189689993.338662.267340@k79g2000hse.googlegroups.com> <4abcb$46e93adc$83aef404$31489@news2.tudelft.nl> Message-ID: <1189690235.317887.262540@r29g2000hsg.googlegroups.com> On Sep 13, 8:27 am, stef wrote: > > I highly recommend the wxPython mailing list. Right now it is down > > (see their website), > > its'up again. That's not what the website says, but I'll take your word for it. Mike From michele.simionato at gmail.com Wed Sep 5 06:32:52 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 05 Sep 2007 10:32:52 -0000 Subject: decorator and signal handler In-Reply-To: <1188985182.617611.121740@r29g2000hsg.googlegroups.com> References: <1188985182.617611.121740@r29g2000hsg.googlegroups.com> Message-ID: <1188988372.077560.213590@d55g2000hsg.googlegroups.com> On Sep 5, 11:39 am, stalex wrote: > Hi all, > > I wrote the following code since I want to try using a decorator to > install signal handler: I do have a decorator for exactly that purpose in my code. Here it is: def on(sig): ''' A factory of decorators for signal handlers. An example of usage is @on(signal.SIGTERM) def termination(frame): print 'sent SIGTERM' raise SystemExit Code calling termination.signal() will send a SIGTERM signal to the main thread, which in turns will call the termination handler, which will print a message and raise SystemExit. ''' def handler_decorator(handler): 'Install the handler and add a .signal function attribute to it' signal.signal(sig, lambda signum, frame : handler(frame)) handler.signal = lambda : os.kill(os.getpid(), sig) return handler return handler_decorator Michele Simionato From rcdailey at gmail.com Tue Sep 25 18:16:25 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 25 Sep 2007 17:16:25 -0500 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: <496954360709251421l578b9dfdwcc0e67d293ede1f3@mail.gmail.com> References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> <496954360709251421l578b9dfdwcc0e67d293ede1f3@mail.gmail.com> Message-ID: <496954360709251516teda6f2dwe8190236029e3688@mail.gmail.com> Hmm, ElementTree.tostring() also adds a space between the last character of the element name and the />. Not sure why it is doing this. Something like will become after the tostring(). On 9/25/07, Robert Dailey wrote: > > One thing I noticed is that it is placing an arbitrary space between " and > />. For example: > > > > > Notice that there's a space between "image" and /> > > Any way to fix this? Thanks. > > On 9/24/07, Gabriel Genellina wrote: > > > > En Mon, 24 Sep 2007 23:51:57 -0300, Robert Dailey > > escribi?: > > > > > What I meant was that it's not an option because I'm trying to learn > > > regular > > > expressions. RE is just as built in as anything else. > > > > Ok, let's analyze what you want. You have for instance this text: > > "" > > which should become > > "" > > > > You have to match: > > (opening angle bracket)(any word)(closing angle bracket)(opening angle > > bracket)(slash)(same word as before)(closing angle bracket) > > > > This translates rather directly into this regular expression: > > > > r"<(\w+)>" > > > > where \w+ means "one or more alphanumeric characters or _", and being > > surrounded in () creates a group (group number one), which is > > back-referenced as \1 to express "same word as before" > > The matched text should be replaced by (opening <)(the word > > found)(slash)(closing >), that is: r"<\1/>" > > Using the sub function in module re: > > > > py> import re > > py> source = """ > > ... > > ... > > ... > > ... > > ... """ > > py> print re.sub(r"<(\w+)>", r"<\1/>", source) > > > > > > > > > > > > > > Now, a more complex example, involving tags with attributes: > > --> > > > > You have to match: > > (opening angle bracket)(any word)(any sequence of words,spaces,other > > symbols,but NOT a closing angle bracket)(closing angle bracket)(opening > > angle bracket)(slash)(same word as before)(closing angle bracket) > > > > r"<(\w+)([^>]*)>" > > > > [^>] means "anything but a >", the * means "may occur many times, maybe > > zero", and it's enclosed in () to create group 2. > > > > py> source = """ > > ... > > ... > > ... """ > > py> print re.sub(r"<(\w+)([^>]*)>", r"<\1\2 />", source) > > > > > > > > > > Next step would be to allow whitespace wherever it is legal to appear - > > left as an exercise to the reader. Hint: use \s* > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Sep 7 22:42:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Sep 2007 23:42:43 -0300 Subject: Subprocess module and unicode input References: <1189201586.423477.28200@g4g2000hsf.googlegroups.com> Message-ID: En Fri, 07 Sep 2007 18:46:26 -0300, Matthew Lausch escribi?: > I'd like to use the subprocess module with upper level characters in > the process name or in the arguments to the process. Something like > this: > > cmd = [ u'test_\u65e5\u672c\u8a9e_exec.bat', u'arg1', u'arg2' ] > subprocess.call(cmd) > > But this gives the error: > > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 5-7: ordinal not in range(128) > > Is there a way around this problem? I don't want to assume any > particular set of characters. The example above uses Japanese > characters, but I would like to support anything. You have to encode those unicode objects anyway - but you don't have to assume any encoding. Your .bat file will be executed by CMD.EXE, and the shell expects a string - doesn't understand unicode objects. Like when you type that same commands on the console. Use sys.getfilesystemencoding() to obtain the required encoding (likely "mbcs"): fse = sys.getfilesystemencoding() cmd = [arg.encode(fse) if isinstance(arg,unicode) else arg for arg in cmd] -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Sep 2 18:33:31 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 02 Sep 2007 22:33:31 -0000 Subject: Adding attributes stored in a list to a class dynamically. References: <1i3t9va.1jkz4om1sajk8pN%aleax@mac.com> <1188769303.724140.248630@d55g2000hsg.googlegroups.com> Message-ID: <13dmehro14cjp05@corp.supernews.com> On Sun, 02 Sep 2007 21:41:43 +0000, Brian Munroe wrote: > One question though, which I haven't been able to find the answer from > scouring the internet. What is the difference between calling > __setattr__ and setattr or __getattr__ and getattr, for that matter? Have you read the following? # setattr, getattr, delattr: http://www.python.org/doc/lib/built-in-funcs.html # __setattr__ etc. http://www.python.org/doc/ref/attribute-access.html If there is anything unclear about the descriptions, please ask. In a nutshell, like all double-underscore methods, __setattr__ are for overriding behaviour in your own classes. With very few exceptions, you shouldn't need to directly call double-underscore methods (although you often may _write_ double-underscore methods). -- Steven. From pyth0nc0d3r at gmail.com Fri Sep 21 20:20:26 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 21 Sep 2007 19:20:26 -0500 Subject: Is it possible to grab headers after you login to a site? Message-ID: For instance cookie headers? I want to login to a site and make sure the site remembers im logged in using python and cgi. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolf_tracks at invalid.com Wed Sep 19 09:23:30 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 19 Sep 2007 06:23:30 -0700 Subject: Tutorial or Example (or Tutorial) of Using Canvas to Produce a Plot In-Reply-To: References: <13evohih7rkd030@corp.supernews.com> <13f0b2qlvj5ige6@corp.supernews.com> <9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com> Message-ID: <6o9Ii.9922$924.4192@newssvr23.news.prodigy.net> Here seems to be another good source. W. Watson wrote: > Ah, I missed your link to Chap 11. That looks very helpful. > > W. Watson wrote: >> Thanks. I've arranged for an inter-library loan(ILL), and probably >> will not get his book for several days yet. I've had the book before, >> but was really unable to get the time to pursue it (the ILL). I have >> his web site bookmarked. I do not yet plan to buy his book, web or >> hardbound yet. Maybe I can re-examine his site for examples, and find >> one that is appropriate. >> >> >> Richard Townsend wrote: >>> On Tue, 18 Sep 2007 13:18:36 -0700, "W. Watson" >>> wrote: >>> >>>> Tk is it. I'm really not interested in the others at this point. >>>> >>> >>> John Grayson's book 'Python and Tkinter Programming' has a chapter on >>> plotting Graphs and Charts. You can even download that chapter as a >>> PDF file: >>> >>> http://www.manning-source.com/books/grayson/grayson_ch11.pdf >>> >>> See http://www.manning.com/grayson/ for more info about the book. >>> >> > -- Wayne Watson (Nevada City, CA) Web Page: From steve at holdenweb.com Sun Sep 16 14:25:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Sep 2007 14:25:42 -0400 Subject: (curses) issue about inch() In-Reply-To: <1189960868.349377.249530@k79g2000hse.googlegroups.com> References: <1189955232.216664.167840@19g2000hsx.googlegroups.com> <1189960868.349377.249530@k79g2000hse.googlegroups.com> Message-ID: Jimmy wrote: > On Sep 17, 12:07 am, Steve Holden wrote: >> Jimmy wrote: >>> hi, all >>> I attempt to use the function inch() to get the character at the >>> current position, and compare it with a particular character like : >>> if screen.inch(x,y) == 'F' >>> but this method doesn't seem work, can anyone tell me the reason and >>> how to corrent it >>> thanks >> The reason is because something is wrong, and yo fix it by correcting >> that issue. >> >> In other words, if you could be a bit more specific about *how* it >> doesn't work (like, show us the code you are running,a nd any error >> messages or evidence of incorrect results) you will be able to get some >> help that actually helps you. >> >> Would you go to a car repair shop with faulty brakes and just tell them >> "my car isn't working"? >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 >> Holden Web LLC/Ltd http://www.holdenweb.com >> Skype: holdenweb http://del.icio.us/steve.holden >> >> Sorry, the dog ate my .sigline > > thanks, > actually i'm writing a game like mine,the pertainign code is: > > def mark(): > """mark the bomb""" > (row, col) = gb.scrn.getyx() > x = gb.scrn.inch(row,col) > if x == 'F': > gb.scrn.addch(row,col, 'X',curses.color_pair(3)) > else: > gb.scrn.addch(row,col, 'F',curses.color_pair(3)) > > gb.scrn.move(row,col) > gb.scrn.refresh() > > the situation is x never equals 'F', even when it really is! > I checked the mannual and found the return value of inch() consists > the actual character(low 8bits) > and the attributes, so I tried the following: (x<<24)>>24,cause I > guess the int is 32bits long. > but it still doesn't work :( > Well first of all, thanks for reading the manual. Let's suppose the value you are receiving is 1234 (clearly more than 8 bits). Unfortunately for you, recent versions of Python don't just use 32-bit integers, but extend the values into Python's long values where necessary. See: >>> (1234<<24)>>24 1234L >>> What you really need is a logical and with 255: >>> 1234 & 255 210 >>> Hope this helps. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From berteun at gmail.com Wed Sep 26 10:27:02 2007 From: berteun at gmail.com (Berteun Damman) Date: Wed, 26 Sep 2007 14:27:02 -0000 Subject: Tracking memory usage and object life time. In-Reply-To: <5lv1nuFadb95U1@mid.individual.net> References: <1190808386.571152.103710@22g2000hsm.googlegroups.com> <5lv1nuFadb95U1@mid.individual.net> Message-ID: <1190816822.684027.323630@w3g2000hsg.googlegroups.com> On Sep 26, 2:31 pm, Bjoern Schliessmann wrote: > Did you check the return value of gc.collect? Also, try using > other "insight" facilities provided by the gc module. gc.collect states it cannot find any unreachable objects. Meanwhile the number of objects the garbage collector has to keep track of keeps increasing. > You cannot "del" structures, you only "del" names. Objects are > deleted when they are not bound to any names when and if the > garbage collector "wants" to delete them. I understand, but just before I del the name, I ask for the refererres to the object the name indicates, and there's only one object. Since it is a local variable, I think this is logical. This object is a dictionary which contains strings as keys, and heaps as values. This heap consists of tuples. Every string is referenced more than once (that's logical), the heaps are only referenced once. So I would expect those to be destroyed if I destroy the dictionary. I furthermore assume that if I call gc.collect() I force the garbage collector to collect? Even if it wouldn't "want" to collect otherwise? > Be sure to check for cyclic references, they can be a problem for > the GC. I don't see how these could occur. It's basically something like list (of lists possibly) of ints/strings. No list containing itself. I'll see whether I can make a stripped down version which exhibits the same memory growth. Berteun From mail at timgolden.me.uk Mon Sep 3 09:27:02 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 03 Sep 2007 14:27:02 +0100 Subject: Soemthing wrong w/ urllib module or something. In-Reply-To: References: <46DBC5CB.3040007@timgolden.me.uk> Message-ID: <46DC0BA6.50606@timgolden.me.uk> [Tim Golden] >> To do the obvious, can you open a socket connection >> to the domain you're using? >> >> >> from socket import socket >> socket ().connect (("DOMAINHERE", 80)) >> >> >> >> or does it give you the same error? [Lamonte Harris] > Yeah I basically got the same error. > > Traceback (most recent call last): > File "", line 1, in > File "", line 1, in connect > socket.error: (10053, 'Software caused connection abort') OK, then *something's* blocking access to that host (at least) on port 80. Can you browse the web normally from this machine? In particular, can you browse to that site ("DOMAINHERE")? TJG From jo5867472 at gmail.com Thu Sep 13 14:03:40 2007 From: jo5867472 at gmail.com (jo5867472 at gmail.com) Date: Thu, 13 Sep 2007 18:03:40 -0000 Subject: plotting pixels in python Message-ID: <1189706620.564963.29690@d55g2000hsg.googlegroups.com> hi to all I am just a beginner of python. I want to know how pixels are plotted in python. I am not intending to use PIL because I don't need to manipulate images. So is there a simple module for 2D graphics and plot pixels From steve at holdenweb.com Sun Sep 16 11:56:38 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Sep 2007 11:56:38 -0400 Subject: generating list of sub lists In-Reply-To: References: <1189931217.415065.102820@w3g2000hsg.googlegroups.com> Message-ID: Rustom Mody wrote: > On 9/16/07, cesco wrote: >> Hi, >> >> is there a one-liner to accomplish the following task? >> >From the list >> l = ['string1', 'string2', 'string3'] >> generate the list of lists >> l = [['string1'], ['string1', 'string2'], ['string1', 'string2', >> 'string3']] >> >> Any help would be appreciated. >> >> Thanks >> Francesco >>>> l = [1,2,3,4,5] > >>>> [l[:i] for i in range(len(l))] > [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] > well almost works except for the first empty list. [Are you sure you > dont want it?] > > Corrected > >>>> [l[:i+1] for i in range(len(l)-1)] > [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] > > Though I wonder if there is as neat a way as the first? >>> [l[:i] for i in range(1, len(l))] [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] >>> seems a slightly neater way to meet the requirement. regards steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From zzbbaadd at aol.com Tue Sep 4 01:10:41 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 03 Sep 2007 22:10:41 -0700 Subject: parameter list notation In-Reply-To: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> Message-ID: <1188882641.899594.212400@22g2000hsm.googlegroups.com> Well I did a search on "Python variable length arguments" and found a hit that seems to explain the *fields parameter: When you declare an argment to start with '*', it takes the argument list into an array. def foo(*args): print "Number of arguments:", len(args) print "Arguments are: ", args From steve at holdenweb.com Wed Sep 5 10:23:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 05 Sep 2007 07:23:40 -0700 Subject: Checking if elements are empty In-Reply-To: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> Message-ID: Doran, Harold wrote: > Dear list: > > Suppose I have a string as follows > > x = ' \t'ff' > >>> x = ' \t'ff' File "", line 1 x = ' \t'ff' ^ SyntaxError: invalid syntax >>> I presume you meant x = ' \t\'ff' > I can split this up as > > y = x.split('\t') > > Which gives > > [ ' ', 'ff'] > > len(y) > 2 > > Is there a way to check if the first element of y is null? > len(y[0]) == 0 would be the obvious way, assuming "null" means "the null string". If whitespace is significant that'll do, if it isn't then you may need to use the strip() method to remove it before your scheck. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From sjmachin at lexicon.net Sat Sep 29 07:22:40 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 29 Sep 2007 04:22:40 -0700 Subject: Delete spaces In-Reply-To: <1190994234.526554.110870@y42g2000hsy.googlegroups.com> References: <1190994234.526554.110870@y42g2000hsy.googlegroups.com> Message-ID: <1191064960.624796.115790@d55g2000hsg.googlegroups.com> On Sep 29, 1:43 am, kou... at hotmail.com wrote: > If I have a text file that is delimited by spaces, how do I import it > and get to comma delimited? Here is a row of data from the text file: > > 1 1 10:55:14 2 65 8.5 > 1.4+1.1 2.5 Class-2 0 > > I tried a few examples from the group and it didn't work, since the > file also has a header row and a row of seperators ( -------). The > lengths of each row is something like 130, so there are extra spaces > after the last value as well. I have tried joining and other things, > but I couldn't figure out how to get the values to come together. > Thanks. > > Kou It would help enormously if you could show us UNAMBIGUOUSLY what is in say the first 3 lines after the headings and separators -- do this: print repr(open("thefile", "rb").read()[:400]) The other thing you need is to know enough about the file format to show us what is the CSV output that you require from the sample input -- we don't have crystal balls, and are likely to make half-donkeyed guesses, like these: If the spaces are really tabs, use line.split('\t') Otherwise: the file has fixed column widths, and any use of line.split will mangle it. The clumsy way to handle this is to count column positions, and write something ugly like: field1 = line[0:8] field2 = line[8:20] etc "a row of seperators ( -------)" sounds suspiciously like the "column aligned" format that can be produced by running a SQL query on a SQL Server database using MS's "Query Analyser". It looks like this: RecordType ID1 ID2 Description ----------- -------------------- ----------- ---------------------- 1 12345678 123456 Widget 4 87654321 654321 Gizmoid etc Does your file look something like that? If so, then all you have to do is leverage off the fact that the second line has one-space gaps between each bunch of dashes, and you can write a little module that will read any file like that, just as though it were a CSV file. Over to you .... Cheers, John From hniksic at xemacs.org Wed Sep 12 10:35:36 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 12 Sep 2007 16:35:36 +0200 Subject: MemoryError on reading mbox file References: <1189589259.662667.149730@w3g2000hsg.googlegroups.com> Message-ID: <87veaggddz.fsf@mulj.homelinux.net> Christoph Krammer writes: > I have to convert a huge mbox file (~1.5G) to MySQL. Have you tried commenting out the MySQL portion of the code? Does the code then manage to finish processing the mailbox? From harry.g.george at boeing.com Tue Sep 11 08:56:12 2007 From: harry.g.george at boeing.com (Harry George) Date: Tue, 11 Sep 2007 12:56:12 GMT Subject: Python Database Apps References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> Message-ID: Tom Brown writes: > On Monday 10 September 2007 19:52, darien.watkins at gmail.com wrote: >> Kindof a poll, kindof curiosity... >> >> What is your favorite python - database combination? I'm looking to >> make an app that has a local DB and a server side DB. I'm looking at >> python and sqlite local side and sql server side. >> >> Any suggestions???? > > I have had a lot of good luck with PostgreSQL. It is easy to install and use. > It is also very stable. It maybe overkill for a client side database. The > psycopg package makes interfacing to PostgreSQL very easy and there is a > package for Linux and Windows to make cross-platform development a breeze. > > -Tom I use postgresql as well. I wonder if Pythonistas do so out of concern for rigor, clarity, and scalability. It works fine for a quick one-off effort and still works fine after scaling to a DBMS server supporting lots of clients, and running 10's of GBs of data. If an app comes already designed for mysql, oracle, sqlite, db2, dbm, etc I'll use those. But for my own projects, it is postgresql, with maybe SQLAlchemy (I'm back and forth on that. Mostly stay with straight SQL). Of course, as long as you write DBI2 compliant code, your app doesn't much care which DBMS you use. The postgresql payoff is in admin functionality and scaling and full ACID. -- Harry George PLM Engineering Architecture From kay.schluehr at gmx.net Wed Sep 19 06:06:57 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 19 Sep 2007 03:06:57 -0700 Subject: Metatest 0.1.0 In-Reply-To: <46F05FB1.7070807@pytex.org> References: <1190130384.753009.142150@i13g2000prf.googlegroups.com> <46F006D5.3060609@pytex.org> <1190147863.968759.229330@g4g2000hsf.googlegroups.com> <46F05FB1.7070807@pytex.org> Message-ID: <1190196417.558367.38490@o80g2000hse.googlegroups.com> On 19 Sep., 01:30, Jonathan Fine wrote: > > there is no fundamental reason why it can't be separated from > > eeconsole.py. > > OK. That might be a good idea. Ironically, I liked the idea of having more expressive assert statements - a discussion you brought up. But this requires either syntcatical analysis in the general case ( EE and assert magic ) some particular API ( Ben Finney ) or a somewhat restricted, but fully embedded, domain specific language ( Metatest ). Here is what I got after an hour of hacking and filtering assert. Additional remarks are in line comments: _______________________________________________________________________________ ZERO On Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] Reuses session report ZERO_20.eerp _______________________________________________________________________________ # define a test function add and check it out >>> def add(y,x): ... return x+y ... >>> assert add(1,2) == 0 Traceback (most recent call last): File "", line 1, in AssertionError: 3 == 0 # An tested assertion is splitted into lhs, op, rhs. If this is not possible assert # won't be changed by magics. # Here we see a simple formatting of the result in the form: # "%s %s %s" % (eval(lhs), op, eval(rhs)) # More elaborated formatting schemes are user defined: >>> class MyFormatter(AssertionFormatter): ... def format(self, lhs, op, rhs): ... if op == "==": ... return "Expected: %s. Received: %s"%(lhs, rhs) ... else: ... return super(MyFormatter, self).format(lhs, op, rhs) ... # The class AssertionFormatter is defined in EasyExtend.fibers.zero.fiber. # It provides a single method # # format(lhs: str, op: str, rhs: str) -> str # # The default behaviour is the one # demonstrated above. One can overwrite format in subclasses and pass the subclass # instance to assert. # The arguments will be supplied by the framework. # Here we see the new formatter in action: >>> assert add(1,2) == 0, MyFormatter Traceback (most recent call last): File "", line 1, in AssertionError: Expected: 3. Received: 0 # Now it falls back to the default formatting: ?>>> >>> ! >>> assert add(1,2) <=0, MyFormatter Traceback (most recent call last): File "", line 1, in AssertionError: 3 <= 0 >>> quit --------------------. Recorded assertions | -------------------------------------------------------------------------------------------------- Status |eerp ln|repl ln| Assertion -------+-------+------- +-------------------------------------------------------------------------- ERROR | 14 | 14 | assert add(1,2) == 0 ERROR | 26 | 26 | assert add(1,2) == 0, MyFormatter ERROR | 31 | 31 | assert add(1,2) <=0, MyFormatter -------+-------+------- +-------------------------------------------------------------------------- Regards, Kay From steve at holdenweb.com Thu Sep 27 10:03:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 10:03:10 -0400 Subject: Confusion regarding constructor as default value In-Reply-To: <1190900523.963182.306590@r29g2000hsg.googlegroups.com> References: <1190898221.833936.40480@57g2000hsv.googlegroups.com> <1190900523.963182.306590@r29g2000hsg.googlegroups.com> Message-ID: aine_canby at yahoo.com wrote: > On 27 Sep, 15:03, aine_ca... at yahoo.com wrote: >> Why are the following different? >> >> def AddRow(self, rowName, tableRow=TableRow(ReleaseDate(""), >> ExpiryDate(""))): >> # check to see if the row already exists, if not add it to the >> container >> >> if not self.dict.has_key(rowName): >> self.dict[rowName] = tableRow >> >> def AddRow(self, rowName, tableRow): >> # check to see if the row already exists, if not add it to the >> container >> >> if not self.dict.has_key(rowName): >> self.dict[rowName] = TableRow(ReleaseDate(""), ExpiryDate("")) >> >> It seems that when I use the first function that I'm getting duplicate >> objects in self.dict >> >> Thanks for your help, >> >> Aine. > > I've just tried the following: > > Function A: > > def AddRow(self, rowName, tableRow=TableRow(ReleaseDate(""), > ExpiryDate(""))): > > print tableRow > if not self.dict.has_key(rowName): > self.dict[rowName] = tableRow > > Function B: > > def AddRow(self, rowName, tableRow=None): > > if tableRow==None: > tableRow = TableRow(ReleaseDate(""), ExpiryDate("")) > # check to see if the row already exists, if not add it to the > container > print tableRow > if not self.dict.has_key(rowName): > self.dict[rowName] = tableRow > > Function A is giving: > > > same! > same! > same! > same! > > Function B is giving: > > > > > > > > So at least I know know what is causing the problem. But I'm still not > understanding why I can't use TableRow() as the default value in order > to geterate new instances. > Because the value of the default is computed as the funciton declaration is processed, whereas you seem to expect to see a new call to ExpiryDate each time the function is called. > How would you implement this? > > Thanks, > > Aine. > Function B is the canonical solution to this problem. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 7 11:42:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 07 Sep 2007 17:42:03 +0200 Subject: Organizing Code - Packages In-Reply-To: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> References: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> Message-ID: <46e17143$0$6189$426a74cc@news.free.fr> xkenneth a ?crit : > All, > > I apologize if this is a commonly asked question, but I didn't > find anything that answered my question while searching. > > So what I have right now is a few packages that contain some commonly > used functions and another package that contains all of my custom > error classes. I want these error classes available to me in all of > the other packages in my library. Currently to achieve this at the top > of every module file I have the line "from My.Library.Errors import > *", my problem with this is that it manages to import the Errors into > every scope that they are used. Ain't that what you want ??? Having "these error classes available to me in all of the other packages in my library" ? If you're worried about perfs or whatever, don't worry, a module is only imported once - next imports will only bind the names in the importing namespace. > I'm still pretty new to Python, and my > approachs are probably very rooted in C/C++ (I've had the hardest time > getting over not being able to overload functions), but am I doing > this correctly? Yes, that's the right thing to do. > Also, are there any good tutorials/examples out there of how to > organize your python code into packges? Most of the Python-specific aspects should be covered by the tutorial (the one in the doc). Else, it's as usual, trying to have high cohesion and low coupling. Ah, yes, a couple of things: - avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens of classes in a same module - plain functions are ok too - no need to stick everything in classes. HTH From seanttierney at gmail.com Fri Sep 21 19:47:17 2007 From: seanttierney at gmail.com (Sean Tierney) Date: Fri, 21 Sep 2007 16:47:17 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190415741.380795.259050@y42g2000hsy.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> Message-ID: <54e1e4bc0709211647v10140c13y90c9bd68007c8398@mail.gmail.com> Just tell him that "functions are like all other variables and can therefore be passed by other functions or returned by other functions. " If your friend understands variables and functions and he can't make the "leap" (and assuming you're right, of course) then your friend doesn't understand variables and functions. Happy Friday. Sean On 9/21/07, Cristian wrote: > On Sep 21, 3:44 pm, Ron Adam wrote: > > > I think key may be to discuss names and name binding with your friend. How > > a name is not the object it self, like a variable is in other languages. > > For example show him how an object can have more than one name. And discus > > how names can be bound to nearly anything, including classes and functions. > > I could discuss name binding but it would be great if Python said this > itself. After all, you can even bind a module with the foo = bar > syntax by using __import__ function. If function definitions followed > the same pattern, I think a beginner would subconsciously (maybe even > consciously) realize that function names are just like everything > else. Actually, this would be helpful for many people. If you come > from a language like Java you're used to thinking of attributes and > methods as living in different namespaces. I think a new syntax will > encourage seasoned programmers think in a more Pythonic way. > > Python has done a very good job in easing people into programming. My > friend doesn't come to me very often because the syntax is clear and > simple and the builtin datatypes allow you to do so much. My goal is > that I would never have to explain to him about name binding; that > he'd pick it up by learning the language on his own. He's learned > lists, dictionaries and even some OOP without me. I don't think name > binding would be a stretch. > > > You could also discus factory functions with him. Once he gets that a > > function can return another function, then it won't be so much of a leap > > for a function to take a function as an argument. > > I think this isn't the most intuitive way of approaching first order > functions. It's true that if a function can return another function > then a function must be first order (i.e., it's just like any other > variable), but that seems almost backwards to me. I think it would > make more sense to have beginners _know_ that functions are like all > other variables and can therefore be passed by other functions or > returned by other functions. That I think would be better accomplished > if they define functions the same way you would define other variables > that you know can be passed and returned. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sean Tierney From steven.bethard at gmail.com Sun Sep 30 03:01:32 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 30 Sep 2007 01:01:32 -0600 Subject: Optparse and help formatting? In-Reply-To: References: Message-ID: Tim Chase wrote: > I've been learning the ropes of the optparse module and have been > having some trouble getting the help to format the way I want. > > I want to specify parts of an option's help as multiline. > However, the optparse formatter seems to eat newlines despite my > inability to find anything in optparse.py that does something > obvious like .replace("\n", " ") to eat the newlines I stick in > the help. It also seems to mung tabs. An example from my code: > > parser.add_option("-x", "--extended", > action="callback", > callback=callback_test, > type="string", # required to get metavar to show in help > dest="test", > metavar="CONF", > help="a comma-separated list of options.\n" > "s=[YYYY]MMDD,n=NAME,c=COLOR\n" > "s,start=[YYYY]MMDD\n" > "\tstart day of period (default, current day)\n" > ... > ) > > which would accept options that looked something like > > test.py -x s=20070401,n=XR71,c=black > > (my callback_test breaks apart parser.rargs[0] to deal with the > funky params). > > However, when I display the help, its reformatting eats the > newlines in my help-string and strangely looks like it converts > my tabs to spaces. > > Any hints on how to either work around the problem or fix it? I guess this is just an optparse-y week on c.l.py. ;-) Ben Finney pointed you in the right direction for optparse. If you care to try out argparse (http://argparse.python-hosting.com/) which has a similar API, it has a builtin RawTextHelpFormatter formatter class:: import argparse def my_type(string): # split string and turn it into appropriate object(s) return 'foo(%s)' % string parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument( "-x", "--extended", type=my_type, dest="test", metavar="CONF", help="a comma-separated list of options.\n" "s=[YYYY]MMDD,n=NAME,c=COLOR\n" "s,start=[YYYY]MMDD\n" "\tstart day of period (default, current day)\n" ) args = parser.parse_args() print args.test This program will produce output like:: $ python script.py -x sdfsdfas foo(sdfsdfas) $ python script.py --help usage: script.py [-h] [-x CONF] optional arguments: -h, --help show this help message and exit -x CONF, --extended CONF a comma-separated list of options. s=[YYYY]MMDD,n=NAME,c=COLOR s,start=[YYYY]MMDD start day of period ... HTH, STeVe From dnhkng at googlemail.com Fri Sep 7 15:16:46 2007 From: dnhkng at googlemail.com (Dr Mephesto) Date: Fri, 07 Sep 2007 19:16:46 -0000 Subject: creating really big lists In-Reply-To: <1189063849.118900.327540@22g2000hsm.googlegroups.com> References: <874pi92tr4.fsf@mulj.homelinux.net> <1189057626.943757.210420@d55g2000hsg.googlegroups.com> <1189063849.118900.327540@22g2000hsm.googlegroups.com> Message-ID: <1189192606.119578.100820@r34g2000hsd.googlegroups.com> On 6 Sep., 09:30, Paul McGuire wrote: > On Sep 6, 12:47 am, Dr Mephesto wrote: > > > > > I need some real speed! a database is waaay to slow for the algorithm > > im using. and because the sublists are of varying size, i dont think I > > can use an array...- Hide quoted text - > > > - Show quoted text - > > How about a defaultdict approach? > > from collections import defaultdict > > dataArray = defaultdict(lambda : [[],[],[],[],[]]) > dataArray[1001][3].append('x') > dataArray[42000][2].append('y') > > for k in sorted(dataArray.keys()): > print "%6d : %s" % (k,dataArray[k]) > > prints: > 1001 : [[], [], [], ['x'], []] > 42000 : [[], [], ['y'], [], []] > > -- Paul hey, that defaultdict thing looks pretty cool... whats the overhead like for using a dictionary in python? dave From exhuma at gmail.com Wed Sep 19 02:54:27 2007 From: exhuma at gmail.com (exhuma.twn) Date: Tue, 18 Sep 2007 23:54:27 -0700 Subject: Using python to create windows apps that everyone can use? In-Reply-To: References: <7C008A37566.00000D2Atomharding@inbox.com> Message-ID: <1190184867.787656.181590@k79g2000hse.googlegroups.com> On Sep 18, 9:22 pm, "Matt McCredie" wrote: > On 9/18/07, Thomas Harding wrote: > > > Hi guys, sorry to post another topic on this, as I am aware that it has > > already been posted a few times, but not with specifically what I am looking > > for. I want an app that makes a gui interface for python (similar to > > Microsoft visual studio or qt designer, not a code based one) and/or an app > > that can make this into a .exe that can be opened by any person on any > > computer without python installed. > > check out py2exe:http://py2exe.org > > matt I am currently building an application with Python using Qt4.3 as widget-toolkit. So I can use designer too ;) Links that might be of interest to you: - http://www.riverbankcomputing.co.uk/pyqt/ - http://www.py2exe.org/index.cgi/Py2exeAndPyQt This works quite well. From mridula.ccpl at gmail.com Mon Sep 17 02:42:17 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Mon, 17 Sep 2007 12:12:17 +0530 Subject: adodb with mysql - connection string syntax for filepath Message-ID: <33dffc910709162342x49657895t938fb1f8af2834de@mail.gmail.com> Dear all, Hi. I am not very tech-savvy so please pardon me if this is a stupid question: so far I have been googling for about 4 days to find help for this, so now I am desperate! :) How do you use adodb with mysql to connect to a file that is on your machine? Also, could you please recommend to me a good resource to learn more about classes and modules from? i don't understand half of the _init_ business that many sites mention. (This *is* something even a newbie needs to learn, right?) Thank you! M.R.S. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joemystery123 at gmail.com Fri Sep 14 10:27:45 2007 From: joemystery123 at gmail.com (joe shoemaker) Date: Fri, 14 Sep 2007 10:27:45 -0400 Subject: newbee: Simple Backend Python Script Question Message-ID: <372de840709140727x65b58400jadccb24bbabbdf62@mail.gmail.com> I need to create python script that is threaded. So the main program will run in infinite loop and just retrieving messages and putting them in a queue. (Main thread) I need child threads from a pool to process the queue. When there is no stuff in the queue, they go to the pool and become available but they don't terminate. This has to be done continuously. Main program need to keep putting stuff in the queue, when there are no messages, then it sleeps for short time and check back to see any messages. To do this, I guess you don't write joinAll(), so that the main threads just don't wait for the child but goes to work. am I right? Also, child threads (a function that is threaded) will make connecitons to the database. I am planning to use threadpool, so that threads reuse the connections. So do you close the database connection at the end of the function? If not then the connection will be opened forever? Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.behnel-n05pAM at web.de Thu Sep 27 03:28:14 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 27 Sep 2007 09:28:14 +0200 Subject: How do I get the value out of a DOM Element In-Reply-To: <1190872252.204687.286640@19g2000hsx.googlegroups.com> References: <1190872252.204687.286640@19g2000hsx.googlegroups.com> Message-ID: <46FB5B8E.8050100@web.de> kj7ny wrote: > I have been able to get xml.dom.minidom.parse('somefile.xml') and then > dom.getElementsByTagName('LLobjectID') to work to the point where I > get something like: [] which I > can get down to but then I > can't find any way to just get the value out from the thing! > > .toxml() returns something like: u' LLobjectID>'. > > How do I just get the 1871203 out of the DOM Element? It contains a CDATA node which in turn contains a Text node (AFAIR), so you have to walk through the children to get what you want. Alternatively, try an XML API that makes it easy to handle XML, like ElementTree (part of the stdlin in Python 2.5) or lxml, both of which have compatible APIs. The code would look like this: tree = etree.parse("some_file.xml") id = tree.find("//LLobjectID") print id.text Stefan From bdesth.quelquechose at free.quelquepart.fr Sat Sep 29 11:44:27 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 29 Sep 2007 17:44:27 +0200 Subject: Can you please give me some advice? In-Reply-To: References: Message-ID: <46ffe55d$0$26294$426a74cc@news.free.fr> Byung-Hee HWANG a ?crit : > Hi there, > > What is different between Ruby and Python? Not much - both are hi-level dynamic object oriented languages with some functional aspects - and quite a lot (their respective object models are totally different). Also, Python, being somewhat older, has perhaps a better implementation, more 3rd part librairies, and a greater (in size) community - but it also suffers from cruft accumulated thru the years and a documentation that's getting a bit messy (not that it's badly documented, but some features are not necessarily covered in the official tutorial...) > I am wondering what language > is really mine for work. The one that best fit your brain, I'd say - or the one that best fit your project. > Anyway I will really make decision today what I have to > study from now on. What I make the decision is more difficult than to > know why I have to learn English. Yeah I do not like to learn English > because it is just very painful.. > > Can you please give me some advice? Not wrt/ learning English !-) From aahz at pythoncraft.com Tue Sep 18 11:01:15 2007 From: aahz at pythoncraft.com (Aahz) Date: 18 Sep 2007 08:01:15 -0700 Subject: The meaning of a = b in object oriented languages References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> Message-ID: In article , Laurent Pointal wrote: >Summercool a ?crit : >> >> The meaning of a = b in object oriented languages. >> ==================================================== > > >Oups, reading the subject I thought it was a Xah Lee post. ...and you're perpetuating the impression by continuing the crossposting. Please don't. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From ldo at geek-central.gen.new_zealand Wed Sep 19 07:23:27 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 19 Sep 2007 23:23:27 +1200 Subject: uninstall python2.5 on debian References: Message-ID: In message , dimitri pater wrote: > I would like to uninstall Python2.5 which was installed > from source (make install) and keep 2.3. How about doing the make install again, and making a note of which files were installed, and removing those? From fakeaddress at nowhere.org Sun Sep 9 20:27:29 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 09 Sep 2007 17:27:29 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> <46E4466C.2030303@sdf.lonestar.org> <0W%Ei.14427$3x.11615@newssvr25.news.prodigy.net> Message-ID: Dotan Cohen wrote: > On 10/09/2007, Bryan Olson wrote: >> Not according to the C standard: >> >> When integers are divided, the result of the / operator is >> the algebraic quotient with any fractional part discarded.(87) >> If the quotient a/b is representable, the expression >> (a/b)*b + a%b shall equal a. >> [...] >> 87) This is often called ''truncation toward zero''. >> >> [International Standard ISO/IEC 9899:1999, Section 6.5.5 >> Multiplicative operators, Paragraph 6 and footnote 87] > > This seems most logical to me. Turbo C is against the standard, then. No, Turbo C is yielding the one-and-only correct result with respect to the C standard: (a/b)*b + a%b shall equal a (-111/10)*10 + -111%10 shall equal -111 (-111/10) evaluates to -11 by the truncate-toward-zero rule -11*10 + -111%10 shall equal -111 -110 + -111%10 shall equal -111 -111%10 shall equal -1 -- --Bryan From ptmcg at austin.rr.com Thu Sep 6 03:30:49 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 06 Sep 2007 00:30:49 -0700 Subject: creating really big lists In-Reply-To: <1189057626.943757.210420@d55g2000hsg.googlegroups.com> References: <874pi92tr4.fsf@mulj.homelinux.net> <1189057626.943757.210420@d55g2000hsg.googlegroups.com> Message-ID: <1189063849.118900.327540@22g2000hsm.googlegroups.com> On Sep 6, 12:47 am, Dr Mephesto wrote: > > I need some real speed! a database is waaay to slow for the algorithm > im using. and because the sublists are of varying size, i dont think I > can use an array...- Hide quoted text - > > - Show quoted text - How about a defaultdict approach? from collections import defaultdict dataArray = defaultdict(lambda : [[],[],[],[],[]]) dataArray[1001][3].append('x') dataArray[42000][2].append('y') for k in sorted(dataArray.keys()): print "%6d : %s" % (k,dataArray[k]) prints: 1001 : [[], [], [], ['x'], []] 42000 : [[], [], ['y'], [], []] -- Paul From daniel.j.larsson at gmail.com Wed Sep 5 09:47:18 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Wed, 5 Sep 2007 15:47:18 +0200 Subject: python exec behaves inconsistent with respect to module imports In-Reply-To: <1188997944.162811.33640@r34g2000hsd.googlegroups.com> References: <1188997944.162811.33640@r34g2000hsd.googlegroups.com> Message-ID: <2bfa72fa0709050647v34124d8diaa1ed61c331c476e@mail.gmail.com> On 9/5/07, carl.dhalluin at gmail.com wrote: > > Hello > > I am completely puzzled why the following exec code does not work: > > mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" > def execute(): > exec mycode > execute() > > > I get the error: > > root at devmachine1:/opt/qbase# python error1.py > Traceback (most recent call last): > File "error1.py", line 5, in ? > execute() > File "error1.py", line 4, in execute > exec mycode > File "", line 4, in ? > File "", line 3, in f > NameError: global name 'math' is not defined This is due to a namespace issue with exec, see http://docs.python.org/ref/exec.html#l2h-569 The namespace used in an exec statement is the local scope. This scope is different in your two cases. If you change the exec call to def execute(): exec mycode in globals() It will work as you expect. Note that the following code _does_ work: > > mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" > exec mycode > > > I have tested this in python 2.3 and 2.4. > > > Regards > Carl > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Sat Sep 15 06:31:06 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 15 Sep 2007 12:31:06 +0200 Subject: c interfacing in 2.5 In-Reply-To: References: Message-ID: <5l1qjvF60829U1@mid.uni-berlin.de> Rustom Mody schrieb: > I used python extensive 3-5 years back. Coming back I find some > changes. Trying to understand whats new and would appreciate any > help/comments/pointers. > > Earlier there were basically two options: > SWIG: convenient but inefficient > Native (Extending/Embedding): an efficient way of getting a headache! > (Boost being ignored because not using C++) > > Now it seems there are more possibilities: > > -- Sip seems to be more efficient than swig and easier than native but > not well documented > -- pyrex could be considered > -- I know someone who uses pygtk to make wrappings > > But most interesting is ctype. I wonder if having ctype in the core > language changes the ease of use of the native wrapping model and > thereby makes sip/swig etc less necessary? > > Your views and/or experience appreciated. ctypes is for C. Where it is great to use. If you need C++-wrapping, I recommend SIP. While the docs for SIP aren't overwhelming, I consider them accurate and complete. Best thing to do is to take a SIP-based project (most probably PyQt itself) and wheneever a question appears, rummage through it. Diez From bignose+hates-spam at benfinney.id.au Wed Sep 12 20:47:27 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 13 Sep 2007 10:47:27 +1000 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> Message-ID: <87sl5j5r34.fsf@benfinney.id.au> TheFlyingDutchman writes: > I am talking about how an author describes in English the "this" > pointer/reference in their book on programming C++ or Java. > > I don't think you will find them saying that under the covers "this" > was passed to the method (if in fact it is). They just say that it > refers to the current object inside that object's method. In other words, it's magic, and the behaviour has to be explained so the reader knows where the undeclared 'this' comes from. How is that preferable to the magic of "instance is passed as the first argument to a method"? -- \ "If nothing changes, everything will remain the same." -- | `\ Barne's Law | _o__) | Ben Finney From michael at jedimindworks.com Sun Sep 2 16:32:54 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 2 Sep 2007 13:32:54 -0700 Subject: how can I find out the process ids with a process name In-Reply-To: <12B3D8EF-C30A-4BCC-80A5-71ADFA8F6944@jedimindworks.com> References: <1188761187.522146.192380@y42g2000hsy.googlegroups.com> <12B3D8EF-C30A-4BCC-80A5-71ADFA8F6944@jedimindworks.com> Message-ID: <76F0B67C-609B-4D27-8A90-E1965F016C31@jedimindworks.com> > > cd /proc > for i in ls [0-9]*/status > do > echo $i `grep '^Name' $i | cut -f2` | sed 's/\/status//g' > done > Um... cd /proc for i in `ls [0-9]*/status` do echo $i `grep '^Name' $i | cut -f2` | sed 's/\/status//g' done --- Let the wookie win. From tenax.raccoon at gmail.com Mon Sep 17 11:55:23 2007 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 17 Sep 2007 08:55:23 -0700 Subject: Use GUI for Python In-Reply-To: <1190043073.093736.272750@k79g2000hse.googlegroups.com> References: <1190043073.093736.272750@k79g2000hse.googlegroups.com> Message-ID: <1190044523.666991.273910@y42g2000hsy.googlegroups.com> On Sep 17, 9:31 am, kou... at hotmail.com wrote: > I am new to python as I have been a VB programmer. I am used to the > GUI interface, and was wondering if I had to choose between a GUI for > Python, which one should I go with? Thanks. > > Kou You need to be more specific. Do you mean that you are used to working in an IDE environment, where you can readily access the list of classes, methods, and such? You might be interested in Eclipse [1], then installing the PyDev [2] plug-in to add Python support. Wing-IDE [3] and Komodo [4] may also be very suitable (but they cost money). If you mean that you want to develop programs with a GUI interface, then you have a number of choices [5]. Most of these choices do not work in the same way that Microsoft Studio's GUI designer works, partly because Python isn't tied to any of them. o wxWidgets is MFC-like o PyQT and PyGTK are similar to their underlying interfaces o Tkinter comes with the default Python install, and provides the Tk widget set o With IronPython, you can access the regular Microsoft .NET GUIs o PythonCard and EasyGUI are supposed to be pretty easy GUIs to use o Dabo is a full-on database/GUI/platform set to easy cross- platform GUI and database programming. The links to all those can be found at link [5]. Don't be afraid if the choices are overwhelming. You have choices. I highly recommend that you learn Python first, then examine the different GUI systems, keeping in mind any requirements you may have and your previous experience. [1] http://www.eclipse.org/ [2] http://pydev.sourceforge.net/ [3] http://wingware.com/ [4] http://www.activestate.com/products/komodo_ide/ [5] http://wiki.python.org/moin/GuiProgramming From w_a_x_man at yahoo.com Sun Sep 30 14:27:32 2007 From: w_a_x_man at yahoo.com (William James) Date: Sun, 30 Sep 2007 11:27:32 -0700 Subject: s.split() on multiple separators In-Reply-To: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> Message-ID: <1191176852.604761.179480@y42g2000hsy.googlegroups.com> On Sep 30, 8:53 am, mrk... at gmail.com wrote: > Hello everyone, > > OK, so I want to split a string c into words using several different > separators from a list (dels). > > I can do this the following C-like way: > > >>> c=' abcde abc cba fdsa bcd '.split() > >>> dels='ce ' > >>> for j in dels: > > cp=[] > for i in xrange(0,len(c)-1): > cp.extend(c[i].split(j)) > c=cp > > >>> c > > ['ab', 'd', '', 'ab', '', ''] > > But. Surely there is a more Pythonic way to do this? > > I cannot do this: > > >>> for i in dels: > > c=[x.split(i) for x in c] > > because x.split(i) is a list. E:\Ruby>irb irb(main):001:0> ' abcde abc cba fdsa bcd '.split(/[ce ]/) => ["", "ab", "d", "", "ab", "", "", "ba", "fdsa", "b", "d"] From steve at REMOVE-THIS-cybersource.com.au Sat Sep 15 19:54:58 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 15 Sep 2007 23:54:58 -0000 Subject: how to join array of integers? References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> Message-ID: <13eos6ihf2mjg4a@corp.supernews.com> On Sat, 15 Sep 2007 15:56:40 +0200, Arnau Sanchez wrote: > js escribi?: > >>> On 9/15/07, Summercool wrote: > >>> in Python... is the method to use ",".join() ? but then it must take >>> a list of strings... not integers... >>> >>> any fast method? > > > print ''.join([str(i) for i in [1,2,3]]) > > It's better to use generator comprehension instead of LC: > > ",".join(str(i) for i in [1, 2, 3]) Really? Why do you say that a generator expression is "better" than a list comprehension? >>> import timeit >>> timeit.Timer("', '.join([str(i) for i in [1,2,3]])", "").repeat() [5.0969390869140625, 4.5353701114654541, 4.5807528495788574] >>> timeit.Timer("', '.join(str(i) for i in [1,2,3])", "").repeat() [11.651727914810181, 10.635221004486084, 10.522483110427856] The generator expression takes about twice as long to run, and in my opinion it is no more readable. So what's the advantage? > Or, if you happen to like the itertools modules: > > from itertools import imap > ",".join(imap(str, [1, 2, 3])) >>> timeit.Timer("', '.join(imap(str, [1,2,3]))", ... "from itertools import imap").repeat() [9.3077328205108643, 8.655829906463623, 8.5271010398864746] Faster than a generator expression, but still pretty slow. -- Steven. From bignose+hates-spam at benfinney.id.au Fri Sep 7 19:47:42 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 08 Sep 2007 09:47:42 +1000 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> Message-ID: <87wsv2ox5t.fsf@benfinney.id.au> Will Maier writes: > On Fri, Sep 07, 2007 at 12:03:23PM -0000, Steven D'Aprano wrote: > [...] > > which is easy enough, but I thought I'd check if there was an > > existing solution in the standard library that I missed. Also, for > > other applications, I might want them to be rather less > > predictable. > > 2.5 includes the uuid module for RFC 4122 universally-unique IDs: > > http://docs.python.org/lib/module-uuid.html I second this recommendation. If you want arbitrary unique IDs that are not a function of the data they identify, the simplest solution is a monotonically-increasing serial number. If you want more than that, you might as well go straight to the standard UUIDs. Even if you're not using Python 2.5, grab the external 'python-uuid' package for your operating system and use that. If you use the options for including random elements, the generated UUIDs will even satisfy your "unpredictable" requirement. -- \ "This sentence contradicts itself -- no actually it doesn't." | `\ -- Douglas Hofstadter | _o__) | Ben Finney From grante at visi.com Fri Sep 7 09:10:16 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Sep 2007 13:10:16 -0000 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <13e2jdobu2kqkf1@corp.supernews.com> On 2007-09-07, Peter Otten <__peter__ at web.de> wrote: > Am Fri, 07 Sep 2007 10:40:47 +0000 schrieb Steven D'Aprano: > >> Python doesn't have any pointers. > > Thinking of python variables or "names" as pointers should > get you a long way when trying to understand python's behaviour. But thinking of them as names bound to objects will get you further (and get you there faster). ;) > As long as you keep in mind that python doesn't have pointers > to pointers, and no pointer arithmetic either... -- Grant Edwards grante Yow! Hello... IRON at CURTAIN? Send over a visi.com SAUSAGE PIZZA! World War III? No thanks! From hat at se-162.se.wtb.tue.nl Mon Sep 10 06:31:39 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 10 Sep 2007 12:31:39 +0200 Subject: Python wrapper, problem with subprocess read/write References: <1189176703.245411.60350@r29g2000hsg.googlegroups.com> Message-ID: On 2007-09-07, NeoGregorian wrote: > I tried instead to use: > > lines = [] > line = proc.stdout.readline() > while line : > lines.append(line) > line = proc.stdout.readline() > > This prints out everything except the ">" line, which is good. But > then freezes while waiting for input, which is bad. > > Any suggestions on how to solve this in a good way? 'readline()' reads a line, that is, some text ending with a new-line. Since your last line, the ">" prompt has no ending new-line, the call blocks, waiting for the new-line character. So the simple anser is "don't use readline()". You have to fall back to reading characters, such as "read(1)" (which block until it receives a character). In addition, you will have to do analysis on whether the line you are currently reading is a prompt, and if so, stop reading to prevent blocking. (and instead, give the program a command by writing to proc.stdin). In case you don't know, pexpect (Python expect) does all (and more) that you are trying to do. Sincerely, Albert From jergosh at wp.pl Wed Sep 5 05:45:29 2007 From: jergosh at wp.pl (=?UTF-8?B?R3J6ZWdvcnogU8WCb2Rrb3dpY3o=?=) Date: Wed, 05 Sep 2007 11:45:29 +0200 Subject: So what exactly is a complex number? In-Reply-To: <1188821241.516029.229020@o80g2000hse.googlegroups.com> References: <451mq4-les.ln1@ozzie.tundraware.com> <1188821241.516029.229020@o80g2000hse.googlegroups.com> Message-ID: <46DE7AB9.9000702@wp.pl> >> In fact, a proper vector in physics has 4 features: point of >> application, magnitude, direction and sense. >> > > so whats the "point of application" of the sum of two vectors? Do > tell. I believe vectors can only be added if they have the same point of application. The result is then applied to the same point. Regards, Greg From lasses_weil at klapptsowieso.net Fri Sep 7 05:56:14 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Fri, 07 Sep 2007 11:56:14 +0200 Subject: Class design (information hiding) In-Reply-To: References: Message-ID: <46e1203e$0$16117$9b4e6d93@newsspool1.arcor-online.net> Alexander Eisenhuth wrote: > As I figured out there is only public and private possible as speakin in > "C++ manner". Are you all happy with it. What does "the zen of python" > say to that design? (protected is useless?) > Ask it yourself: >>> import this > > class A: > def __init__(self): > self.__z = 1 > self._z = 2 > self.z = 3 > def _getX(self): > return "X" > def __getY(self): > return "Y" > def doAnything(self): > print self.__getY() > > > class B(A): > def __init__(self): > A.__init__(self) > print dir (self) > >>> b = B() > ['_A__getY', '_A__z', '__doc__', '__init__', '__module__', '_getX', > '_z', 'doAnything', 'z'] > > I was a bit surprised about '_A__getY' and '_A__z'. > In what way exactly? "__*"-type methods are meant to be private to the exact class they were defined in, so thats why you get these names prefixed with "_A__". If you're confused why that happens at all, look for "name mangling". > What would you say to a C++ Programmer about class interfaces in big > Python systems? What is the idea behind the _ and __ naming. Use or > don't use '_' methods ? (As Designer of the software, as Programmer of > the software) > Don't worry about information-hiding too much. If anyone is determined, they can get at any information they want. You should just rely on people not directly using a single-underscore method; thats how python does it: trust instead of force. Use the double underscore technique only when you *need* it, that is, you don't want a method to be overridden by a subclass -- for whatever reason that might be. Generally you can just forget about this type of methods. /W From exhuma at gmail.com Wed Sep 19 03:19:57 2007 From: exhuma at gmail.com (exhuma.twn) Date: Wed, 19 Sep 2007 00:19:57 -0700 Subject: Using python to create windows apps that everyone can use? In-Reply-To: References: <7C008A37566.00000D2Atomharding@inbox.com> Message-ID: <1190186397.712075.114330@g4g2000hsf.googlegroups.com> On Sep 18, 9:22 pm, "Matt McCredie" wrote: > On 9/18/07, Thomas Harding wrote: > > > Hi guys, sorry to post another topic on this, as I am aware that it has > > already been posted a few times, but not with specifically what I am looking > > for. I want an app that makes a gui interface for python (similar to > > Microsoft visual studio or qt designer, not a code based one) and/or an app > > that can make this into a .exe that can be opened by any person on any > > computer without python installed. > > check out py2exe:http://py2exe.org > > matt Oh... I forgot. With newer versions of Qt, you have to adapt the setup script a bit. Here's an example (even with an icon-resource ) ;) setup(windows=['ide.py'], options={"py2exe":{ "includes":["sip", "PyQt4._qt"], "icon_resources":[(1,"gnucash.ico")]}}) The trick here, is to also add "PyQt4._qt" to the includes. From carl.dhalluin at gmail.com Wed Sep 5 09:12:24 2007 From: carl.dhalluin at gmail.com (carl.dhalluin at gmail.com) Date: Wed, 05 Sep 2007 13:12:24 -0000 Subject: python exec behaves inconsistent with respect to module imports Message-ID: <1188997944.162811.33640@r34g2000hsd.googlegroups.com> Hello I am completely puzzled why the following exec code does not work: mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" def execute(): exec mycode execute() I get the error: root at devmachine1:/opt/qbase# python error1.py Traceback (most recent call last): File "error1.py", line 5, in ? execute() File "error1.py", line 4, in execute exec mycode File "", line 4, in ? File "", line 3, in f NameError: global name 'math' is not defined Note that the following code _does_ work: mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" exec mycode I have tested this in python 2.3 and 2.4. Regards Carl From khemkaamit at gmail.com Fri Sep 21 02:12:31 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Fri, 21 Sep 2007 11:42:31 +0530 Subject: global name is not defined - but this is actually a function's name In-Reply-To: <33dffc910709202259h699c04a3w111f0fa23966a59d@mail.gmail.com> References: <33dffc910709202259h699c04a3w111f0fa23966a59d@mail.gmail.com> Message-ID: <1360b7230709202312j48bd3b85x8729b6ff74fe90c7@mail.gmail.com> On 9/21/07, Mridula Ramesh wrote: > hi. > > i'm a beginner and i'm trying to get the hang of classes and functions. my > code looks like this: > > > > class showRecord(main): > def __init__(self): > global gmax > #now to create the screen by placing all the widgets > rt = Tk() > showbuttons() > #call the scroller to DoSomething > scroll() > > def showbuttons(self): > # NAVIGATION BAR------ > NavBut1 = Button(rt, text="|<", width=6, height=2, > bg="DarkSeaGreen", fg="Black") > NavBut1.grid(row=10, column=20, padx=6, pady=6, columnspan=3) > NavBut2 = Button(rt, text="<<", width=6, height=2, > bg="DarkSeaGreen", fg="Black") > NavBut2.grid (row=10, column=25, padx=6, pady=6, columnspan=3) > #widget bindings > NavBut2.bind('', lambda e:GoPrev(ctr)) > > > > my problem is at the 6th line: showbuttons() > the error says "global name "showbuttons" is not defined.... but it's not a > global variable. what am i doing wrong? use self.showbuttons() > also, should i say ... > > def showbuttons(self): This should work ! Cheers, -- ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in From __peter__ at web.de Wed Sep 12 05:37:15 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Sep 2007 11:37:15 +0200 Subject: function to do dynamic import? References: <13ecb84p1ghrd64@corp.supernews.com> <1189491152.601490.33880@o80g2000hse.googlegroups.com> <13eehnapt0r0jc2@corp.supernews.com> Message-ID: Am Wed, 12 Sep 2007 11:54:51 +1000 schrieb bambam: > def gim(): > exec "global gamel" > exec "import gamel" > > Unfortunately, does not have the desired effect. > Steve. Both statements have to be part of a single exec: def gim(): modulename = "gamel" # determined at runtime exec "global %s; import %s" % (modulename, modulename) It may work, but it is still a bad idea to create global variables with a name not known until runtime. Peter From wizzardx at gmail.com Fri Sep 21 16:16:36 2007 From: wizzardx at gmail.com (David) Date: Fri, 21 Sep 2007 22:16:36 +0200 Subject: executing list of methods (and collecting results) In-Reply-To: <46F301B6.10801@fmed.uba.ar> References: <46F301B6.10801@fmed.uba.ar> Message-ID: <18c1e6480709211316m4a6b23fdob6623d278bf70baf@mail.gmail.com> > I wondering if is this a good pattern to apply, i like the way it looks > like, at least to me it looks `natural', but...im calling every method > twice here? One in v_dict and again on the dict iteration? > > Any suggestion will be great! Another suggestion is to use a naming convention for your validators. Then you don't need a separate dict that lists them. Just run through your module or class dict and process each method/function whose name starts with a certain pattern. You can also cache the names the first time round so you don't have to match string patterns every time that collect_validators() runs. From ivonet at gmail.com Fri Sep 21 15:56:47 2007 From: ivonet at gmail.com (Ivo) Date: Fri, 21 Sep 2007 21:56:47 +0200 Subject: elementtree question In-Reply-To: References: Message-ID: <46f4211c$0$3030$e4fe514c@dreader31.news.xs4all.nl> Tim Arnold wrote: > Hi, I'm using elementtree and elementtidy to work with some HTML files. For > some of these files I need to enclose the body content in a new div tag, > like this: > >
> original contents... >
> > > I figure there must be a way to do it by creating a 'div' SubElement to the > 'body' tag and somehow copying the rest of the tree under that SubElement, > but it's beyond my comprehension. > > How can I accomplish this? > (I know I could put the class on the body tag itself, but that won't satisfy > the powers-that-be). > > thanks, > --Tim Arnold > > You could also try something like this: from sgmllib import SGMLParser class IParse(SGMLParser): def __init__(self, verbose=0): SGMLParser.__init__(self, verbose) self.data = "" def _attr_to_str(self, attrs): return ' '.join(['%s="%s"' % a for a in attrs]) def start_body(self, attrs): self.data += "" % self._attr_to_str(attrs) print "remapping" self.data += '''
''' def end_body(self): self.data += "
" # end remapping self.data += "" def handle_data(self, data): self.data += data def unknown_starttag(self, tag, attrs): self.data+="<%s %s>" % (tag, self._attr_to_str(attrs),) def unknown_endtag(self, tag): self.data += "" % tag if __name__=="__main__": i = IParse() i.feed(''' original italic contents... '''); print i.data i.close() just look at the code from sgmllib (standard lib) and it is very easy to make a parser. for some much needed refactoring From gnewsg at gmail.com Mon Sep 17 14:13:23 2007 From: gnewsg at gmail.com (=?iso-8859-1?q?Giampaolo_Rodol=E0?=) Date: Mon, 17 Sep 2007 11:13:23 -0700 Subject: ANN: Python FTP Server library (pyftpdlib) 0.2.0 released Message-ID: <1190052803.192708.77410@n39g2000hsh.googlegroups.com> Hi, I'm pleased to announce release 0.2.0 of Python FTP Server library (pyftpdlib). http://code.google.com/p/pyftpdlib/ === About === Python FTP server library provides an high-level portable interface to easily write asynchronous FTP servers with Python. Based on asyncore framework pyftpdlib is actually the most complete RFC959 FTP server implementation available for Python programming language. === Major changes === * Support for FXP, site-to-site transfers. * NAT/Firewall support with PASV (passive) mode connections. * Configurable range of ports to use for passive data transfers. * Per-user messages configurability. * Maximum connections limit. * Per-source-IP limits. * Maximum login attempts limit. A complete list of changes including enhancements and bug fixes is available here: http://code.google.com/p/pyftpdlib/wiki/ReleaseNotes02 === More links: === * Source tarball: http://pyftpdlib.googlecode.com/files/pyftpdlib_0.2.0.tar.gz * Online docs: http://code.google.com/p/pyftpdlib/wiki/Tutorial * FAQs: http://code.google.com/p/pyftpdlib/wiki/FAQ * Roadmap: http://code.google.com/p/pyftpdlib/wiki/Roadmap * Issue tracker: http://code.google.com/p/pyftpdlib/issues/list Thanks, -- Giampaolo Rodola' < g.rodola [at] gmail [dot] com > From fakeaddress at nowhere.org Tue Sep 25 04:57:59 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 25 Sep 2007 01:57:59 -0700 Subject: Google and Python In-Reply-To: <1i4xorh.j5nc9k3y60vqN%aleax@mac.com> References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> <1i4rfyx.8vuc2j14j596uN%aleax@mac.com> <1i4xorh.j5nc9k3y60vqN%aleax@mac.com> Message-ID: <344Ki.547$ua4.285@newssvr22.news.prodigy.net> Alex Martelli wrote: > Bryan Olson wrote: > ... >>> YouTube (one of Google's most valuable properties) is essentially >>> all-Python (except for open-source infrastructure components such as >>> lighttpd). Also, at Google I'm specifically "Uber Tech Lead, Production >>> Systems": while I can't discuss details, my main responsibilities relate >>> to various software projects that are part of our "deep infrastructure", >>> and our general philosophy there is "Python where we can, C++ where we >>> must". >> Good motto. So is most of Google's code base now in >> Python? About what is the ratio of Python code to C++ >> code? Of course lines of code is kine of a bogus measure. >> Of all those cycles Google executes, about what portion >> are executed by a Python interpreter? > > I don't have those numbers at hand, and if I did they would be > confidential: you know that Google doesn't release many numbers at all > about its operations, most particularly not about our production > infrastructure (not even, say, how many server we have, in how many data > centers, with what bandwidth, and so on). > > Still, I wouldn't say that "most" of our codebase is in Python: Can you see how that motto, "Python where we can, C++ where we must," might lead people to a false impression of how much Google uses Python versus C++, especially on "production systems"? I tried to Google-up that motto; your post seems to be Google's first disclosure of it. [...] > To me, on the contrary, it seems > self-evident that if a company X enjoys great success employing > technique Y, this *DOES* make something of a case for another company Z > to seriously consider and probably try out Y, when attempting tasks > analogous to those X has had success with, to see if some of the success > could not be replicable in Z's own similar tasks. Similar tasks to what made Google a great success? I'm not seeing many of those. People seem to think they should duplicate the way Google does things, but without deep understanding of how and why they work for Google. An impossible task, because it's about the most un-Googley thing anyone could do. > This is the heart of > "benchmarking" and "industry best practices" -- and why many companies > in the role of X aren't all that forthcoming about publicizing all the > details of their Y's, just in case Z's endeavours should put Z in > competition with X (this always needs to be balanced with the many > _advantages_ connected to publicizing some of those Y's, of course). In the case of Google, there's way, way too much hidden for people to reason based on what Google does. In this thread, did you notice how far wrong people went about how Google's stuff works? > Such empirical support, while of course far from infallible (one will > always have to take into consideration many details, and the devil is in > the details), tends to perform vastly better in supporting decision > making than purely abstract considerations bereft of any such empirical > underpinnings. Wikipedia is in PHP, Slashdot in Perl, Basecamp in Ruby. They all rock, but more importantly, we can look under the hood. If Wikipedia makes a weaker case for PHP than Google for Python, it's largely because the whole story is never as neat as a trickle of selective disclosures. -- --Bryan From david at boddie.org.uk Wed Sep 26 18:53:04 2007 From: david at boddie.org.uk (David Boddie) Date: Thu, 27 Sep 2007 00:53:04 +0200 Subject: Script to extract text from PDF files Message-ID: <200709270053.05491.david@boddie.org.uk> On Wed Sep 26 23:50:16 CEST 2007, byte8bits wrote: > On Sep 26, 4:49 pm, Svenn Are Bjerkem > wrote: > > > I have downloaded this package and installed it and found that the > > text-extraction is more or less useless. Looking into the code and > > comparing with the PDF spec show a very early implementation of text > > extraction. Luckily it is possible to overwrite the textextraction > > method in the base class without having to fiddle with the original > > code. I tried to contact the developer to offer some help on > > implementing text extraction, but he didn't answer my emails. That's disappointing to hear, but it's understandable. I must have one or two outstanding requests to add features to pdftools from a year ago. I keep meaning to look into making the necessary changes, but it's not something I'm looking forward to. > Well, feel free to send any ideas or help to me! It seems simple... Do > a binary read. Find 'stream' and 'endstream' sections. > zlib.decompress() all the streams. Assuming that they're FlateEncoded... > Find BT and ET markers (Begin Text > & End Text) and finally locate the parens within those and string the > text together. Which works fine if the generator put in space characters. Otherwise, it seems to me that you need to figure out where any spaces should go. > This works great on 3 out of 10 PDF documents, but my > main issue seems to be the zlib compressed streams. Some of them don't > seem to be FlateDecodeable (although they claim to be) or the header > is somehow incorrect. But, once I get a good stream and decompress it, > things are OK from that point on. Seriously, if you have ideas, please > let me know. I'll be glad to share what I've got so far. You need to take a good parser and work on a higher level text extraction library. > Not many people seem to be interested. I'll stop adding to this > thread... I don't want to beat a dead horse. Anyone interested in > helping, can contact me via emial. On the contrary, lots of people are interested in this sort of thing: http://phaseit.net/claird/comp.text.pdf/PDF_converters.html http://sourceforge.net/projects/pdfplayground http://www.adaptive-enterprises.com.au/~d/software/pdffile/ http://pybrary.net/pyPdf/ http://www.boddie.org.uk/david/Projects/Python/pdftools/ I discussed working with the author of pdfplayground, but things never really got going. I'd like to be part of a team working on a PDF library for Python, but my views on software licensing mean that I'd prefer to use a strong copyleft license rather than the permissive licenses found attached to most of the above libraries. David From aleax at mac.com Sun Sep 2 13:13:06 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 2 Sep 2007 10:13:06 -0700 Subject: Google spreadsheets References: <1188564051.726895.288860@y42g2000hsy.googlegroups.com> <1188578994.210244.70800@i13g2000prf.googlegroups.com> Message-ID: <1i3t5mo.lopt711vavlbwN%aleax@mac.com> iapain wrote: > On Aug 31, 5:40 pm, Michele Simionato > wrote: > > I would like to upload a tab-separated file to a Google spreadsheet > > from Python. Does anybody > > have a recipe handy? TIA, > > > > Michele Simionato > > Probably its irrelevant to python. Use should see Google Spreadsheet > API and use it in your python application. > > http://code.google.com/apis/spreadsheets/ For Python-specific use, you probably want to get the Python version of the GData client libraries, ; an example of using it with a spreadsheet is at . Alex From mail at microcorp.co.za Wed Sep 26 02:59:17 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 26 Sep 2007 08:59:17 +0200 Subject: Google and Python References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com><1190231094.276099.136250@22g2000hsm.googlegroups.com><1190235678.019823.315850@o80g2000hse.googlegroups.com><7xejgr68pm.fsf@ruckus.brouhaha.com> <7xps07w5g3.fsf@ruckus.brouhaha.com> Message-ID: <011301c8000d$0778ef00$03000080@hendrik> "Paul Rubin" wrote: > "Hendrik van Rooyen" writes: > > What is the advantage of passing the open file rather than just the > > fully qualified file name and having the other process open the > > file itself? > > The idea is that the application is a web server. The socket listener > accepts connections and hands them off to other processes. That is, > the file descriptors are handles on network connections that were > opened by the remote client, not disk files that can be opened > locally. Ok got it - so instead of starting a thread, as is current practice, you fork a process (possibly on another machine) and "hand over" the client. Can't you do this by passing the client's IP addy and the negotiated socket on the clients machine? Or is this where the heavy lifting comes in? - "spoofing" the original local IP addy on the new server? - seems you would have to route to a local machine based not on IP addy only, but on (IP,socket) tuples. - This might work if you have only one entry point to the local LAN, but would be harder to do if there are two points of entry, and packets could hit from outside on either.. Might be easier to redirect the browser than to try to do this. - Hendrik From rschroev_nospam_ml at fastmail.fm Sun Sep 16 11:46:09 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 16 Sep 2007 15:46:09 GMT Subject: Cannot formulate regex In-Reply-To: References: Message-ID: <5dcHi.108404$Y95.5768344@phobos.telenet-ops.be> Dotan Cohen schreef: > I'd like to filter spam from a certain company. Here are examples of > strings found in their spam: > Mega Dik > Mega D1k > MegaDik > Mega. Dik > M eg ad ik > M E _G_A_D_ IK > M_E_G. ADI. K > > I figured that this regex would match all but the second example, yet > it matches none: > |[^a-z]m[^a-z]e[^a-z]g[^a-z]a[^a-z]d[^a-z]i[^a-z]k[^a-z]|i > > What would be the regex that matches "megadik" regardless of whatever > characters are sprinkled throughout? m[^a-z]*e[^a-z]*g[^a-z]*a[^a-z]*d[^a-z]*i[^a-z]*k FYI Kodos (http://kodos.sourceforge.net/) can be very useful for developing, testing and debugging such regexes. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From mrkafk at gmail.com Sun Sep 30 15:16:30 2007 From: mrkafk at gmail.com (mrkafk at gmail.com) Date: Sun, 30 Sep 2007 12:16:30 -0700 Subject: s.split() on multiple separators In-Reply-To: References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> Message-ID: <1191179790.181227.323480@k79g2000hse.googlegroups.com> > > c=' abcde abc cba fdsa bcd '.split() > > dels='ce ' > > for j in dels: > > cp=[] > > for i in xrange(0,len(c)-1): > > The "-1" looks like a bug; remember in Python 'stop' bounds > are exclusive. The indexes of c are simply xrange(len(c)). Yep. Just found it out, though this seems a bit counterintuitive to me, even if it makes for more elegant code: I forgot about the high stop bound. >From my POV, if I want sequence from here to there, it should include both here and there. I do understand the consequences of making high bound exclusive, which is more elegant code: xrange(len(c)). But it does seem a bit illogical... > print re.split('[ce ]', c) Yes, that does the job. Thanks. Regards, Marcin From horpner at yahoo.com Wed Sep 19 08:58:48 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 19 Sep 2007 12:58:48 GMT Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <87abrkhtfp.fsf@mulj.homelinux.net> <871wcvzhvc.fsf@benfinney.id.au> <87odfz5dc3.fsf@mulj.homelinux.net> Message-ID: On 2007-09-19, Hrvoje Niksic wrote: > Ben Finney writes: > >> Hrvoje Niksic writes: >> >>> class X(Y): >>> def foo(self): >>> super(X, self).foo() >>> >>> ...there is in fact no guarantee that super() calls a superclass of >>> X. However, it is certainly guaranteed that it will call a superclass >>> of type(self). >> >> Not even that. It could call *any class in the inheritance >> hierarchy*, > > The inheritance hierarchiy is populated by the various (direct > and indirect) superclasses of type(self). > >> depending on how the MRO has resolved "next class". Even one that is >> neither an ancestor nor a descendant of X. > > My point exactly. superclass of X is not the same as > superclass of type(self). Super iterates over the latter, > where you expect the former. I can't blame a person for thinking that the call super(A, self) is taking the superclass of A. A is perhaps too prominently placed. -- Neil Cerutti From michele.simionato at gmail.com Sun Sep 2 01:46:39 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sun, 02 Sep 2007 05:46:39 -0000 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1188709535.459572.22130@r34g2000hsd.googlegroups.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> <1188709535.459572.22130@r34g2000hsd.googlegroups.com> Message-ID: <1188711999.430235.97520@y42g2000hsy.googlegroups.com> On Sep 2, 7:05 am, Russ wrote: > Someone please correct me if I am wrong, > but I think PEP adds only to the libraries. You are wrong, PEPs also add to the core language. Why don't you give a look at the PEP parade on python.org? Michele Simionato From deets at nospam.web.de Mon Sep 10 15:34:56 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Sep 2007 21:34:56 +0200 Subject: noob: reloading modified python file within Python Shell In-Reply-To: <1189450434.578698.286760@o80g2000hse.googlegroups.com> References: <1189450434.578698.286760@o80g2000hse.googlegroups.com> Message-ID: <5klkjgF4du6mU1@mid.uni-berlin.de> johnny schrieb: > from people.models import * > > Now I make changes to the models.py. How do I reload this module in > Python Shell? > reload(module) which works only with import people.models reload(people.models) Which is better anyway, as the from module import * syntax will create local names that won't be changed by the reload. Diez From m.n.summerfield at googlemail.com Wed Sep 26 10:24:17 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Wed, 26 Sep 2007 14:24:17 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190815180.945099.248670@n39g2000hsh.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <1190805297.182232.116830@50g2000hsm.googlegroups.com> <1190815180.945099.248670@n39g2000hsh.googlegroups.com> Message-ID: <1190816657.574437.80980@g4g2000hsf.googlegroups.com> On 26 Sep, 14:59, Paul Hankin wrote: > On Sep 26, 2:46 pm, Duncan Booth wrote: > > > Paul Hankin wrote: > > > More flexibly, keep a set of inserted keys that haven't yet been > > > included in the sorted list, and a set of deleted keys that haven't > > > yet been removed from the sorted list. The cache is invalid if either > > > of these sets are empty - and to make it valid you can choose what to > > > do based on the sizes of the two sets (and the sorted list). For > > > instance, if there's just been one insertion you're probably better > > > doing an insertion rather than a full resort. Of course, there's a few > > > nasty cases here but it's always possible to just throw away the > > > sorted list and reconstruct it from the dict keys when things get too > > > hairy (eg, the user deletes a key that's in the inserted-but-not-yet- > > > sorted set). > > > Yes that sounds good. Did you mean 'The cache is invalid if either of > > these sets is not empty'? > > Yes :) > > > If you delete a key which is in the inserted set you can simply delete > > it from the inserted set. > > No, in case it was already in the sorted list before the insert. You > have to remove it from the inserted set AND add it to the deleted set. > > -- > Paul Hankin So should Duncan's def __removekey(self, key): if key in self.__addkeys: del self.__addkeys[key] else: self.__delkeys.add(key) be changed to: def __removekey(self, key): if key in self.__addkeys: del self.__addkeys[key] self.__delkeys.add(key) ? (BTW I'm happy to put up a new version on PyPI, but I'm v. conscious of the fact that the key ideas and code have come from you and Duncan, so if either of you would like to adopt it, I will gladly step aside. I just want a sorteddict in Python, and I don't mind who does it:-) From ricaraoz at gmail.com Sat Sep 8 12:24:40 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 08 Sep 2007 13:24:40 -0300 Subject: creating really big lists In-Reply-To: <1189267181.964313.302520@g4g2000hsf.googlegroups.com> References: <874pi92tr4.fsf@mulj.homelinux.net> <1189057626.943757.210420@d55g2000hsg.googlegroups.com> <1189063849.118900.327540@22g2000hsm.googlegroups.com> <1189192606.119578.100820@r34g2000hsd.googlegroups.com> <1189267181.964313.302520@g4g2000hsf.googlegroups.com> Message-ID: <46E2CCC8.6040707@bigfoot.com> Dr Mephesto wrote: > On Sep 8, 3:33 am, "Gabriel Genellina" wrote: >> En Fri, 07 Sep 2007 16:16:46 -0300, Dr Mephesto >> escribi?: >> >>> hey, that defaultdict thing looks pretty cool... >>> whats the overhead like for using a dictionary in python? >> Dictionaries are heavily optimized in Python. Access time is O(1), >> adding/removing elements is amortized O(1) (that is, constant time unless >> it has to grow/shrink some internal structures.) >> >> -- >> Gabriel Genellina > > well, I want to (maybe) have a dictionary where the value is a list of > 5 lists. And I want to add a LOT of data to these lists. 10?s of > millions of pieces of data. Will this be a big problem? I can just try > it out in practice on monday too :) > > thanks > > targetList = myDict[someKey] # This takes normal dict access time for j in xrange(5) : for i in xrange(50000000) : # Add a LOT of data to targetList targetList[j].append(i) # This takes normal list access time From zzbbaadd at aol.com Fri Sep 28 14:04:39 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 11:04:39 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> <1190997769.002795.59450@57g2000hsv.googlegroups.com> <5m4qc2Fbbk19U1@mid.uni-berlin.de> <1191000394.828693.285210@k79g2000hse.googlegroups.com> Message-ID: <1191002679.569709.16870@22g2000hsm.googlegroups.com> On Sep 28, 10:57 am, Steve Holden wrote: > TheFlyingDutchman wrote: > > On Sep 28, 10:01 am, Marc 'BlackJack' Rintsch wrote: > >> On Fri, 28 Sep 2007 09:42:49 -0700, TheFlyingDutchman wrote: > >>> Which of the common languages have higher order functions and what is > >>> the syntax? > >> C, C++, Pascal, Perl, PHP, Ruby have them. And of course the functional > >> languages, most notably Lisp and Scheme as you asked for common languages. > > >> Don't know if C#'s delegates qualify. > > >> Ciao, > >> Marc 'BlackJack' Rintsch > > > What is the syntax of a higher order function in C, C++ and Pascal? > > This is like listening to a four-year-old torment its parents with > incessant questions. Do you *have* to ask every question that pops into > your mind? > In this case I asked it as part of the original question and it was ignored. I have programmed in C and C++ and a little Pascal many years ago. I don't remember anything about Higher Order Functions and would like to see exactly how you do it and to verify the contention. From hniksic at xemacs.org Wed Sep 12 10:41:08 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 12 Sep 2007 16:41:08 +0200 Subject: Dynamically removing methods in new-style classes References: <1189607295.676704.215210@r34g2000hsd.googlegroups.com> Message-ID: <87r6l4gd4r.fsf@mulj.homelinux.net> agupta0318 at gmail.com writes: > I am trying unsuccessfully to remove some methods from an instance, You can't remove the method from an instance because the method is stored in its class. > With the older python classes I could have done: > self.__class__.__dict__[''test1"] to achieve the desired result. self.__class__.test1 still works, doesn't it? Removing methods can be achieved the same way: >>> x=X() >>> class X(object): ... def blah(self): pass ... >>> x=X() >>> x.blah > >>> del type(x).blah >>> x.blah Traceback (most recent call last): File "", line 1, in AttributeError: 'X' object has no attribute 'blah' From xkenneth at gmail.com Tue Sep 4 15:18:23 2007 From: xkenneth at gmail.com (xkenneth) Date: Tue, 04 Sep 2007 19:18:23 -0000 Subject: Sort of an odd way to debug... Message-ID: <1188933503.704007.285590@22g2000hsm.googlegroups.com> All, Sorry for the vague topic, but I really didn't know how to describe what I want to do. I'd like to almost do a traceback of my code for debugging and I thought this would be a really cool way to do it if possible. What I'd like to do, is define a base class. This base class would have a function, that gets called every time another function is called (regardless of whether in the base class or a derived class), and prints the doc string of each function whenever it's called. I'd like to be able to do this without explicitly specifying the function inside all of the other functions of a base class or derived class. Here's what I think it would look like: class Base: __init__(self,debug=False): if debug: self.debug = debug def functionThatAlwaysGetsCalled(self): print self.__docstring__ class Derived(Base): """This function prints something""" def printSometing(something) #ghost function get's called here print something Output would be: This function prints something something Thanks for any help! From danfike at gmail.com Thu Sep 20 10:45:51 2007 From: danfike at gmail.com (danfike at gmail.com) Date: Thu, 20 Sep 2007 14:45:51 -0000 Subject: Building Python with VC8 on x64 Vista Message-ID: <1190299551.573204.322440@57g2000hsv.googlegroups.com> Hi all, So I'm working on a C++ application that will eventually embed or extend Python using Boost.Python, but I first need to get Python compiled correctly for my platform. I've got a Windows Vista 64-bit machine with a Core 2 processor, and I'm compiling with a VC8. I downloaded the Python 2.5.1 source from python.org, and I opened the Visual Studio solution file that was in the PCbuild8 directory. I created a new x64 platform and managed to successfully compile the 'pythoncore' and 'python' projects (both in Debug and Release configurations), resulting in working executables. (Aside: When launched, the python console says "Python 2.5.1 [MSC v.1400 64 bit (AMD64)] on win32" up top. Does that seem right?) So, this program I'm writing with Boost.Python (that worked correctly on x86 with home-built libraries) won't compile with these x64 libraries. I keep getting 'unresolved external symbols.' But, I'm certain I'm linking in the library correctly. Here's a snippet from the output (with /verbose:lib) when compiling: 1>Searching libraries 1> 1> Searching ..\..\..\3rdParty\boost_1_34_0\lib_x64\libboost_python- vc80-mt-gy-1_34.lib: 1> 1> Searching ..\..\..\3rdParty\Python25\libs_x64\python25_d.lib: 1>Finished searching libraries 1>py_dyn_test.obj : error LNK2001: unresolved external symbol _Py_NoneStruct 1>vector_py.obj : error LNK2001: unresolved external symbol _Py_NoneStruct 1>volume_py.obj : error LNK2001: unresolved external symbol _Py_NoneStruct 1>py_dyn_test.obj : error LNK2001: unresolved external symbol _Py_RefTotal 1>vector_py.obj : error LNK2001: unresolved external symbol _Py_RefTotal 1>volume_py.obj : error LNK2001: unresolved external symbol _Py_RefTotal 1>volume_py.obj : error LNK2001: unresolved external symbol PyExc_IndexError If I switch to the Release configuration, I see fewer errors: 1>py_dyn_test.obj : error LNK2001: unresolved external symbol _Py_NoneStruct 1>volume_py.obj : error LNK2001: unresolved external symbol PyExc_IndexError Note that none of my own code is Debug-specific. Also, the code in my files is correct, because (as stated above), it worked fine for x86. Though I don't know how useful it is, I did open the python libraries in wordpad, and though most of the file wasn't legible, I did find strings "Py_NoneStruct," "Py_RefTotal," and "PyExc_IndexError." I suspect that I set up my "x64" platform configuration incorrectly, or missed something. It's basically the same as the Win32 configuration, except with the /MACHINE:X64 flag instead of / MACHINE:X86. One of the things I'm noticing just now, as I post this, is that the preprocessor flag "WIN32" is still defined in the x64 configuration. Maybe if I change that to "WIN64," I'll have better luck. Any advice you have on what the "correct" way to do this is would be appreciated. -Dan From software at ginstrom.com Wed Sep 12 19:06:06 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Thu, 13 Sep 2007 08:06:06 +0900 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189634093.644036.40780@r29g2000hsg.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com><13efndlln9n9659@corp.supernews.com> <1189634093.644036.40780@r29g2000hsg.googlegroups.com> Message-ID: <053b01c7f591$7fe4e9c0$0203a8c0@MOUSE> > On Behalf Of madzientist > As a newbie to Python (and OOP), I would love to hear what > people think of Steven's suggestion below. Is there a reason > why classes would be useful for the OP's question ? If you > can point me to a brief online tutorial addressing this, I > would happily go there to read it too :) In general, you should use classes when you need to maintain state. The classic example is a BankAccount class, each instance of which maintains a "balance" state. When you don't need to maintain state, module-level functions are fine. In fact, for testability/reliability, they're preferred, because when a method twiddles some internal state, it's much harder to test. It's valuable to have a function that always gives output x for input y, with no side effects. That (to me) is the appeal of the functional programming style. Regards, Ryan Ginstrom From grante at visi.com Mon Sep 3 11:31:01 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 03 Sep 2007 15:31:01 -0000 Subject: Looking for Delaunay triangulation module... References: <13dge9m2339ka68@corp.supernews.com> Message-ID: <13doa5l2r5dmg2b@corp.supernews.com> On 2007-09-02, Robert Kern wrote: >> Can anybody point me to a Delaunay triangulation module (for >> Win32)? I'm currently using http://flub.stuffwillmade.org/delny/ >> under Linux, but I have been unable to find a build for >> Windows. I don't have the tools (or skills) to build libqhull >> and Pythion extensions on Win32). >> >> I've also found the delaunay module in scipy's "sandbox". I >> could never get that module to work under Linux, and I can't >> build it for Windows anyway. > > I'm working on it today. I'm going to break it out into a > separate package. If you can remember what problems you had, > I'd like to fix them. I'm clearing up a number of (really > dumb) memory leaks. I'm sorry I don't remember what the problems were. It was some time ago (probably 14-16 months) when I was trying to use the module. After spending a day or two on it, I switched to the Delny module (which I had used in the past). I do have Dlaunay triangulation working using VTK (which is included in Enthought Python), but I haven't been able to figure out how to extract the triangle list from the object containing the resulting triangulation. The object method that people on the VTK mailing list tell me to call isn't available in the Python binding. -- Grant Edwards grante Yow! .. does your DRESSING at ROOM have enough ASPARAGUS? visi.com From python at cx.hu Wed Sep 5 21:07:20 2007 From: python at cx.hu (Ferenczi Viktor) Date: Thu, 6 Sep 2007 03:07:20 +0200 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? In-Reply-To: References: <46DEFD2E.5050205@sbcglobal.net> <200709060128.03248.python@cx.hu> Message-ID: <200709060307.21071.python@cx.hu> > > AFAIK there is no such a thing as "intentionally ugly" in the Python > > language. I've never read this sentence before in manuals, tutorials, > > etc. > > Perhaps not, but ... > > http://mail.python.org/pipermail/python-dev/2005-September/056846.html > WOW, thats true! :-D (AFAIK these creations are rather complicated than just plain ugly.) Thanks for your comment. Viktor From jstroud at mbi.ucla.edu Fri Sep 28 23:13:17 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 28 Sep 2007 20:13:17 -0700 Subject: python 2.5 and 3gb switch In-Reply-To: References: Message-ID: neil wrote: > Hello group, > > I have a question I hope someone knowledgeable here might assist me with :o) > > I am working on a python exporter to get a scene out of Blender and into a > renderer called Indigo. I hope you at least have heard of open source > Blender.. > The scene is very large requiring me to use a 3gb switch enabled version of > Blender and of course boot into a 3gb XP. > Unfortunately it seems that the limitation is now that python wont handle > the mission I pass to it. > I am wondering if there is any build of python available that is 3gb aware? > ( if that is indeed the issue) > I see python is not really there for 64 bit yet but most of the people > wanting to use this exporter will have 32 bit anyway. > > Any assistance is appreciated > regards > Neil > > Please post the relevant code and error messages. James From bignose+hates-spam at benfinney.id.au Sat Sep 29 19:58:03 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 30 Sep 2007 09:58:03 +1000 Subject: getopt with negative numbers? References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <1190915197.390247.313590@57g2000hsv.googlegroups.com> <1190930134.780005.68510@22g2000hsm.googlegroups.com> <1190944143.521085.66910@g4g2000hsf.googlegroups.com> <871wcj4ib9.fsf@benfinney.id.au> <1190999036.588941.165610@g4g2000hsf.googlegroups.com> <87odfm3021.fsf@benfinney.id.au> <1191021322.905791.21300@r29g2000hsg.googlegroups.com> Message-ID: <87zlz510tw.fsf@benfinney.id.au> Carl Banks writes: > On Sep 28, 6:19 pm, Ben Finney > wrote: > > Steven Bethard writes: > > > A user shouldn't have to go out of their way to specify regular > > > numbers on the command line, regardless of whether they're > > > positive or negative. > > > > A user shouldn't have to go out of their way to know whether what > > they type on a command line will be treated as an option or an > > argument. > > I guess typing > ./program --help > > is out of the question. You're trying to have it both ways. You're saying the user "shouldn't have to go out of their way" to type arbitrary arguments on the command line. Then, in your next message, you suggest they must *read the detailed command-line help* in order to know whether they *can* type arbitrary command-line arguments. Is "learn about how the program expects options and arguments" within your definition of "go out of their way", or isn't it? If it's not, then "shouldn't have to go out of their way" is *not* an argument in favour of special-casing negative-numbers. -- \ "We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up." -- Phyllis Diller | Ben Finney From koutoo at hotmail.com Tue Sep 18 14:21:01 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Tue, 18 Sep 2007 11:21:01 -0700 Subject: Newbie question Message-ID: <1190139661.046103.45440@19g2000hsx.googlegroups.com> If I have a file name: AVC1030708.14. How do I strip out certain characters from the file name? I am so used to using MID, LEFT, and RIGHT functions, that I have no idea how to do this in python? I have had trouble as well with most newbies on finding the help. But I have used the command line built in help, but with no luck. Thanks. Kou From dieter at handshake.de Fri Sep 28 14:18:45 2007 From: dieter at handshake.de (Dieter Maurer) Date: Fri, 28 Sep 2007 20:18:45 +0200 Subject: [Zope] how do I test for the current item in an iteration In-Reply-To: <005b01c801e5$600ad3c0$0200a8c0@design4> References: <005b01c801e5$600ad3c0$0200a8c0@design4> Message-ID: <18173.17797.719591.185734@gargle.gargle.HOWL> kamal hamzat wrote at 2007-9-28 16:36 +0100: >I have this error after i added the if statement > >Error Type: TypeError >Error Value: mybrains.__cmp__(x,y) requires y to be a 'mybrains', not a 'int' > > >for i in context.zCatNewsCurrent(): > if i <= 5: > print "%s: %s: %s" % (i.id, i.author, i.summary) You are aware that you use "i" both as an integer ("i <= 5") as well as a structure ("i.id", "i.author", ...). Python is quite polymorph -- but there are some limits. Andreas suggestion was good: "enumerate" may help you... -- Dieter From sjmachin at lexicon.net Sat Sep 15 07:03:19 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Sep 2007 21:03:19 +1000 Subject: reading xls file from python In-Reply-To: References: <21903009.66741189806994236.JavaMail.www@wwinf4602> Message-ID: <46EBBBF7.8060003@lexicon.net> On 15/09/2007 1:50 PM, Gabriel Genellina wrote: > En Fri, 14 Sep 2007 18:56:34 -0300, escribi?: > >> I have installed python 2.5 for windows in my pc, I have a file xls >> say "file.xls" in c:/python25. How I can read this files from Python. >> Many thanks in advance. > > Try xlrd: http://www.python.org/pypi/xlrd In the interests of even-handedness: http://www.velocityreviews.com/forums/t352440-how-to-read-excel-files-in-python.html covers other possibilities. OT: A note for the OP: It is not a good idea to store your data files (example: file.xls) in the folder of some installed software (example: c:/python25). You may need to re-install the software and this may trash your data. Consider storing data files in folders whose names give some hint as to their contents. HTH, John From stefan.behnel-n05pAM at web.de Mon Sep 10 04:37:13 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 10 Sep 2007 10:37:13 +0200 Subject: Python syntax wart In-Reply-To: References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> <5ki2sdF3nr68U1@mid.individual.net> <5kk8p0F3vfqqU1@mid.uni-berlin.de> <5kkcmvF3vfqqU3@mid.uni-berlin.de> Message-ID: <46E50239.7050007@web.de> Lawrence D'Oliveiro wrote: > In message <5kkcmvF3vfqqU3 at mid.uni-berlin.de>, Marc 'BlackJack' Rintsch > wrote: >> And this is also easily written that way in Python if you don't insist on >> the line break after the ``if`` or can live with backslashes. > > Which is precisely the point. This actually sounds somewhat pointless to me. If complex things don't fit into one line, a good way to deal with it is not to insist on making them a single statement. Stefan From bignose+hates-spam at benfinney.id.au Thu Sep 20 00:52:50 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 20 Sep 2007 14:52:50 +1000 Subject: Mixin classes and single/multiple inheritance References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> <877immvye0.fsf_-_@benfinney.id.au> <1190257864.945639.199230@k79g2000hse.googlegroups.com> <87y7f2uhpp.fsf@benfinney.id.au> <1190262607.684957.49610@57g2000hsv.googlegroups.com> Message-ID: <87myviuee5.fsf@benfinney.id.au> Michele Simionato writes: > Since the language we have does have multiple inheritance, let's > use it to implement mixins. > ... > So, multiple inheritance is giving us very little for the point of > view of mixins; OTOH, multiple inheritance is giving us a lot of > headaches for what concerns cooperative methods. I may be obtuse, but the above statements seem to be professing contradictory viewpoints. Do you think multiple inheritance should or should not be used in Python to do what mixins do? > My point was that even if Python had been implemented without > multiple inheritance, it would have been simple to implement mixins, > or by copying the methods, or by dispatching with __getattr__. Can you give a code example of how you think mixins should be implemented in Python, assuming the absence of multiple inheritance? -- \ "The best way to get information on Usenet is not to ask a | `\ question, but to post the wrong information." -- Aahz | _o__) | Ben Finney From korovev76 at gmail.com Thu Sep 20 08:38:43 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Thu, 20 Sep 2007 05:38:43 -0700 Subject: I MEANT ONIX.... [it was Re: ONYX] In-Reply-To: <46f25191$0$29574$426a34cc@news.free.fr> References: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> <46f1726f$0$15276$426a74cc@news.free.fr> <1190282489.824709.29050@r29g2000hsg.googlegroups.com> <1190283378.175422.73290@r29g2000hsg.googlegroups.com> <46f25191$0$29574$426a34cc@news.free.fr> Message-ID: <1190291923.310128.156430@22g2000hsm.googlegroups.com> On 20 Set, 12:55, Bruno Desthuilliers wrote: > > First question : do you *really* need a validating parser ? > that's what they told me ("they" being "da boss")... I mean: i have to validate and to parse... i guess you can't do it at the same time, can you? > Second question : did you try to google for > "+Python +validating +XML +parser" I've already googled it, and found pyRXP... but I was looking for someone/something already experienced with onix... From mail at timgolden.me.uk Mon Sep 10 11:11:07 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 10 Sep 2007 16:11:07 +0100 Subject: shared memory pointer In-Reply-To: <1189436265.841415.234050@w3g2000hsg.googlegroups.com> References: <1189436265.841415.234050@w3g2000hsg.googlegroups.com> Message-ID: <46E55E8B.1040302@timgolden.me.uk> Tim wrote: > Hello Everyone, > > I am getting shared memory in python using the following. > > szName = c_char_p(name) > hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE, > None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName) > if (hMapObject == 0): > print "OpenKey: Could not open name file mapping object" > raise WinError() > > self.pData = windll.kernel32.MapViewOfFile(hMapObject, > FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE) Without answering your question directly, why not use the stdlib mmap module, which does exactly this for you behind the scenes? Docs - http://docs.python.org/lib/module-mmap.html Example - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413807 TJG From lac at openend.se Tue Sep 11 01:57:26 2007 From: lac at openend.se (Laura Creighton) Date: Tue, 11 Sep 2007 07:57:26 +0200 Subject: [PyCON-Organizers] Next PyCon Organizers' Meeting Tuesday, 11 September In-Reply-To: Message from "Douglas Napoleone" of "Mon, 10 Sep 2007 22:34:01 EDT." References: <46E5CFAB.8090802@python.org> <18149.64774.138831.976974@montanaro.dyndns.org> Message-ID: <200709110557.l8B5vQbm011421@theraft.openend.se> Does this mean that if you do not have a google account, and do not want one, there is no way to join the meeting? Laura In a message of Mon, 10 Sep 2007 22:34:01 EDT, "Douglas Napoleone" writes: >I have found that jabber accounts no longer work, but google accounts >do. I had a jabber account, but could never get it working in GAIM. My >google account works fine. > > -Doug > > >On 9/10/07, skip at pobox.com wrote: >> >> David> Connection details: >> David> http://wiki.python.org/moin/PyCon2008/OrganizersMeetingsConn >ectionDetails >> >> Ah, now I remember. GAIM complained: >> >> 400: Malformed Jabber ID >> >> GAIM recorded my Jabber ID as "skip.montanaro at jabber.org" which seems p >retty >> well-formed to me. >> >> Skip >> _______________________________________________ >> Pycon-organizers mailing list >> Pycon-organizers at python.org >> http://mail.python.org/mailman/listinfo/pycon-organizers >> >_______________________________________________ >Pycon-organizers mailing list >Pycon-organizers at python.org >http://mail.python.org/mailman/listinfo/pycon-organizers From bdesth.quelquechose at free.quelquepart.fr Wed Sep 19 15:54:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 21:54:48 +0200 Subject: lambda-funcs problem In-Reply-To: References: <1190201984.062329.182460@k79g2000hse.googlegroups.com> <06eb01c7fab5$0aa2bb50$0203a8c0@MOUSE> Message-ID: <46f17eaf$0$31727$426a34cc@news.free.fr> St?phane Larouche a ?crit : (snip) > > funcs = [(lambda i: lambda x: x+i)(i) for i in xrange(10)] A bit more complex than necessary... The canonical solution is funcs = [lambda x, i=i: x+i for i in xrange(10)] From llothar at web.de Tue Sep 4 22:20:21 2007 From: llothar at web.de (llothar) Date: Tue, 04 Sep 2007 19:20:21 -0700 Subject: Questions on FOX GUI and Python In-Reply-To: References: Message-ID: <1188958821.873330.102310@d55g2000hsg.googlegroups.com> On 5 Sep., 02:15, Kenneth McDonald wrote: > Would anyone care to offer their opinions as to using Python with the > FOX GUI toolkit? Ease of use, stability, power, > speed, etc., all thoughts would be appreciated. Pure theoretical question, as FXPy is not supported anymore, but i bite: Don't use FOX if you want to write a mainstream application. I did it and i whish i could find the time to switch to another toolkit. Too many problems and to many useability bugs. The later ones are getting more serious for me. Also development for the GUI part stalled and even before it was OpenSource but never OpenCommunity. And it is (if not patched) almost as ugly as the old TK. From duncan.booth at invalid.invalid Fri Sep 14 08:16:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Sep 2007 12:16:30 GMT Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> Message-ID: Piet van Oostrum wrote: >>>>>> Ben Finney (BF) wrote: > >>BF> The latter two statements are equivalent. The >>'instance.method(args)' BF> syntax is just sugar for >>'Class.method(instance, args)'. > > It is more than just syntactic sugar because the Class is derived from > the instance at runtime. Other differences that mean it isn't just sugar: you can save the bound method created by 'instance.method' but not with the expanded version. The equivalence depends on the type of 'method', other expansions are possible: e.g. Class.method(Class, args) or Class.method(args) or invent your own. From stefan.behnel-n05pAM at web.de Wed Sep 19 04:13:24 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 19 Sep 2007 10:13:24 +0200 Subject: Extracting xml from html In-Reply-To: <1190144020.294613.167800@57g2000hsv.googlegroups.com> References: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> <46EF769E.4080103@web.de> <1190144020.294613.167800@57g2000hsv.googlegroups.com> Message-ID: <46F0DA24.5030000@web.de> kyosohma at gmail.com wrote: > Does this make sense? It works pretty well, but I don't really > understand everything that I'm doing. > > def Parser(filename): It's uncommon to give a function a capitalised name, unless it's a factory function (which this isn't). > parser = etree.HTMLParser() > tree = etree.parse(r'path/to/nextpage.htm', parser) > xml_string = etree.tostring(tree) What you do here is parse the HTML page and serialise it back into an XML string. No need to do that - once it's a tree, you can work with it. lxml is a highly integrated set of tools, no matter if you use it for XML or HTML. > events = ("recordnum", "primaryowner", "customeraddress") You're not using this anywhere below, so I assume this is left-over code. > context = etree.iterparse(StringIO(xml_string), tag='') > for action, elem in context: > tag = elem.tag > if tag == 'primaryowner': > owner = elem.text > elif tag == 'customeraddress': > address = elem.text > else: > pass > > print 'Primary Owner: %s' % owner > print 'Address: %s' % address Admittedly, iterparse() doesn't currently support HTML (although this might become possible in lxml 2.0). You could do this more easily in a couple of ways. One is to use XPath: print [el.text for el in tree.xpath("//primaryowner|//customeraddress")] Note that this works directly on the tree that you retrieved right in the third line of your code. Another (and likely simpler) solution is to first find the "Row" element and then start from that: row = tree.find("//Row") print row.findtext("primaryowner") print row.findtext("customeraddress") See the lxml tutorial on this, as well as the documentation on XPath support and tree iteration: http://codespeak.net/lxml/xpathxslt.html#xpath http://codespeak.net/lxml/api.html#iteration Hope this helps, Stefan From cjw at sympatico.ca Sun Sep 16 10:17:18 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 16 Sep 2007 10:17:18 -0400 Subject: We need PIGs :) In-Reply-To: <5k9qpsF2mrncU3@mid.uni-berlin.de> References: <46d74472$0$402$426a34cc@news.free.fr> <87hcm81dot.fsf@kip.sateh.com> <5k9qpsF2mrncU3@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Thu, 06 Sep 2007 09:00:02 +0200, Stefan Arentz wrote: > >> What I find really frustrating in Python (combined with usually bad >> documentation) is that many people have different styles. The most >> frustratinng being getFoo() vs .foo, vs get_foo(). > > `getFoo()` is discouraged by PEP 8. You don't have the choice between > `.foo` and `.get_foo()` in Java because Java has no properties and people > are trained to write getters and setters for everything. I like that > choice in Python because I can write shorter code that is not cluttered > with very simple getters and setters. > > Ciao, > Marc 'BlackJack' Rintsch Perhaps PEP 8 needs rethinking. I prefer getFoo(). Similarly, I feel that the standard indent of 4 increases the likelihood of running off the end of a line. An indent of 1 isn't quite clear visually, but 2 is. Colin W. From dotancohen at gmail.com Tue Sep 11 18:19:38 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 12 Sep 2007 01:19:38 +0300 Subject: Need a KDE app, where to find a coder? In-Reply-To: <5kmq00F4d2c9U2@mid.uni-berlin.de> References: <5kmq00F4d2c9U2@mid.uni-berlin.de> Message-ID: <880dece00709111519l66bb94d9v11f2a63bf611c18b@mail.gmail.com> On 11/09/2007, Diez B. Roggisch wrote: > Dotan Cohen schrieb: > > I need an application, and I'd like it to be written in Python with QT > > as I am a KDE user. I simply don't have the time to code it myself, as > > I've been trying to find the time for half a year now. > > > > What are some reputable websites for finding Python coders? If anyone > > on the list wants the job, this is what I need: > > > > I need a hierarchical list manager, similar to ListPro > > (http://www.iliumsoft.com/site/lp/listpro.htm) which is the app that > > I'm replacing. Specifically, I need the checkmark (boolen), item > > (string), date, amount (int/100), and notes fields. As KDE is moving > > to QT4 in December (with the release of KDE4) it would be best if the > > app were coded with this in mind. As the application is for my own > > personal use, I will try to maintain it with the little python that I > > know, but I may need help along the way. > > There are a few places to ask - like guru.com. > > But you most probably will have to make a financial offer. > > Apart from that - do you know basket? It's integrated into kontact, and > maybe does what you want. > > Diez Thanks, I will look at guru.com. I have tried Basket, and found that it is very difficult for me to use. It seems to cater to those who find presentation more important that data structure. It does have checkmark functions, but it is impossible to use in an efficient manner. Dotan Cohen http://what-is-what.com http://gibberish.co.il From lasses_weil at klapptsowieso.net Sun Sep 23 10:29:57 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 23 Sep 2007 16:29:57 +0200 Subject: building a GUI In-Reply-To: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> Message-ID: <46f67866$0$4534$9b4e6d93@newsspool3.arcor-online.net> yadin wrote: > if i were up to make a GUI chich are the advantages of choosing python > over matlab or java? > This question is WAY to broad to give sane advice. You might want to state your context, objectives and restrictions are. Since you brought up Matlab, I suspect you're going after a scientific problem, involving data entry and display. In that case I'd say you're pretty well off using Matlab, since, well, it specific purpose is just that (GUI-wise, I mean). /W From bj_666 at gmx.net Sat Sep 29 02:27:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Sep 2007 06:27:07 GMT Subject: C Source Code Generator For Test Cases References: <1191001738.456766.176050@n39g2000hsh.googlegroups.com> <5m51iuFbao07U1@mid.uni-berlin.de> <1191009469.736521.39210@k79g2000hse.googlegroups.com> Message-ID: <5m69hrFbre38U1@mid.uni-berlin.de> On Fri, 28 Sep 2007 12:57:49 -0700, gamename wrote: >> How about using c-types to access your C-stuff to test, and use python + the >> testcase-tables to invoke that? >> > > Sure, that's possible. But the source code for tests (once all the > parms are read) > still needs to be generated. Calling the lib from python or from C, > there still > needs to be a way to generate 100+ test routines. ;-) Instead of reading the testcase tables and generating source for test routines you simply can do the tests right away. Ciao, Marc 'BlackJack' Rintsch From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 26 05:41:00 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 26 Sep 2007 11:41:00 +0200 Subject: the address of list.append and list.append.__doc__ In-Reply-To: <1190796145.444227.191030@y42g2000hsy.googlegroups.com> References: <1190775258.351819.24930@22g2000hsm.googlegroups.com> <1190780557.879816.13800@d55g2000hsg.googlegroups.com> <46fa102d$0$26322$426a74cc@news.free.fr> <1190796145.444227.191030@y42g2000hsy.googlegroups.com> Message-ID: <46fa290d$0$21888$426a74cc@news.free.fr> HYRY a ?crit : >> There's no such thing as an "original method" - what's stored as an >> attribute of the class is a plain function. FWIW, you can get at this >> function quite easily - via the im_func attribute of the method. > > I know about im_func, but I tried the im_func attribute of append and > I get error: 'builtin_function_or_method' object has no attribute > 'im_func' Hmm, yes, of course. builtin C implementation here... (snip use case) From mensanator at aol.com Thu Sep 6 19:39:44 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 06 Sep 2007 16:39:44 -0700 Subject: Beginners Query - Simple counter problem In-Reply-To: References: <13e0g0id9rlmg71@corp.supernews.com> <1189102450.3376.17.camel@dot.uniqsys.com> Message-ID: <1189121984.384107.53410@22g2000hsm.googlegroups.com> On Sep 6, 1:44 pm, Carsten Haese wrote: > On Thu, 2007-09-06 at 11:24 -0700, Ian Clark wrote: > > Carsten Haese wrote: > > > def d6(count): > > > return sum(random.randint(1, 6) for die in range(count)) > > > My stab at it: > > > >>> def roll(times=1, sides=6): > > ... return random.randint(times, times*sides) > > That produces an entirely different probability distribution if times>1. > Consider times=2, sides=6. Your example will produce every number > between 2 and 12 uniformly with the same probability, 1 in 11. When > rolling two six-sided dice, the results are not evenly distributed. E.g. > the probability of getting a 2 is only 1 in 36, but the probability of > getting a 7 is 1 in 6. > > -- > Carsten Haesehttp://informixdb.sourceforge.net Why settle for a normal distribution? import random def devildice(dice): return sum([random.choice(die) for die in dice]) hist = {} for n in xrange(10000): the_key = devildice([[1,2,3,10,11,12],[4,5,6,7,8,9]]) if the_key in hist: hist[the_key] += 1 else: hist[the_key] = 1 hkey = hist.keys() m = max(hkey) n = min(hkey) histogram = [(i,hist.get(i,0)) for i in xrange(n,m+1)] for h in histogram: print '%3d %s' % (h[0],'*'*(h[1]/100)) ## 5 ** ## 6 ***** ## 7 ******** ## 8 ******** ## 9 ******** ## 10 ******* ## 11 ***** ## 12 ** ## 13 ## 14 ** ## 15 ****** ## 16 ******** ## 17 ******** ## 18 ******** ## 19 ******** ## 20 ***** ## 21 ** They're called Devil Dice because the mean is 13 even though you cannot roll a 13. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Sep 13 08:21:44 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 13 Sep 2007 14:21:44 +0200 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> Message-ID: <5ksoaoF5am8cU1@mid.individual.net> TheFlyingDutchman wrote: > I am not talking about how the implementation of a C++ or Java > compiler uses the this pointer/this reference internally. I am > talking about how an author describes in English the "this" > pointer/reference in their book on programming C++ or Java. Ah, okay. > I don't think you will find them saying that under the covers > "this" was passed to the method (if in fact it is). They just say > that it refers to the current object inside that object's method. Mh, in my book, there is (quickly translated from german): | Instance pointer (C++ only) | | The /this/ pointer is a feature of all non-static class methods. | Every non static method is extended internally by a /this/ | argument. To that argument the compiler passes a pointer to the | instance for which the method is being called. (Dirk Louis, C/C++-Kompendium, Markt&Technik-Verlag, 2000) And that's only from the pointer chapter. The OOP chapters are more detailed. And no, it's no book about compiler architecture, it's a compendium. > Here is a link to a tutorial where Sun is talking about the this > reference: > http://java.sun.com/docs/books/tutorial/java/javaOO/thiskey.html That's a tutorial for getting you started, no reference documentation or in-depth course. > I am referring to C++. If someone is trying to learn the language, > knowledge of the internal implemenation is counter-productive in > my opinion because it distracts from the details they need to > learn. In a language like C++ it is beneficial to know some inner workings -- in the same way like it's beneficial to know some inner workings of a computer if you want to use it. BTW, C is not for nothing called "portable assembler" :) > If they are experienced and want to learn about the internals to > potentially help them code in the most blazingingly fast manner > they ideally would just be reminded they are using C++ and not > some slower byte-code executed language where it could possibly > matter. ;) I don't know if it's just me, but I tend to understand stuff like virtual methods much better if I know *why* they exist, and not just *that* they do. That makes judging if and when I need them easier. Regards, Bj?rn -- BOFH excuse #192: runaway cat on system. From tjreedy at udel.edu Wed Sep 19 20:08:59 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Sep 2007 20:08:59 -0400 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com><1190164166.378500.155990@o80g2000hse.googlegroups.com> Message-ID: "Terry Reedy" wrote in message news:fcq352$u0a$1 at sea.gmane.org... | | "TheFlyingDutchman" wrote in message | news:1190164166.378500.155990 at o80g2000hse.googlegroups.com... | Since Guido wrote that, there have been put forth more ideas and interest | and promises of efforts to remove or revise the GIL or do other things to | make using multiple cores easier. (The later being the point of the | concern over GIL.) A few days ago, an undergraduate posted on the dev list that he just started an independent study project on removing the GIL. Maybe we'll get a report early next year. Guido also said that he is willing to make changes to the CPython internals to aid multiproccessor usage [as long, presumably, as it does not cut speed in half]. || How much faster/slower would Greg Stein's code be on today's || processors versus CPython running on the processors of the late || 1990's? | | Perhaps a bit faster, though processor speeds have not increased so much | the last couple of years. This assumes that comparing versions of 1.5 is still relevant. As far as I know, his patch has not been maintained to apply against current Python. This tells me that no one to date really wants to dump the GIL at the cost of half Python's speed. Of course not. The point of dumping the GIL is to use multiprocessors to get more speed! So with two cores and extra overhead, Stein-patched 1.5 would not even break even. Quad (and more) cores are a different matter. Hence, I think, the resurgence of interest. ||And if you decide to answer, please add a true/false response || to this statement - "CPython in the late 1990's ran too slow". | | False by late 1990's standards, True by today's standards ;-). So now this question for you: "CPython 2.5 runs too slow in 2007: true or false?" If you answer false, then there is no need for GIL removal. If you answer true, then cutting its speed for 90+% of people is bad. | Most people are not currently bothered by the GIL and would not want its | speed halved. And another question: why should such people spend time they do not have to make Python worse for themselves? Terry Jan Reedy From n.anand.k at gmail.com Tue Sep 25 06:30:05 2007 From: n.anand.k at gmail.com (Anand) Date: Tue, 25 Sep 2007 03:30:05 -0700 Subject: Inserting an element into existing xml file In-Reply-To: <46F8E0E2.3050602@web.de> References: <1190712485.761290.136570@50g2000hsm.googlegroups.com> <46F8E0E2.3050602@web.de> Message-ID: <1190716205.955284.220810@n39g2000hsh.googlegroups.com> On Sep 25, 3:20 pm, Stefan Behnel wrote: > Anand wrote: > > I'm new to Python. we are using python2.4. > > > I wanted to insert an element into an existing xml file. Can anyone > > help me with this? > > I've seen lxml and elementTree in python2.5 has some API's to insert > > into existing xml file. > > We cant use python 2.5 due to some limitations. So how can we do it in > > 2.4? > > Install lxml and read the tutorial. It should be easy to grasp, as the API is > very simple. > > http://codespeak.net/lxml/tutorial.htmlhttp://codespeak.net/lxml/tutorial.html#elements-are-lists > > It's compatible to ElementTree, which you can also install on Python 2.4 (it's > what later became part of Python 2.5). > > Stefan Hi Stefan, First of all thanks for your reply. I'm Afraid to say, I can't use lxml or elementTree as it requires many legal approvals and there is high chances of not getting it through. So Do you have any other method / idea just by using plain 2.4 to accomplish the task Cheers, Anand From istvan.albert at gmail.com Thu Sep 27 11:42:11 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 27 Sep 2007 15:42:11 -0000 Subject: setuptools without unexpected downloads In-Reply-To: <87ejgmklep.fsf@benfinney.id.au> References: <87ejgmklep.fsf@benfinney.id.au> Message-ID: <1190907731.511106.42610@o80g2000hse.googlegroups.com> On Sep 26, 2:09 am, Ben Finney wrote: > behaviour with a specific invocation of 'setup.py'. But how can I > disallow this from within the 'setup.py' program, so my users don't > have to be aware of this unexpected default behaviour? I don't have the answer for this, but I can tell you that I myself dislike the auto-download behavior and I wish it worked differently. I've given up on setuptools/easy-install altogether. It is most annoying to end up with half a dozen unexpected packages. The default behavior should be to pop a question with a list of packages that will be downloaded (and have a flag that bypasses this). And of course being able to turn off this feature from setup.py. i. From bbxx789_05ss at yahoo.com Mon Sep 17 09:21:32 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 17 Sep 2007 06:21:32 -0700 Subject: curses: x, y positioning In-Reply-To: References: <1189891633.622313.81850@r29g2000hsg.googlegroups.com> Message-ID: <1190035292.415363.22320@50g2000hsm.googlegroups.com> Hi, Thanks for the response. On Sep 16, 8:41 pm, Tim Roberts wrote: > Don't you want mvaddstr? > import curses def my_program(screen): while True: ch = screen.getch() if ch == ord("q"): break if ch <= 255: screen.mvaddstr(30, 10, "*%s*" % chr(ch)) screen.refresh() curses.wrapper(my_program) Traceback (most recent call last): File "2pythontest.py", line 13, in ? curses.wrapper(my_program) File "/Library/Frameworks/Python.framework/Versions/2.4//lib/ python2.4/curses/wrapper.py", line 44, in wrapper return func(stdscr, *args, **kwds) File "2pythontest.py", line 10, in my_program screen.mvaddstr(5, 5, "*%s*" % chr(ch)) AttributeError: mvaddstr > >(And remember that y comes first.) > -- >>I can't seem to get any y, x coordinates to work with curses. However, while changing things around, I discovered what is causing the error: the coordinate 30, 10 is off my screen. When I change the y, x coordinates to 5, 10, then the program executes as it should. However, now I am having a problem trying to set the color of the text that is output: import curses def my_program(screen): while True: ch = screen.getch() if ch == ord("q"): break if ch <= 255: output = "*%s*" % chr(ch) screen.addstr(5, 5, output, curses.COLOR_RED) screen.refresh() curses.wrapper(my_program) A strange thing is happening. The integer value of the constant curses.COLOR_RED is 1, and when I type in a character, 1 is getting added to the character's ascii code. For instance, if I type in an 'h', then an 'i' displays on the screen--and in white, not red. I did some testing and has_colors() returns True, but I still can't get the curses output to show up in red. The tutorial: Curses Programming with Python A.M. Kuchling, Eric S. Raymond says: To use color, you must call the start_color() function soon after calling initscr(), to initialize the default color set (the curses.wrapper.wrapper() function does this automatically). Once that's done, the has_colors() function returns TRUE if the terminal in use can actually display color. Another thing that is strange: that paragraph uses the syntax curses.wrapper.wrapper(). And the docs say this: -------- 6.17 curses.wrapper -- Terminal handler for curses programs New in version 1.6. This module supplies one function, wrapper()... -------- which implies that I should be using the syntax curses.wrapper.wrapper() in my code. But I get an error when I try it: Traceback (most recent call last): File "2pythontest.py", line 16, in ? curses.wrapper.wrapper(my_program) AttributeError: 'function' object has no attribute 'wrapper' I get the same error if add the import statement: import curses.wrapper I'm using an intel mac if that makes any difference. From steve at holdenweb.com Thu Sep 27 08:27:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 08:27:50 -0400 Subject: URGENT REQUIREMENT FOR PYTHON DEVELOPERS In-Reply-To: <20070926221048.CD77B1E4009@bag.python.org> References: <20070926221048.CD77B1E4009@bag.python.org> Message-ID: <46FBA1C6.4020308@holdenweb.com> Krishna: You might want to consider reading http://www.python.org/community/jobs/howto/ and submitting these jobs to the Job Board. It's free. regards Steve kishore at mindriver-it.com wrote: > HI > > > > THIS IS KRISHNA KISHORE FROM MindRiver. We have an Urgent requirement > for Python Developers who have 5-7 YRS of EXP. > > > > SKILLS :PYTHON AND C/C++ > > > > WORK LOCATION : BANGALROE > > > > PLEASE REVERT US WITH YOUR UPDATED PROFILES. > > > > Thanks & Regards, > > Kishore Seethanraju |Senior Associate-People Consulting| MindRiver > Information Technologies Pvt. Ltd. > Suite# 512, 4th Floor and Suite # 104, Ground Floor ,Oxford Towers, 139, > Airport Road, Bangalore 560 008| Tel: +91.80.3052.1600 |Direct: > +91.80.3057.5799| Mobile: + 91.9901 96 1696 | Fax: +91.80.3057.5797| > Email: kishore at mindriver-it.com | Web > www.mindriver-it.com > > Information transmitted by this-mail is proprietary to MindRiver and / > or its Customers and is intended for use only by the individual or > entity to which it is addressed, and may contain information that is > privileged, confidential or exempt from disclosure under applicable law. > If you are not the intended recipient or it appears that this mail has > been forwarded to you without proper authority, you are notified that > any use or dissemination of this information in any manner is strictly > prohibited. In such cases, please notify us immediately at the above > mentioned telephone number or email to services at mindriver-it.com > and delete this mail from your > records. We believe this email to be virus free but do not warrant that > this is the case and we will not accept liability for any losses arising > from any virus being transmitted unintentionally by us' > > > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From steve at REMOVE-THIS-cybersource.com.au Sun Sep 16 18:35:23 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 22:35:23 -0000 Subject: how to join array of integers? References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <13eos6ihf2mjg4a@corp.supernews.com> <87lkb6o4bx.fsf@rudin.co.uk> Message-ID: <13erbtbos7ld123@corp.supernews.com> On Sun, 16 Sep 2007 19:25:22 +0100, Paul Rudin wrote: >> The generator expression takes about twice as long to run, and in my >> opinion it is no more readable. So what's the advantage? > > If you do it with a decent size list they take more or less the same > time. Did you try it, or are you guessing? What do you call a decent size? > You'd presumably expect the generator to use less memory; which > might be an advantage if you have large lists. Unfortunately, Python doesn't make it as easy to measure memory use as it does to time snippets of code, so that's just a hypothetical. > Isn't it odd that the generator isn't faster, since the comprehension > presumably builds a list first and then iterates over it, whereas the > generator doesn't need to make a list? Who says it doesn't need to make a list? string.join() needs a sequence. -- Steven. From paul.hankin at gmail.com Thu Sep 20 18:46:53 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 20 Sep 2007 22:46:53 -0000 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190325588.608625.259800@q3g2000prf.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> Message-ID: <1190328413.226577.206740@k79g2000hse.googlegroups.com> On Sep 20, 10:59 pm, Python Maniac wrote: > I am new to Python however I would like some feedback from those who > know more about Python than I do at this time. > > def scrambleLine(line): > s = '' > for c in line: > s += chr(ord(c) | 0x80) > return s > > def descrambleLine(line): > s = '' > for c in line: > s += chr(ord(c) & 0x7f) > return s > ... Well, scrambleLine will remove line-endings, so when you're descrambling you'll be processing the entire file at once. This is particularly bad because of the way your functions work, adding a character at a time to s. Probably your easiest bet is to iterate over the file using read(N) for some small N rather than doing a line at a time. Something like: process_bytes = (descrambleLine, scrambleLine)[action] while 1: r = f.read(16) if not r: break ff.write(process_bytes(r)) In general, rather than building strings by starting with an empty string and repeatedly adding to it, you should use ''.join(...) For instance... def descrambleLine(line): return ''.join(chr(ord(c) & 0x7f) for c in line) def scrambleLine(line): return ''.join(chr(ord(c) | 0x80) for c in line) It's less code, more readable and faster! -- Paul Hankin From sjmachin at lexicon.net Sat Sep 15 09:07:47 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Sep 2007 06:07:47 -0700 Subject: regexp search on infinite string? In-Reply-To: <1189860966.073168.33840@50g2000hsm.googlegroups.com> References: <1189802940.518794.129130@r29g2000hsg.googlegroups.com> <1189860966.073168.33840@50g2000hsm.googlegroups.com> Message-ID: <1189861667.962508.76850@57g2000hsv.googlegroups.com> On Sep 15, 10:56 pm, Paddy wrote: > On Sep 14, 9:49 pm, Paddy wrote: > > > Lets say i have a generator running that generates successive > > characters of a 'string'>From what I know, if I want to do a regexp search for a pattern of > > > characters then I would have to 'freeze' the generator and pass the > > characters so far to re.search. > > It is expensive to create successive characters, but caching could be > > used for past characters. is it possible to wrap the generator in a > > class, possibly inheriting from string, that would allow the regexp > > searching of the string but without terminating the generator? In > > other words duck typing for the usual string object needed by > > re.search? > > > - Paddy. > > There seems to be no way of breaking into the re library accessing > characters from the string: > > >>> class S(str): > > ... def __getitem__(self, *a): > ... print "getitem:",a > ... return str.__getitem__(self, *a) > ... def __get__(self, *a): > ... print "get:",a > ... return str.__get__(self, *a) > ...>>> s = S('sdasd') > >>> m = re.search('as', s); m.span() > (2, 4) > >>> m = sre.search('as', s); m.span() > (2, 4) > >>> class A(array.array): > > ... def __getitem__(self, *a): > ... print "getitem:",a > ... return str.__getitem__(self, *a) > ... def __get__(self, *a): > ... print "get:",a > ... return str.__get__(self, *a) > ... > > >>> s = A('c','sdasd') > >>> m = re.search('as', s); m.span() > (2, 4) > >>> m = sre.search('as', s); m.span() > (2, 4) > > - Paddy. That would no doubt be because it either copies the input [we hope not] or more likely because it hands off the grunt work to a C module (_sre). Why do you want to "break into" it, anyway? From JohnRoth1 at jhrothjr.com Sat Sep 29 12:29:37 2007 From: JohnRoth1 at jhrothjr.com (John Roth) Date: Sat, 29 Sep 2007 09:29:37 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: Message-ID: <1191083377.191358.303320@d55g2000hsg.googlegroups.com> On Sep 27, 5:37 pm, Steve Holden wrote: > I wondered if a straw poll could get some idea of readers' thoughts > about when they will be migrating to 3.0 on, so I used the new widget on > Blogger to add a poll for that. > > I'd appreciate if if you would go to > > http://holdenweb.blogspot.com/ > > and register your vote on your intended migration timescale. > > Thanks! > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline I was thinking of starting work on converting Python FIT to 3.0, and then they posted PEP 3137. I think it's a real good idea, but it shows that 3.0a1 isn't ready for a conversion effort. http://www.python.org/dev/peps/pep-3137/ I'll look at it again in a year or so. John Roth From garyjefferson123 at yahoo.com Thu Sep 20 02:08:55 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: Thu, 20 Sep 2007 06:08:55 -0000 Subject: distutils, extensions, and missing headers Message-ID: <1190268535.052437.226240@v23g2000prn.googlegroups.com> My setup.py (with extension) seems to work great for build and install, but for bdist_rpm, compilation of the extension fails because some of the headers needed to build the extension aren't in the bdist tarball. I've tried adding a 'depends=[]' to the Extension definition with these header files present, but they still don't get put in the tarball. What's the key to getting headers or other [non-python] files included in a bdist? Thanks, Gary From khemkaamit at gmail.com Sat Sep 8 04:00:28 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Sat, 8 Sep 2007 13:30:28 +0530 Subject: Python and Cron In-Reply-To: References: Message-ID: <1360b7230709080100o5a6ff416oab913834785cb838@mail.gmail.com> On 9/8/07, Greg Lindstrom wrote: > # run client pricing at 0215 (p) Monday-Friday > 15 2 * * 1-5 cd /m01/edith/src && /usr/bin/python /m01/edith/src/driver.py > --paid-date yesterday --jobname professional >> > /m01/edith/stdout/ecomppo.stdout 2&>1 "2&>1", Is that a typo ? It should be "2>&1" . Are you *sure* that the cron job is running ? cheers, -- ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in From freesoftwareweb at gmail.com Sun Sep 23 15:44:18 2007 From: freesoftwareweb at gmail.com (freesoftwareweb at gmail.com) Date: Sun, 23 Sep 2007 19:44:18 -0000 Subject: Latest software downloads!!!!! Message-ID: <1190576658.923018.297350@k79g2000hse.googlegroups.com> http://freesoftwareupgrades.blogspot.com/ From knjaz0 at gmail.com Tue Sep 11 07:58:52 2007 From: knjaz0 at gmail.com (knjaz) Date: Tue, 11 Sep 2007 04:58:52 -0700 Subject: Car-ac-systems Message-ID: <1189511932.371621.112970@o80g2000hse.googlegroups.com> Here you can find everything you need to know about car air conditioning http://car-ac-systems.blogspot.com/ From jkrukoff at ltgc.com Tue Sep 4 12:27:47 2007 From: jkrukoff at ltgc.com (John Krukoff) Date: Tue, 4 Sep 2007 10:27:47 -0600 Subject: GC performance with lists In-Reply-To: <1188914819.723858.25000@d55g2000hsg.googlegroups.com> Message-ID: <002101c7ef10$8ca160d0$0201a8c0@naomi> > -----Original Message----- > From: python-list-bounces+jkrukoff=ltgc.com at python.org [mailto:python- > list-bounces+jkrukoff=ltgc.com at python.org] On Behalf Of jonas at mit.edu > Sent: Tuesday, September 04, 2007 8:07 AM > To: python-list at python.org > Subject: GC performance with lists > > While working on some python wrapping, I've run into some problems > where the GC seems to take an unreasonable amount of time to run. The > code below is a demonstration: > > import gc > #gc.disable() > > data = [] > for i in xrange(100000): > > shortdata = [] > for j in range(57): > mytuple = (j, i+1, i+2, i+3, i+4, i+5, i+6) > shortdata.append(mytuple) > data.extend(shortdata) > > print len(data) > > with gc disabled (the second line) the code runs in 15 seconds, with > it enabled it runs in 2:15, or ~9x slower. I expected some gc > overhead, but not an order of magnitude! Am I doing something > obviously wrong in the above code? > > Thanks, > ...Eric > > -- > http://mail.python.org/mailman/listinfo/python-list The only real optimization I see for this is moving the common subexpressions (i+1, i+2, etc...) out of the loop as previous poster suggested. Something that looks like this, maybe: data = [] append = data.append for i in xrange( 100000 ): shortdata = ( i+1, i+2, i+3, i+4, i+5, i+6 ) for j in range( 57 ): append( ( j, ) + shortdata ) That'll help a little, I just checked the docs to be sure, and collection is triggered by the number of allocations - number of deallocations going over a certain threshold (700 by default). You do realize just what a massive data structure you're building here, too, right? On my box, building this consumes about 750Mb of memory. You're doing a massive number of allocations to create it, too, approximately 40 million. So, if the gc gets called every 700 allocations, you're spending a lot of time in the gc, and it's got a huge amount of memory it's sweeping. It sounds to me like you're triggering worst case behaviour for the gc, and should either change the threshold values, or simply disable the gc before the loop and reenable it after. A single gc run at the end probably won't be so bad as all the intermediate ones, though my box has pretty severe issues doing anything after creating this data structure as it starts swapping to disc. My architechtural suggestion would be to refactor this as an iterator if at all possible, so as to avoid the massive allocation burden. --------- John Krukoff helot at comcast.net From zzbbaadd at aol.com Fri Sep 28 16:00:08 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 13:00:08 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <1191008702.579795.141180@r29g2000hsg.googlegroups.com> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> <1191008702.579795.141180@r29g2000hsg.googlegroups.com> Message-ID: <1191009608.985644.271160@50g2000hsm.googlegroups.com> On Sep 28, 12:45 pm, George Sakkis wrote: > On Sep 28, 3:29 pm, TheFlyingDutchman wrote: > > > One issue I have with this group and that I encountered many years ago > > in the Perl group is that there is no separate group > > comp.lang.python.beginner where you can ask questions without getting > > hit with RTFM! and the like. > > Which shows once again that you're trying to break the world record of > being wrong in as many sentences as possible: > > http://mail.python.org/mailman/listinfo/tutor > > You would do yourself (and others) a favor by migrating there for a > few weeks or months. > > George Being in a land where every nit can be picked, I am surprised that you offered up a mailing list when I was asking for a newsgroup. From martin at v.loewis.de Wed Sep 12 16:29:07 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 12 Sep 2007 22:29:07 +0200 Subject: pwdmodule.c In-Reply-To: <1189622437.459458.129390@57g2000hsv.googlegroups.com> References: <1189622437.459458.129390@57g2000hsv.googlegroups.com> Message-ID: <46E84C13.3000409@v.loewis.de> > Is pwdmodule.c supposed to be excluded for windows compilation? Yes, it is - it gives access to /etc/passwd. See PCbuild/*.vcproj for what files get compiled on Windows. Regards, Martin From gagsl-py2 at yahoo.com.ar Sat Sep 22 01:16:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 22 Sep 2007 02:16:56 -0300 Subject: Newbie completely confused References: <4437CC27-104E-4EE9-80DB-DCF36213B44F@gmail.com> Message-ID: En Fri, 21 Sep 2007 13:34:40 -0300, Jeroen Hegeman escribi?: > So the first time around the file gets read in in ~0.1 seconds, the > second time around it needs almost four seconds! As far as I can see > this is related to 'something in memory being copied around' since if > I replace the 'alternative 1' by the 'alternative 2', basically > making sure that my classes are not used, reading time the second > time around drops back to normal (= roughly what it is the first pass). > class ModerateClass: > def __init__(self): > return > def __del__(self): > pass > return > > class HugeClass: > def __init__(self,line): > self.clear() > self.input(line) > return > def __del__(self): > del self.B4v > return > def clear(self): > self.long_classes = {} > self.B4v={} > return Don't use __del__ unless it's absolutely necesary. ModerateClass.__del__ does nothing, but its mere existence does not allow the garbage collector to work efficiently. If you explicitey call clear() from HugeClass, you can avoid using __del__ too. And if B4v is not involved in cycles, clearing it is not even necesary. (BTW, all those return statements are redundant and useless) -- Gabriel Genellina From richie at entrian.com Thu Sep 13 11:03:48 2007 From: richie at entrian.com (Richie Hindle) Date: Thu, 13 Sep 2007 16:03:48 +0100 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: > [Amer] > #!/usr/bin/python > [...] On my home PC [...] > [Thu Sep 13 04:16:03 2007] [error] [client 0.0.0.0] (OS 2)The system > cannot find the file specified. That's because on your home PC Python is somewhere like C:\Python25\python.exe, not /usr/bin/python. Are you sure /usr/bin/python is correct for your hosting environment? -- Richie Hindle richie at entrian.com From jstroud at mbi.ucla.edu Fri Sep 14 00:19:07 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 13 Sep 2007 21:19:07 -0700 Subject: How to Start In-Reply-To: References: Message-ID: Michael R. Copeland wrote: > Yes, I could fire up the interactive mode and play with some > statements...but I consider that sort of thing for programming neophytes > or experimenting with specific issues. The interactive interpreter is *the fastest* way to learn, expert, novice, or somewhere in-between. Let me do a quick count of the number of instances I have running just on the machine I'm at right now...ok, only 1, but that's because I just switched over to a Mac at work and it doesn't support multiple desktops--yet. I basically test just about every idea I have in the interactive interpreter before I lay it down in a text file. First, I want to develop a > simple Windows application, and because of the plethora of "stuff" the > Python world offers, I don't know where to begin. Pseudocode (~ python code). > For example, what basic, easy-to-use interface might I start with to > build a simple text file parsing and analysis program? That is, I'd > like to start with a simple Windows shell that prompts for a file name, > processes it, and then displays some result. #! /usr/bin/env python def main(): file_name = prompt_for_name() result = process(file_name) display(result) def prompt_for_name(): [fill in here] [etc.] > I am certainly impressed with the apparent experience and openness of > the regular players here, but the discussions here (and in > c.l.p.announce) truly presume knowledge and experience with Python I > don't yet have. Yes, for even a very experienced programmer, entering > the Python world is very daunting - but I want to get started. > Please advise. TIA Here's your recipe: 1. begin coding until you hit a wall 2. read official tutorial until you figure out a solution 3. experiment in interactive interpreter 4. goto 1. I know this sounds obvious, but its the best way to jumpstart. James From garyjefferson123 at yahoo.com Fri Sep 21 10:50:24 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: Fri, 21 Sep 2007 14:50:24 -0000 Subject: calling extension's autoconf/make from distutils In-Reply-To: <1190349834.894931.128050@q3g2000prf.googlegroups.com> References: <1190349834.894931.128050@q3g2000prf.googlegroups.com> Message-ID: <1190386224.536371.136640@q3g2000prf.googlegroups.com> On Sep 20, 10:43 pm, Gary Jefferson wrote: > I've got a python extension that comes with its own standard autoconf/ > automake system, and I can "python setup.py build" just fine with it > as long as I have previously done "./configure" in that directory. > > However, 'python setup.py bdist_rpm' can't hope to have done './ > configure' first, as it untars and tries to build the extension there. > > Is there a hook for bdist_rpm (and friends) that will allow me to > insert a './configure' in the build process, sometime before it tries > to build the extension? > > Thanks, > Gary I ended up simply subclassing 'Extension' and having it os.system('./ configure') before proceeding. This isn't perfect, as it does the './configure' everytime, but it works. Gary From bborcic at gmail.com Mon Sep 3 13:30:45 2007 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 03 Sep 2007 19:30:45 +0200 Subject: So what exactly is a complex number? In-Reply-To: References: Message-ID: Lamonte Harris wrote: > Like in math where you put letters that represent numbers for place > holders to try to find the answer type complex numbers? > Not quite. Relating them to (plane) trigonometry is much closer to the mark. Complex numbers are like a subclass of real numbers that elegantly extends the usual arithmetic operations to provide access to trigonometric functions and related goodies. This then allows you to think of trigonometric problems as simple arithmetic problems. From jurian at oco.co.za Wed Sep 5 16:55:13 2007 From: jurian at oco.co.za (Jurian Botha) Date: Wed, 5 Sep 2007 13:55:13 -0700 (PDT) Subject: SSL Issue Message-ID: <12510772.post@talk.nabble.com> Sorry if this is a real dumb question, but I'm totally stumped. I'm trying to connect to a https url in order to do some xml-rpc method calls, but I'm getting the following error: Error Type: sslerror Error Value: (6, 'TLS/SSL connection has been closed') What could be causing this error, any clues would be greatly appreciated. Thanks -- View this message in context: http://www.nabble.com/SSL-Issue-tf4388062.html#a12510772 Sent from the Python - python-list mailing list archive at Nabble.com. From http Fri Sep 7 11:47:58 2007 From: http (Paul Rubin) Date: 07 Sep 2007 08:47:58 -0700 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> <7x3axq7a8a.fsf@ruckus.brouhaha.com> Message-ID: <7xodgejx3l.fsf@ruckus.brouhaha.com> Paul Rubin writes: > def unique_id(): > return os.urandom(10).encode('hex') Sorry, make that 32 or 40 instead of 10, if the number of id's is large, to make birthday collisions unlikely. If you don't want the id's to be that large, you can implement a Feistel cipher using md5 or sha as the round function pretty straightforwardly, then just feed successive integers through it. That also guarantees uniqueness, at least within one run of the program. I have some sample code around for that, let me know if you need it. From jgardner.jonathangardner.net at gmail.com Tue Sep 4 15:47:11 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Tue, 04 Sep 2007 19:47:11 -0000 Subject: REGULAR EXPRESSION In-Reply-To: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> References: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> Message-ID: <1188935231.472813.32530@k79g2000hse.googlegroups.com> On Sep 4, 6:32 am, AniNair wrote: > hi.. I am trying to match '+ %&/-' etc using regular expression in > expressions like 879+34343. I tried \W+ but it matches only in the > beginning of the string Plz help Thanking you in advance... You may want to read the page describing the regex syntax a little closer. http://docs.python.org/lib/re-syntax.html \W would match anything but \w. That is, it would match spaces and tabs as well as the weird characters. I don't think that's what you want. Also, don't forget to use raw strings. r"\W+" is preferred over "\W+". From michele.simionato at gmail.com Mon Sep 24 11:44:40 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 24 Sep 2007 15:44:40 -0000 Subject: Can a base class know if a method has been overridden? In-Reply-To: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> Message-ID: <1190648680.658816.150430@r29g2000hsg.googlegroups.com> On Sep 24, 5:23 pm, Ratko wrote: > Hi all, > > I was wondering if something like this is possible. Can a base class > somehow know if a certain method has been overridden by the subclass? > I appreciate any ideas. > Thanks, > > Ratko The first time I used Zope, I immediately had an issue of overriding a predefined methods without knowing it (there were 400+ methods inherited from dozens of base classes). So I wrote this utility: def check_if_I_am_overriding_names(): """Prints a message if we are overriding a name. Useful for framework beginners. Example in Zope: >> from OFS.Folder import Folder >> class MyFolder(OFS.Folder): .. check_if_I_am_overriding_names() .. id = 'pippo' .. AlreadyDefinedNameWarning: id """ def makecls(name, bases, dic): for nam, val in dic.iteritems(): if nam.endswith("__") or nam == "meta_types": # ignore redefinitions of special names # and redefinition of meta_types (for Zope code) continue any_base_has_name = [base for base in bases if hasattr(base, nam)] if any_base_has_name: print "AlreadyDefinedNameWarning: " + nam return type(name, bases, dic) f = sys._getframe(1) f.f_locals["__metaclass__"] = makecls Michele Simionato From duncan.booth at invalid.invalid Mon Sep 24 10:43:36 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Sep 2007 14:43:36 GMT Subject: Converting numbers to unicode charaters References: <1190641342.127770.115610@y42g2000hsy.googlegroups.com> Message-ID: Laurent Pointal wrote: > You may eventually use a more condensed expression and avoid n > concatenation of n chars using join, like this: > > >>> u''.join(unichr(int(x,16)) for x in ['42','72','61','64']) > u'Brad' Or even avoid the loop completely: >>> hexs = ['42', '72', '61', '64'] >>> u'\\x'.join(['']+hexs).decode('string-escape') 'Brad' (but for that to work you really do need to be sure that all the values are 2 characters). From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 18 10:46:27 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 16:46:27 +0200 Subject: Memory Problem In-Reply-To: References: <5la11gF71rf0U2@mid.uni-berlin.de> Message-ID: <46efe4bb$0$14248$426a74cc@news.free.fr> Christoph Scheit a ?crit : > On Tuesday 18 September 2007 15:10, Marc 'BlackJack' Rintsch wrote: >> On Tue, 18 Sep 2007 14:06:22 +0200, Christoph Scheit wrote: >>> Then the data is added to a table, which I use for the actual >>> Post-Processing. The table is actually a Class with several "Columns", >>> each column internally being represented by array. (snip) > I have to deal with several millions of data, actually I'm trying an example > with > 360 grid points and 10000 time steps, i.e. 3 600 000 entries (and each row > consits of 4 int and one float) Hem... My I suggest that you use a database then ? If you don't want to bother with a full-blown RDBMS, then have a look at SQLite - it's lightweight, works mostly fine and is a no-brainer to use. > Of course, the more keys the bigger is the dictionary, but is there a way to > evaluate the actual size of the dictionary? You can refer to the thread "creating really big lists" for a Q&D, raw approx of such an evaluation. But it's way too big anyway to even consider storing all this in ram. From Shawn at Milochik.com Wed Sep 5 10:27:08 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 5 Sep 2007 10:27:08 -0400 Subject: PythonAlley.com Message-ID: <2dc0c81b0709050727q7e56e99dnf8918e7d143d53a@mail.gmail.com> I bought the domain PythonAlley.com (and PerlAlley.com and RubyAlley.com) not too long ago. I had the inspiration to make some kind of community site thing, but never did get around to it. Does anyone have any ideas as to what a wonderful use for PythonAlley.com would be? I'd really like to do something with at least the Python site, since I love Python. Not too sure about the others -- maybe I'm make them wikis and open them up to the community. Maybe I should just sell them. Ideas? Thanks, Shawn From fakeaddress at nowhere.org Sat Sep 15 00:55:55 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Sep 2007 21:55:55 -0700 Subject: Possible suggestion for removing the GIL In-Reply-To: <1189657576.772108.136550@d55g2000hsg.googlegroups.com> References: <1189657576.772108.136550@d55g2000hsg.googlegroups.com> Message-ID: Prateek wrote: [...] > Mainly it revolves around dedicating one core for executing > synchronized code and doing context switches instead of acquiring/ > releasing locks. > > http://www.brainwavelive.com/blog/index.php?/archives/12-Suggestion-for-removing-the-Python-Global-Interpreter-Lock.html Context switches are generally more expensive than acquiring and release locks. Most systems' run-queues are protected by locks. The context switches at issue all involve the dedicated core, so I do not see any parallelism advantage. -- --Bryan From ldo at geek-central.gen.new_zealand Mon Sep 24 03:58:25 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 24 Sep 2007 19:58:25 +1200 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> Message-ID: In message <1190415741.380795.259050 at y42g2000hsy.googlegroups.com>, Cristian wrote: > I think it would make more sense to have beginners _know_ that functions > are like all other variables ... Functions are not variables. Though they are values, and can be held in variables. In Python, every name is a variable, and can be assigned to. From arkanes at gmail.com Fri Sep 28 12:05:10 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 28 Sep 2007 11:05:10 -0500 Subject: Python 3.0 migration plans? In-Reply-To: <1190993122.979034.305060@50g2000hsm.googlegroups.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> Message-ID: <4866bea60709280905l1c5a88f1q11516e4eeddba5b0@mail.gmail.com> On 9/28/07, TheFlyingDutchman wrote: > On Sep 28, 2:49 am, "Diez B. Roggisch" wrote: > > TheFlyingDutchman wrote: > > > > All serious languages are turing-complete. So can we put away with this > > non-sense argument right away, please? > > You said it was a most basic language feature. I still haven't heard > anything that leads me to believe that statement is correct. What > languages implemented decorators as a most basic language feature? > Python didn't have them for over a decade so it doesn't qualify. > Decorators are syntax sugar for higher order functions. Higher order functions are a both a basic and a fundamental language feature, and exist in many languages. The fact that you don't know this just proves, once again, that you like to talk more than you like to learn. From deets at nospam.web.de Tue Sep 18 11:09:36 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Sep 2007 17:09:36 +0200 Subject: Saving parameters between Python applications? References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> <1190060967.696332.113190@n39g2000hsh.googlegroups.com> <1190122569.509673.41420@57g2000hsv.googlegroups.com> Message-ID: <5la81hF6t0khU1@mid.uni-berlin.de> Stodge wrote: > os.path.expanduser isn't an option; I need each console/window to > maintain different values which I wouldn't get from saving to a user's > home directory. Unless I used a different file for each console/window > but that just gets me into the same situation I'm already in. I think > the only option is to set environment variables using another script. > I'm really surprised and disapponited by this. you can't do that either. It's the principle behind environment-vars that you can't alter the ones of your parent process. That's the reason why environment-changes must be done by using "source": # source my_script where my_script contains e.g. export FOO="bar" If you can have your user alter his/her .bashrc, you might consider creating a environtment-variable in there that the subsequent script invocations refer to. Like this: # .bashrc export SESSION= Then in the python-scripts you can use SESSION as a common prefix into /tmp-residual files or such thing. Diez From wolf_tracks at invalid.com Thu Sep 20 15:54:56 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 20 Sep 2007 19:54:56 GMT Subject: Python Imaging Library Handbook--Printing It? Message-ID: Is there a pdf file for this somewhere, or another type of file. It would be good to print the whole thing at once. Ah, I see there's a pdf for an earlier version. Apparently, nothing for 1.1.4. -- Wayne Watson (Nevada City, CA) Web Page: From ajaksu at gmail.com Fri Sep 7 15:27:45 2007 From: ajaksu at gmail.com (ajaksu) Date: Fri, 07 Sep 2007 19:27:45 -0000 Subject: Speed of Python In-Reply-To: References: <1189185542.798286.168880@50g2000hsm.googlegroups.com> Message-ID: <1189193265.845514.190500@y42g2000hsy.googlegroups.com> On Sep 7, 2:37 pm, "wang frank" wrote: > I am not familiar with python, so I just simply try to reproduce the same > code in python. Seems almost correct, but from what I guess of MatLab, George's suggestions make it a bit more fair. > If you think that my python script is not efficient, could you tell me how > to make it more efficient? In pure Python? No idea (besides using Roberto's and George's suggestions). If you allow for extensions, Istvan has the answer. If you allow compiling Python to C++ (using ShedSkin: http://shed-skin.blogspot.com/), here's a small report: ---------- ajaksu at Belkar:~/sandbox$ cat bench.py import math n = 1 def bench1(n): for i in range(n): for j in range(1000): m=j+1 z=math.log(m) z1=math.log(m+1) z2=math.log(m+2) z3=math.log(m+3) z4=math.log(m+4) z5=math.log(m+5) z6=math.log(m+6) z7=math.log(m+7) z8=math.log(m+8) z9=math.log(m+9) return z9 a = bench1(10) ajaksu at Belkar:~/sandbox$ ss -e bench.py *** SHED SKIN Python-to-C++ Compiler 0.0.22 *** Copyright 2005-2007 Mark Dufour; License GNU GPL version 2 (See LICENSE) (Please send bug reports here: mark.dufour at gmail.com) [iterative type analysis..] ** iterations: 2 templates: 44 [generating c++ code..] ajaksu at Belkar:~/sandbox$ make bench.so g++ -O3 -s -pipe -fomit-frame-pointer -I/home/ajaksu/shedskin-0.0.22/ lib -g -fPIC -I/usr/include/python2.5 -D__SS_BIND /home/ajaksu/ shedskin-0.0.22/lib/builtin.cpp /home/ajaksu/shedskin-0.0.22/lib/ math.cpp bench.cpp -lgc -shared -Xlinker -export-dynamic -lpython2.5 - o bench.so ajaksu at Belkar:~/sandbox$ mv bench.py pbench.py ajaksu at Belkar:~/sandbox$ ipython Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [...] In [1]: from pbench import bench1 as pbench1 In [2]: from bench import bench1 In [3]: %timeit a = bench1(10) 100 loops, best of 3: 10.2 ms per loop In [4]: %timeit a = pbench1(10) 10 loops, best of 3: 92.8 ms per loop ---------- I guess you'd also see nice improvements from Pyrex or Cython, Blitz and other tools. Check http://wiki.python.org/moin/PythonSpeed/PerformanceTips for the general ideas and http://scipy.org/PerformancePython for an insight on available tools that even compares their speeds to Matlab. And-if-you-run-more-benchmarks-please-do-post-them-ly yrs, Daniel From http Thu Sep 6 04:44:38 2007 From: http (Paul Rubin) Date: 06 Sep 2007 01:44:38 -0700 Subject: Autogenerate functions (array of lambdas) References: <1189067829.685339.50550@y42g2000hsy.googlegroups.com> Message-ID: <7xr6lc6v49.fsf@ruckus.brouhaha.com> Chris Johnson writes: > a = [lambda: i for i in range(10)] > print [f() for f in a] > results in: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] > rather than the hoped for: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The usual idiom is a = [lambda i=i: i for i in range(10)] That way i is not a free variable in the lambda. From bignose+hates-spam at benfinney.id.au Wed Sep 5 00:01:51 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 05 Sep 2007 14:01:51 +1000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <5jn9qgFdmbcU3@mid.uni-berlin.de> <1188886461.236237.168230@y42g2000hsy.googlegroups.com> Message-ID: <871wdd92vk.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > In message <1188886461.236237.168230 at y42g2000hsy.googlegroups.com>, > Jason wrote: > > > The reason why the exception is more Pythonic is that the return > > value is always a guaranteed good index into the list. > > How do you explain dict.get, then? I explain it by noting that list.index and dict.get serve totally different purposes. The former returns the index given a value; the latter returns a value given a key. There are many areas of poor symmetry in the language and libraries; it isn't particularly clever or difficult to find them if one looks. Doing so doesn't appear to illustrate any point I see relevant in this thread. -- \ "If you're a horse, and someone gets on you, and falls off, and | `\ then gets right back on you, I think you should buck him off | _o__) right away." -- Jack Handey | Ben Finney From gh at gregor-horvath.com Sun Sep 9 15:10:29 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Sun, 09 Sep 2007 21:10:29 +0200 Subject: Class design (information hiding) In-Reply-To: <1i44z4p.fbrtvc1qvlmitN%aleax@mac.com> References: <42d6c$46e138d3$547078de$10495@news.chello.at> <1i44z4p.fbrtvc1qvlmitN%aleax@mac.com> Message-ID: <9d017$46e44525$547078de$8339@news.chello.at> Alex Martelli schrieb: > > Why, thanks for the pointer -- I'm particularly proud of having written > """ > The only really workable way to develop large software projects, just as > the only really workable way to run a large business, is a state of > controlled chaos. > """ Yes, indeed a good saying. The problem is that we do not understand those complex systems, despite the fact that some megalomaniacal people think they do. Declaring a method as private, public or protected assumes that the author fully understands the uses of this class by other programmers or even himself later on. But if the software is complex enough, chances are good that he does *NOT* understand it fully at the time he writes "Protected". Programming means attempting. Attempt implies failure. Flexible systems that are built for easy correction are therefore superior. Greg From cjw at sympatico.ca Fri Sep 28 16:55:20 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 28 Sep 2007 16:55:20 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <46FD40A5.8030504@holdenweb.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> <1190997769.002795.59450@57g2000hsv.googlegroups.com> <5m4qc2Fbbk19U1@mid.uni-berlin.de> <1191000394.828693.285210@k79g2000hse.googlegroups.com> <46FD40A5.8030504@holdenweb.com> Message-ID: <46FD6A38.5070606@sympatico.ca> Steve Holden wrote: > TheFlyingDutchman wrote: >> On Sep 28, 10:01 am, Marc 'BlackJack' Rintsch wrote: >>> On Fri, 28 Sep 2007 09:42:49 -0700, TheFlyingDutchman wrote: >>>> Which of the common languages have higher order functions and what is >>>> the syntax? >>> C, C++, Pascal, Perl, PHP, Ruby have them. And of course the functional >>> languages, most notably Lisp and Scheme as you asked for common languages. >>> >>> Don't know if C#'s delegates qualify. >>> >>> Ciao, >>> Marc 'BlackJack' Rintsch >> What is the syntax of a higher order function in C, C++ and Pascal? >> > This is like listening to a four-year-old torment its parents with > incessant questions. Do you *have* to ask every question that pops into > your mind? > > regards > Steve Tut Tut! A reasonable question is being asked. Colin W. From horpner at yahoo.com Tue Sep 11 09:57:55 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 11 Sep 2007 13:57:55 GMT Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> <13dmctogeh19410@corp.supernews.com> Message-ID: On 2007-09-11, Robert Brown wrote: > Neil Cerutti writes: > >> On 2007-09-02, Steven D'Aprano >> wrote: >>> A big question mark in my mind is Lisp, which according to >>> aficionados is just as dynamic as Python, but has native >>> compilers that generate code running as fast as highly >>> optimized C. > >> Lisp, as far as I know, requires type declarations, >> discipline, deep knowledge of Lisp, and more than passing >> knowledge of your Lisp implementation in order to generate >> code that's competitive with C. > > On my Mac Mini, the original Python code runs in 6 minutes 37 > seconds using Python 2.3.5. The Common Lisp code below, a > straightforward translation, containing *no* type declarations, > runs in 27 seconds on the same Mini using SBCL. > > When the commented out optimization declaration is included in > the code, the run time drops to 3.3 seconds. For comparison, > run times with GCC on the C version posted earlier are 3.5 > seconds unoptimized and 0.58 seconds with optimization flag > "-O3". > > So for this example, deep knowledge of the Lisp implementation > and type declarations are not required to get speed equivalent > to unoptimized C code. Approaching the speed of optimized C > code does require more work. >==================== > > (defun doit () > ;; (declare (optimize (speed 3) (safety 0) (debug 0))) > (let ((solutions (make-array 1001 :initial-element 0))) > (loop for a upfrom 1 below 10000 > do (loop for b upfrom 1 below (- 1000 a) > do (loop for c upfrom 1 below (- 1000 a b) > do (let ((p (+ a b c))) > (when (and (< p 1000) > (= (+ (* a a) (* b b)) (* c c))) > (incf (aref solutions p))))))) > (loop with max-index = 0 > with max = 0 > for solution across solutions > for index upfrom 0 > do (when (> solution max) > (setf max solution) > (setf max-index index)) > finally (print max-index)))) That's pretty cool. Thanks for the example. -- Neil Cerutti From nyamatongwe+thunder at gmail.com Mon Sep 17 02:35:30 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 17 Sep 2007 06:35:30 GMT Subject: Try this In-Reply-To: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> Message-ID: GeorgeRXZ: > Then Open the Notepad and type the following sentence, and save the > file and close the notepad. Now reopen the file and you will find out > that, Notepad is not able to save the following text line. This is a known issue with Notepad. See the "Unicode detection" section of http://en.wikipedia.org/wiki/Notepad Neil From gagsl-py2 at yahoo.com.ar Sun Sep 9 15:17:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Sep 2007 16:17:49 -0300 Subject: /dev/null as a file-like object, or logging to nothing References: <87k5r1jdzq.fsf@wilson.homeunix.com> <5kg48jF33dv5U3@mid.uni-berlin.de> <87fy1pjbpl.fsf@wilson.homeunix.com> Message-ID: En Sat, 08 Sep 2007 14:42:14 -0300, Torsten Bronger escribi?: >> `os.devnull`? > > Yes, but I wasn't really sure how portable it is, in particular, on > Windows. So does > > open(os.devnull, "w").write("Schallalla") > > work on Windows like on Unix? Yes. os.devnull=='nul' on Windows. -- Gabriel Genellina From stefan.behnel-n05pAM at web.de Fri Sep 21 09:12:21 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 21 Sep 2007 15:12:21 +0200 Subject: __contains__() : Bug or Feature ??? In-Reply-To: <1190380085.770828.19400@o80g2000hse.googlegroups.com> References: <1190380085.770828.19400@o80g2000hse.googlegroups.com> Message-ID: <46F3C335.60905@web.de> sebastien.lannez at gmail.com wrote: > I need to overload the operator in and let him > return an object ... It seems it is not a > behavior Python expect : > >>>> class A: > ... def __contains__(self,a): > ... return 'yop' > ... >>>> a=A() >>>> print 'toto' in a > True Not sure what you're trying to achieve, but the semantics of the "in" operator make it return a boolean value. The string "yop" evaluates to the boolean value True, as it is not empty. Stefan From wizzardx at gmail.com Sat Sep 8 16:28:03 2007 From: wizzardx at gmail.com (David) Date: Sat, 8 Sep 2007 22:28:03 +0200 Subject: Organizing Code - Packages In-Reply-To: <1189280539.449868.169910@22g2000hsm.googlegroups.com> References: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> <46e17143$0$6189$426a74cc@news.free.fr> <1189183088.922537.18290@r34g2000hsd.googlegroups.com> <87r6laa0ir.fsf@rudin.co.uk> <46e1a0bc$0$7689$9b4e6d93@newsspool2.arcor-online.net> <1189280539.449868.169910@22g2000hsm.googlegroups.com> Message-ID: <18c1e6480709081328i1f95e67cje22409de1657c3da@mail.gmail.com> > > How do import statements that are declared at the top of a python > module work? > > for instance.... > > from MyModule.Objects import * > > class Class: > def function: > #here i cannot access the things that should have been > imported from the above statement > #i printed the dir() function to verify this I have seen this myself (stuff seemingly not imported) when 2 modules import each other, perhaps indirectly, and try to use elements from each other (at the global/declaration step, rather than in functions. Logic that runs later (not during the import phase) still works fine, however)). This sounds like the problem you're having, but your code snippet isn't complete enough for me to tell. The way to fix this is generally to move out stuff used by both modules into a separate module. Another reason can be that the imported module should be but isn't setting the "__all__" variable. (in general the "import *" syntax is frowned upon, it reduces readability). From aahz at pythoncraft.com Wed Sep 19 11:20:35 2007 From: aahz at pythoncraft.com (Aahz) Date: 19 Sep 2007 08:20:35 -0700 Subject: Using pseudonyms (was Re: Python 3K or Python 2.9?) References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46effd63$0$16044$426a74cc@news.free.fr> Message-ID: In article <46effd63$0$16044$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: >Aahz a ?crit : >> In article , >> Steve Holden wrote: >>> Aahz wrote: >>>> In article <46ef893c$0$21882$426a34cc at news.free.fr>, >>>> Bruno Desthuilliers wrote: >>>>> Aahz a ?crit : >>>>>> In article <46ee2d9d$0$26213$426a74cc at news.free.fr>, >>>>>> Bruno Desthuilliers wrote: >>>>>>> But what, given that I'm an AOL user still thinking it's kewl to hide >>>>>>> behind a pseudo, what else would you expect ? >>>>>> What exactly is a "pseudo", pray tell? >>>>> Sorry : a pseudonym (a nickname). >>>> >>>> You apparently missed the thrust of my sarcasm. You can't tell what is >>>> or is not a pseudonym online. For all I know, "Bruno Desthulliers" is a >>>> pseudonym. While I recognize that there is some social advantage to >>>> linking consistent identifiers with people, I have I think understandable >>>> irritation with people who insist that names follow certain patterns. >>>> >>>> (For those joining only recently, my full legal name is "Aahz", which I >>>> changed from my former name precisely because of attitudes like Bruno's.) > >For the record, I usually don't give a damn about what >name/nickname/whatever peoples use. Then why mention pseudonyms at all? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From pyth0nc0d3r at gmail.com Fri Sep 14 19:50:33 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 14 Sep 2007 18:50:33 -0500 Subject: Is there some sort of Python Error log. Message-ID: Command prompt is a pain and it would be pretty nice to have this feature. -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Thu Sep 20 13:18:07 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 20 Sep 2007 12:18:07 -0500 Subject: Sets in Python In-Reply-To: References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <13f3m15igkstq2e@corp.supernews.com> <1190260923.243865.312190@z24g2000prh.googlegroups.com> <13f4nclh902f78f@corp.supernews.com> Message-ID: <4866bea60709201018y119f05f6v76e9c5c86ef45976@mail.gmail.com> On 9/20/07, OKB (not okblacke) wrote: > Steven D'Aprano wrote: > > > But of course you can't look up the dict by value, only by > > identity. But that's what you wanted. > > Actually, if I understand the OP's examples right, he wants to look > up only by value, not by identity. > He's switched at least twice, as I understand his writing. Currently, he appears to want to look up by value, copying lists on insertion, and is ignoring what happens if you mutate the key. From dorjetarap at googlemail.com Mon Sep 17 15:04:11 2007 From: dorjetarap at googlemail.com (dorje tarap) Date: Mon, 17 Sep 2007 20:04:11 +0100 Subject: pattern combinations Message-ID: Hi all, Given some patterns such as "...t...s." I need to make all possible combinations given a separate list for each position. The length of the pattern is fixed to 9, so thankfully that reduces a bit of the complexity. For example I have the following: pos1 = ['a',' t'] pos2 = ['r', 's'] pos3 = ['n', 'f'] So if the pattern contains a '.' character at position 1 it could be 'a' or 't'. For the pattern '.s.' (length of 3 as example) all combinations would be: asn asf tsn tsf Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From BjornSteinarFjeldPettersen at gmail.com Sat Sep 29 14:24:15 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sat, 29 Sep 2007 11:24:15 -0700 Subject: strange unbound local error? In-Reply-To: <1191089079.818739.245820@22g2000hsm.googlegroups.com> References: <1191089079.818739.245820@22g2000hsm.googlegroups.com> Message-ID: <1191090255.338427.260390@w3g2000hsg.googlegroups.com> On Sep 29, 8:04 pm, rig... at arcor.de wrote: > hi folks, > > suppose this snipplet: > > spam = 42 > > def eggs(): > print spam > spam = spam + 1 > > if __name__=="__main__": > eggs() > > This thows an UnboundLocalError at line 4 (print statement). But if I > comment out line 5 (variable assignment), no error occurs. > > Can you explain me this, please? > > Regards, > Enrico If you're going to assign to a global variable in a function, you need to declare it as such: spam = 42 def eggs(): global spam print spam spam = spam + 1 When Python sees an assignment to an identifier in a function it creates a variable that is local to the function (otherwise you'd be unable to create local variables with the same name as any of the global variables). -- bjorn From steve at REMOVE-THIS-cybersource.com.au Sun Sep 30 09:19:06 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Sep 2007 13:19:06 -0000 Subject: Optparse and help formatting? References: <87abr423hu.fsf@benfinney.id.au> Message-ID: <13fv8ia94nq69d3@corp.supernews.com> On Sun, 30 Sep 2007 07:37:10 -0500, Tim Chase wrote: > def format_option(self, option): > # The help for each option consists of two parts: > # * the opt strings and metavars [snip] Tim, I notice you're using lots of # lines as comments to describe the function. Perhaps you should consider using docstrings instead. Pardon me if I'm telling you what you already know... A docstring is a string that immediately follows a class, function or method declaration, or at the beginning of a module: def parrot(): "This is a doc string." s = "this is not a docstring" The advantage of docstrings is that unlike # comments, they aren't discarded at compile time, and can be accessed by the caller: >>> parrot.__doc__ 'This is a doc string' This is especially useful in the interactive interpreter, where help(object) will grab the docstring and format it nicely on screen. -- Steven. From iddw at hotmail.com Tue Sep 11 15:25:34 2007 From: iddw at hotmail.com (Dave Hansen) Date: Tue, 11 Sep 2007 12:25:34 -0700 Subject: Car-ac-systems In-Reply-To: <1189532573.728913.306470@g4g2000hsf.googlegroups.com> References: <1189532573.728913.306470@g4g2000hsf.googlegroups.com> Message-ID: <1189538734.525106.191550@b32g2000prf.googlegroups.com> On Sep 11, 12:42 pm, Zentrader wrote: > > What is it about "please do not top-post" that you have difficulty > understanding? Or do "MVP"s feel that their time is so much more > valuable than anyone else's that they are free to ignore the norms? > > Who made this the norm? http://www.ietf.org/rfc/rfc1855.txt If you don't know what the IETF is, or what an RFC is, you should educate yourself. http://www.ietf.org/glossary.html#IETF is a good place to start. > In my travels through web-land, it appears to Usenet is not "web-land". And it is not Google Groups, either. Look up http://www.faqs.org/faqs/usenet/welcome/part1/ for more info > be the opposite. Don't waste space repeating everything in every > post, and it wastes everyone's time by have to go over the same thing > again and again. Perhaps this thread has a purpose after all, anyway > it has been reported as spam. You have much to learn. Regards, -=Dave From steven at REMOVE.THIS.cybersource.com.au Thu Sep 6 23:42:07 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Sep 2007 03:42:07 -0000 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> <13dvvgk96amhhec@corp.supernews.com> <13e1cbetihma1d6@corp.supernews.com> Message-ID: On Fri, 07 Sep 2007 12:03:26 +1000, bambam wrote: > Hi Steven. > > Looking at your code, why are you naming the value __all__? It looks > like a built-in variable? When you say: from module import * Python looks in the module for a list of names called "__all__", and imports only the names in that list. It is recommended that your modules take advantage of that feature. I'm just using the same name. > Unless there is an automatic way to correctly get the function list, I > will probably be better off giving the lines sequence numbers, and > generating the function list from that. I don't understand what you mean by "giving the lines sequence numbers". Where do they come from? How do you go from sequence numbers to functions? As far as I am concerned, the right behavior is for the module containing the functions to define which functions need to be tested. Since modules aren't actually intelligent, that means some person needs to list the functions. Why list the function NAME when you can list the function itself? From gagsl-py2 at yahoo.com.ar Mon Sep 24 22:19:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Sep 2007 23:19:13 -0300 Subject: Python script to optimize XML text References: <496954360709241336i43173947sda5245c2d7477ecb@mail.gmail.com> Message-ID: En Mon, 24 Sep 2007 17:36:05 -0300, Robert Dailey escribi?: > I'm currently seeking a python script that provides a way of optimizing > out > useless characters in an XML document to provide the optimal size for the > file. For example, assume the following XML script: > > > > > > > > > By running this through an XML optimizer, the file would appear as: > > ElementTree does that almost for free. I've just posted an example. source = """ """ import xml.etree.ElementTree as ET tree = ET.XML(source) print ET.tostring(tree) Output: If you still want to remove all whitespace: def stripws(node): if node.text: node.text = node.text.strip() if node.tail: node.tail = node.tail.strip() for child in node.getchildren(): stripws(child) stripws(tree) print ET.tostring(tree) Output: -- Gabriel Genellina From rabidpoobear at gmail.com Sat Sep 15 00:09:52 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 14 Sep 2007 23:09:52 -0500 Subject: [pygame] Re: Just bought Python in a Nutshell In-Reply-To: References: <1189784843.896396.108960@g4g2000hsf.googlegroups.com> <59f9c5160709141412q1098a4cbi989b6eed2f2cc899@mail.gmail.com> Message-ID: <46EB5B10.2020100@gmail.com> Lamonte Harris wrote: > Wow I just got it, and its nice doesn't even look used god damn. :D. It's generally considered rude to curse in technical forums such as this. Also, please use more punctuation. You're hard to understand sometimes. -Luke From claird at lairds.us Fri Sep 14 10:37:00 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 14 Sep 2007 14:37:00 +0000 Subject: automatic parallelization References: <46E99488.20909@uni-oldenburg.de> <1338560.ksk72Tk4Kk@aldan.algebra.com> Message-ID: In article <1338560.ksk72Tk4Kk at aldan.algebra.com>, Mikhail Teterin wrote: . . . >> I'm fond of Linda > http://www.unixreview.com/documents/s=10125/ur0704l/ >, Parallel >> Python only one of several >> initiatives which aspire to exploit multicores, and so on. > >Linda URL does not open... I'll look into Parallel Python, but it is . . . It comes and goes. It seems to have been OK the last several hours. From Caseyweb at gmail.com Thu Sep 27 12:58:44 2007 From: Caseyweb at gmail.com (Casey) Date: Thu, 27 Sep 2007 16:58:44 -0000 Subject: True of False In-Reply-To: References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> Message-ID: <1190912324.363127.26100@r29g2000hsg.googlegroups.com> On Sep 27, 12:48 pm, "Simon Brunning" wrote: > On 9/27/07, kou... at hotmail.com wrote: > > > I tried writing a true and false If statement and didn't get > > anything? I read some previous posts, but I must be missing > > something. I just tried something easy: > > > a = ["a", "b", "c", "d", "e", "f"] > > > if "c" in a == True: > > Print "Yes" > > > When I run this, it runs, but nothing prints. What am I doing wrong? > > Just use > > if "c" in a: > > and all will be well. The True object isn't the only truthy value in > Python - see . I would recommend the OP try this: run the (I)python shell and try the following: >>> a = [x for x in "abcdefg"] >>> a ['a','b','c','d','e','f','g'] >>> "c" in a True >>> "c" in a == True False >>> ("c" in a) == True True The reason your conditional failed is that it was interpreted as "c" in (a == True) which is False. the "==" operator binds at a higher precedence level than the "in" operator, just as multiplication binds higher than addition From carsten at uniqsys.com Sat Sep 22 16:50:03 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 22 Sep 2007 16:50:03 -0400 Subject: frange() question In-Reply-To: <87odfuwoh8.fsf@pobox.com> References: <87tzppjhe4.fsf@pobox.com> <87lkaz40sj.fsf@pobox.com> <87odfuwoh8.fsf@pobox.com> Message-ID: <1190494203.3266.21.camel@localhost.localdomain> On Sat, 2007-09-22 at 18:21 +0000, John J. Lee wrote: > Carsten Haese writes: > > The second half of my post illustrates a difference of opinion about > > what constitutes a generator function. You state that frange() is not a > > generator function because it doesn't use yield, but it behaves like > > one. My point is that it *is* a generator function because the generator > > expression is merely syntactic sugar for an equivalent for/yield loop. > > Seems to me that's a definitional thing, with no conceptual content, > so "difference of opinion" seems an odd choice of words. It would be > nice to nail the definitions down. Do the Python docs do that? > > > > Of course, the distinction of whether frange() *is* a generator function > > or merely *behaves* as one is immaterial in practice, and we can both be > > right in the absence of a formal definition of what a generator function > > is. PEP 255 says "A function that contains a yield statement is called a > > generator function," but that was written before generator expressions > > were introduced. > > Ah, they do -- thanks. Though I'm now left puzzled why you express > your "difference of opionion" above... It's a matter of opinion whether the excerpt from the PEP constitutes the formal definition of what a generator function is or isn't. A formal definition needs conditions that are both sufficient and necessary. The PEP only says that having a yield statement is sufficient for making a generator function. It doesn't say that a yield statement is necessary for making a generator function. In other words, it doesn't say that a function that doesn't contain a yield statement isn't a generator function. The language reference is equally wishy-washy: "Using a yield statement in a function definition is *sufficient* to cause that definition to create a generator function instead of a normal function." [emphasis mine] Again, no indication that a yield statement is necessary for making a generator function. It then proceeds to saying "When a generator function is called, it returns an iterator known as a generator iterator, or more commonly, a generator." That condition seems to be true for the OP's frange() function, even though it doesn't have a yield statement. Until somebody can point out a definition that says unequivocally "an object is a generator function if and only if ...", it's up in the air whether frange() is a generator function or merely impersonates a generator function. Ultimately, though, this is a purely academic question without a useful answer. The useful conclusion is that a function can behave like a generator function without a yield statement, and we have reached that conclusion a long time ago. -- Carsten Haese http://informixdb.sourceforge.net From zzbbaadd at aol.com Thu Sep 13 13:10:57 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 13 Sep 2007 10:10:57 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: <46e96aaa$0$7685$9b4e6d93@newsspool2.arcor-online.net> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> <46e96aaa$0$7685$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1189703457.297526.172460@50g2000hsm.googlegroups.com> > > Isn't one of the main ideas behind python that it doesn't force you to > do (well, declare) anything? And by "ideas" I mean "design decisions". > Thats exactly what makes python great for prototyping; you just do it > and see if it works. As soon as you need to declare things you have to > change stuff in at least 2 places for every change of heart you have. > > (Can you tell I'm currently forced to developing in Java? ;) (Which I'm > currently avoiding to do, by wasting my time on usenet.)) > But if you are looking at code you didn't write, it's nice to be able to see all the member variables that a class has listed separate from method code. I think static typing helps in trying to deduce what code is doing, particularly when you are looking at function definitions. You don't have to work to find out what type of variables it takes. From paul at boddie.org.uk Mon Sep 10 09:55:55 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 10 Sep 2007 06:55:55 -0700 Subject: uninstall In-Reply-To: References: Message-ID: <1189432555.060384.194820@50g2000hsm.googlegroups.com> On 10 Sep, 15:45, Milos Prudek wrote: > I run "make install" of Python 2.4.4 and now I discovered that I do not like > the default placement of my install. The Makefile does not support > an "uninstall" option. > > Is there a way to uninstall Python compiled from sources? If you're installing from sources "manually", you might want to consider checkinstall to give you the option of an uninstall for those software distributions which don't support "make uninstall": http://www.asic-linux.com.mx/~izto/checkinstall/ I seem to recall at some point doing a checkinstall on one or more programs, installing the resulting packages, then uninstalling them in order to remove installed files. That might be one approach you could take, although it obviously won't restore any files overwritten when you originally installed Python. That said, Python tends to install into /usr/local by default and is fairly conservative about where it puts its files, so it's unlikely that anything was overwritten. Paul From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Sep 27 05:14:14 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 27 Sep 2007 11:14:14 +0200 Subject: Using closures and partial functions to eliminate redundant code References: Message-ID: <5m1aj6FahetoU1@mid.individual.net> Matthew Wilson wrote: > I'm interested to hear how other people deal with really similar > code. > The similarity just bugs me. However, I wonder if using stuff > like closures or partial function application is needlessly showy. ACK -- but not because it's showy, but because it may be more error-prone and less readable. I'd often use an approach like this: def create_user(username, userpassword, useremail, create = False): """ Send an email that will update a user in the remote system. If create evaluates to True, don't update the user, but create her instead. """ if not create: subject = "UPDATE" else: subject = "CREATE" # Build email email_body = """ USERNAME = %s USERPASSWORD = %s USEREMAIL = %s """ % (username, userpassword, useremail) # send it. send_email(subject=subject, body=email_body) Regards, Bj?rn -- BOFH excuse #353: Second-system effect. From steve at REMOVE-THIS-cybersource.com.au Sat Sep 15 20:40:13 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 00:40:13 -0000 Subject: Needless copying in iterations? References: <5l3ab6F5v20uU3@mid.uni-berlin.de> Message-ID: <13eourdrne86e61@corp.supernews.com> On Sun, 16 Sep 2007 00:05:58 +0000, Marc 'BlackJack' Rintsch wrote: > On Sat, 15 Sep 2007 14:58:15 -0700, James Stroud wrote: > >> I was staring at a segment of code that looked like this today: >> >> for something in stuff[x:y]: >> whatever(something) >> >> and was wondering if the compiler really made a copy of the slice from >> stuff as the code seems to suggest, or does it find some way to produce >> an iterator without the need to make a copy (if stuff is a built-in >> sequence type)? > > The compiler can't "optimize" this as it would change the semantics. > There's no way for the compiler to tell if this copy really is > "needless". `whatever()` may change `stuff[i]` where `i` is in `x:y` and > this may lead to different results wether it iterates over a copy or the > original. In *general* the compiler can't tell, but in specific cases it could. A (hypothetical) optimizing compiler would tell the difference between: for item in alist[1:5]: print item # no possible side-effects for item in alist[1:5]: function(alist, item) # there might be side-effects for item in alist[1:5]: alist.append(item) # side-effects DON'T matter for i, item in enumerate(alist[1:5]): alist[i+1] = function(item) # side-effects DO matter Of course this is all besides the point, since no such optimizing compiler exists today, at least not for CPython. Any volunteers? -- Steven. From mstepnicki at gmail.com Wed Sep 26 09:39:22 2007 From: mstepnicki at gmail.com (=?iso-8859-2?q?Marcin_St=EApnicki?=) Date: Wed, 26 Sep 2007 13:39:22 +0000 (UTC) Subject: scope, modyfing outside object from inside the method References: Message-ID: Dnia Mon, 24 Sep 2007 10:41:22 -0300, Ricardo Ar?oz napisa?(a): > Would this work for you? Thank you both for help. Well - yes and no :). It's getting more interesting: First, your code: class myrow(): def __init__(self, idict = {}): self.container = idict def __str__ (self): return self.container.__str__() results = [ {'a': 12, 'b' :30 }, {'a': 13, 'b' :40 } ] mystruct = [] for row in results: mystruct.append(myrow(row)) results[1]['b'] = 444 print results # [{'a': 12, 'b': 30}, {'a': 13, 'b': 444}] print mystruct # does not work ok , you should probably define # mystruct's __str__ method properly # But, save for the __str__ thingy, the rest is ok. for row in mystruct: print row # {'a': 12, 'b': 30} # {'a': 13, 'b': 444} And now let's try to swap results with something else: print id(results) # new resultset results = [ {'a': 112, 'b' : 130 }, {'a': 113, 'b' : 140 } ] print id(results) for row in mystruct: print row # {'a': 12, 'b': 30} # {'a': 13, 'b': 444} At first glance (before adding id()) it's a little bit weird. The original object was supposedly "overwritten", but as one can see it has different id then the new one. mystruct still holds references to old object, though. I can handle it and just change original object, but I'm curious if there's a way to "swap" them "on-the-fly". Thanks one again. -- | And Do What You Will be the challenge | http://apcoln.linuxpl.org | So be it in love that harms none | http://biznes.linux.pl | For this is the only commandment. | http://www.juanperon.info `---* JID: Aragorn_Vime at jabber.org *---' http://www.naszedzieci.org From Shawn at Milochik.com Wed Sep 19 13:15:30 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 19 Sep 2007 13:15:30 -0400 Subject: [Tutor] Finding prime numbers In-Reply-To: <2dc0c81b0709191013k181d1a74m76a08cecadb005c4@mail.gmail.com> References: <1190218927.7991.25.camel@apprentice-laptop> <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> <1190219929.7991.28.camel@apprentice-laptop> <2dc0c81b0709191013k181d1a74m76a08cecadb005c4@mail.gmail.com> Message-ID: <2dc0c81b0709191015l1ac39615ya541e307abe5c372@mail.gmail.com> Okay, I caught one bug already myself: for y in range(3,(math.sqrt(x) + 1)): should be for y in range(3,(int(math.sqrt(x)) + 1)): From spam.noam at gmail.com Tue Sep 18 11:49:45 2007 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: Tue, 18 Sep 2007 15:49:45 -0000 Subject: How can I know how much to read from a subprocess In-Reply-To: References: <1190070896.332844.23080@22g2000hsm.googlegroups.com> <1190072376.600475.254260@y42g2000hsy.googlegroups.com> Message-ID: <1190130585.255648.312730@q3g2000prf.googlegroups.com> On Sep 18, 1:48 pm, "A.T.Hofkamp" wrote: > On 2007-09-17, spam.n... at gmail.com wrote: > > > It seems that another solution is gobject.io_add_watch, but I don't > > see how it tells me how much I can read from the file - if I don't > > know that, I won't know the argument to give to the read() method in > > order to get all the data: > > >http://www.pygtk.org/docs/pygobject/gobject-functions.html#function-g... > > Usually, gobject only tells you that data is there (that is all it knows). > Therefore a read(1) should be safe. But even if it's fast enough, how do you know how many times you should call read(1)? If you do it too much, you'll be blocked until more output is available. > If that is too slow, consider os.read() which reads all data available (afaik, > never tried it myself). > I tried it now, and it blocks just like the normal file.read(). Thanks, Noam From larry.bates at websafe.com Wed Sep 19 10:27:34 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 19 Sep 2007 09:27:34 -0500 Subject: Using python to create windows apps that everyone can use? In-Reply-To: References: <7C008A37566.00000D2Atomharding@inbox.com> Message-ID: Matt McCredie wrote: > On 9/18/07, Thomas Harding wrote: >> Hi guys, sorry to post another topic on this, as I am aware that it has >> already been posted a few times, but not with specifically what I am looking >> for. I want an app that makes a gui interface for python (similar to >> Microsoft visual studio or qt designer, not a code based one) and/or an app >> that can make this into a .exe that can be opened by any person on any >> computer without python installed. > > check out py2exe: http://py2exe.org > > matt Might want to take a look at wxGlade (http://wxglade.sourceforge.net), you will need wxWindows and py2exe to complete the toolkit. -Larry From bj_666 at gmx.net Mon Sep 10 16:31:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2007 20:31:07 GMT Subject: memcpy References: <1189449530.171049.323230@22g2000hsm.googlegroups.com> Message-ID: <5klnsbF3vfqqU10@mid.uni-berlin.de> On Mon, 10 Sep 2007 11:38:50 -0700, Tim wrote: > How do I memcpy from a pointer to an array of floats in python? > > I get errors: NameError: global name 'row' is not defined Well than the (global) name `row` is not defined. Quite clear message, isn't it? ;-) > I want to be able to get the row[i] array element. In C I would > normally place the address of row as the first argument. > > cdll.msvcrt.memcpy( row, pData, 256 ) > > > If I define row as the following I also get the following error: > > row = ones( TOTAL_PARAMETER_ENTRIES, dtype=float ) > > ArgumentError: argument 1: : Don't know > how to convert parameter 1 You don't give enough information so we have to guess. For example I guess the `ones()` function comes from one of the packages `numeric`, `numarray` or `numpy`!? This function returns a Python object. You can't use arbitrary Python objects with `ctypes`. `memcpy` expects a pointer not an object. Ciao, Marc 'BlackJack' Rintsch From szhorvat at gmail.com Wed Sep 12 09:51:15 2007 From: szhorvat at gmail.com (=?ISO-8859-1?Q?Szabolcs_Horv=E1t?=) Date: Wed, 12 Sep 2007 15:51:15 +0200 Subject: pythonesque constructs for c++ In-Reply-To: References: Message-ID: Josh wrote: > One of the best features of python is its ease of use, and the ease of use > of its modules. Modules like os, os.path, and datetime are invaluable! > > Does anyone know of analagous c++ libraries? It seems to me that most of the > functionality of these modules could easily be replicated in c++. Before I > go about doing that, I was just wondering if anyone knows if they already > exist? Check out Boost. http://www.boost.org/ http://www.boost.org/libs/filesystem/doc/index.htm http://www.boost.org/doc/html/date_time.html -- Szabolcs From kostaspaxos at yahoo.gr Sat Sep 15 05:24:01 2007 From: kostaspaxos at yahoo.gr (Konstantinos Pachopoulos) Date: Sat, 15 Sep 2007 12:24:01 +0300 Subject: trim start and trailing space chars from string Message-ID: <46EBA4B1.1030302@yahoo.gr> Hi, is there something corresponding to the java String.trim() method, ie trim start and trailing space/tab chars from string? say convert " asdf " to "asdf"? Thnx From naga86 at gmail.com Mon Sep 10 05:50:30 2007 From: naga86 at gmail.com (Nagarajan) Date: Mon, 10 Sep 2007 02:50:30 -0700 Subject: less obvious "super" Message-ID: <1189417830.645749.226120@d55g2000hsg.googlegroups.com> Hi group, I am confused with "super" usage..It seems to be complicated and less obvious. Here is what I need to achieve.. class A : def __init__( self ): self.x = 0 class B ( A ): def __init__( self, something ): # Use "super" construct here so that I can "inherit" x of A self.y = something How should I use "super" so that I could access the variable "x" of A in B? Thanks! From super.sgt.pepper at gmail.com Fri Sep 21 17:37:18 2007 From: super.sgt.pepper at gmail.com (Cristian) Date: Fri, 21 Sep 2007 21:37:18 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? Message-ID: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> A friend of mine is an engineer and he's been needing to do more and more programming as he goes on with is career. I convinced him to learn Python instead of Perl and he's really started to like it. He usually comes to me when he can't accomplish a task with his current knowledge and I introduce him to a new feature in Python. FYIW, he thought List Comprehensions were freakin' awesome. He's started writing his own personal scripts for tasks like web scraping. So, from personal experience, Python truly is a great first language to learn. Although his learning experience has gone mostly smoothly, he's hit a lot of speed bumps with functions. Specifically, he's having trouble thinking of functions as first order data (don't worry, I haven't confused him with such terminology yet). He had a little trouble understanding that you can pass functions as arguments to other functions (e.g., passing a key to the list.sort method). He also had a little trouble grasping functions within other functions. Last but not least, he had trouble grasping methods in class declarations, especially the required self as the first argument (I'm sure he wasn't the first). Now, my friend's a smart guy so I know it isn't any lack of brain cells on his part. I still remember many students in my CS classes having trouble grasping the very same concept. And, after we finally get a hold of first order functions, we appreciate its incorporation into languages. It would be a shame if my friend just learns the motions and never incorporates first order functions into his programs. I began to wonder if there was anything Python could do to help newcomers grasp the power of first order functions or, as Pythonistas put it, everything is an object. To me, the biggest setback for new programmers is the different syntax Python has for creating functions. Instead of the common (and easy to grasp) syntax of foo = bar Python has the def foo(): syntax. So, when a new programmer is first introduced to functions they are immediately confronted with the notion that functions are "different". After all, they have their own special syntax. This seems to only further the separation newbies make between "data" and "functions" or "stuff" and "actions". Now, the vast majority of us learned this dichotomy when we first began to program, so we are ingrained to assume and even expect a different syntax for function declaration, but in a program like Python there doesn't seem to be any other reason to have it. Furthermore, I think it actually inhibits the learning of the uninitiated. We can, of course, keep the current syntax as sugar. To someone who's learning to program wouldn't a syntax like the further give them all they need and also reinforces the idea that functions are data just like everything else? my_function = function(foo, bar): pass an_instance_method = function(self, foo): pass a_method_declaration = method(self, foo): pass The last one is mostly my pet peeve of having Python "magically" create methods out of (what is essentially) a function declaration. When I first learned it, it felt wrong but you had to press through it because there was really no other way of declaring methods. What do you think? Have you hit this roadblock when helping others learn Python? Does the current syntax make you feel that functions are still treated as second class (get it?) citizens? From python at rcn.com Mon Sep 24 18:04:56 2007 From: python at rcn.com (Raymond Hettinger) Date: Mon, 24 Sep 2007 15:04:56 -0700 Subject: Can a base class know if a method has been overridden? In-Reply-To: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> Message-ID: <1190671496.599826.215840@y42g2000hsy.googlegroups.com> On Sep 24, 8:23 am, Ratko wrote: > Hi all, > > I was wondering if something like this is possible. Can a base class > somehow know if a certain method has been overridden by the subclass? > I appreciate any ideas. > Thanks, > > Ratko It's not hard. Both bound and unbound methods have an im_func attribute pointing to the underlying function code. So you can check for overrides by testing whether the underlying functions are the same: >>> class A: def p(self): pass def q(self): pass >>> class B(A): def q(self): pass >>> b = B() >>> b.p.im_func is A.p.im_func # Verify that b.p runs A.p True >>> b.q.im_func is A.q.im_func # Verify that b.q overrides A.q Raymond False From paul.nospam at rudin.co.uk Tue Sep 18 04:44:59 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Tue, 18 Sep 2007 09:44:59 +0100 Subject: can Python be useful as functional? References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Message-ID: <87odg0l5v8.fsf@rudin.co.uk> Lorenzo Stella writes: > Hi all, > I haven't experienced functional programming very much, but now I'm > trying to learn Haskell and I've learned that: 1) in functional > programming LISTS are fundmental; 2) any "cycle" in FP become > recursion. > I also know that Python got some useful tool such as map, filter, > reduce... so I told: "let's try some FP-style programming with > Python!". I took a little example of Haskell: > > listprimes :: Integer -> [Integer] > listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)] > where > sieve [] = [] > sieve (p:xs) = p : sieve (filter (\x -> mod x p > 0) xs) > > and I tried to "translate" it in Python: > > def sieve(s): > if s == []: > return [] > else: > return [s[0]] + sieve(filter((lambda x: x % s[0] > 0), > s[1:])) > > def listprimes(n): > return sieve(range(2,n)) > > These should be almost the same: listprimes actually lists prime > integers up to n-1. The result is: Haskell implementation works well, > maybe it's not the better way to do it, but it does what I wanted. > Python implementation gives me > > RuntimeError: maximum recursion depth exceeded in cmp > > My question is: how can we call a language "functional" if it's major > implementation has a limited stack? Or is my code wrong? It's no tthat it's "wrong", but doing recursion in python can be problematic because there's no tail recursion optimisation and the size of the stack is limited (so eventually you'll run out of stack if you recurse deep enough). One way to capture the spirit of that Haskell program in Python is to use things from itertools; something like this (modified from ): import itertools def listprimes(n): def sieve(nums): seq = nums while True: prime = seq.next() seq = itertools.ifilter(prime.__rmod__, seq) yield prime if n == 0: return sieve(itertools.count(2)) else: return sieve(itertools.islice(itertools.count(2), n-1)) >>> list(listprimes(100)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] From steve at holdenweb.com Sun Sep 16 21:56:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Sep 2007 21:56:52 -0400 Subject: where are the .pyc files? In-Reply-To: <1189992200.860524.58620@w3g2000hsg.googlegroups.com> References: <1189963710.714191.74440@n39g2000hsh.googlegroups.com> <5l57t1F655kfU5@mid.uni-berlin.de> <1189992200.860524.58620@w3g2000hsg.googlegroups.com> Message-ID: Summercool wrote: > On Sep 16, 10:36 am, Marc 'BlackJack' Rintsch wrote: >> The `*.pyc` files are usually only created when you import a module, not >> when a module is run directly. > > how come a program that runs directly doesn't need to be optimized > into bytecode first? Or... is it that the interpreter will just run > the program as it goes by, without ever generating a .pyc file? So > what if you have a program that you only update every few weeks... > then you can ask a .pyc to be generated so that it runs faster every > time? > > You can, if you want, compile a program manually: http://docs.python.org/lib/module-compileall.html and run the resulting .pyc file if you wish. Most people don't bother, though. If you have a very large main program you can encapsulate it as a library and then call the library function from a teent-weeny main program that isn't worth compiling. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From zzbbaadd at aol.com Wed Sep 12 20:33:36 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 12 Sep 2007 17:33:36 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: <5kr8vlF53m8gU3@mid.individual.net> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> Message-ID: <1189643616.826715.58150@d55g2000hsg.googlegroups.com> On Sep 12, 3:53 pm, Bjoern Schliessmann wrote: > TheFlyingDutchman wrote: > > In C++ and Java I don't believe "this" is ever referred to as an > > implicit function parameter. > > Oh yes, it is. All methods use it as a base address into instances. > Implicitly though. I am not talking about how the implementation of a C++ or Java compiler uses the this pointer/this reference internally. I am talking about how an author describes in English the "this" pointer/reference in their book on programming C++ or Java. I don't think you will find them saying that under the covers "this" was passed to the method (if in fact it is). They just say that it refers to the current object inside that object's method. Here is a link to a tutorial where Sun is talking about the this reference: http://java.sun.com/docs/books/tutorial/java/javaOO/thiskey.html > > If it is in fact a real parameter in the underlying compiled-code > > implementation, that knowledge hurts more than it helps. > > To which language are you referring here, Python or C++? No matter > what, I still don't really understand why it hurted. > I am referring to C++. If someone is trying to learn the language, knowledge of the internal implemenation is counter-productive in my opinion because it distracts from the details they need to learn. If they are experienced and want to learn about the internals to potentially help them code in the most blazingingly fast manner they ideally would just be reminded they are using C++ and not some slower byte-code executed language where it could possibly matter. ;) From aahz at pythoncraft.com Mon Sep 17 21:01:46 2007 From: aahz at pythoncraft.com (Aahz) Date: 17 Sep 2007 18:01:46 -0700 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@1 <46ee2d9d$0$26213$426a74cc@news.free.fr> Message-ID: In article <46ee2d9d$0$26213$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: > >But what, given that I'm an AOL user still thinking it's kewl to hide >behind a pseudo, what else would you expect ? What exactly is a "pseudo", pray tell? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From khemkaamit at gmail.com Mon Sep 3 05:34:39 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Mon, 3 Sep 2007 15:04:39 +0530 Subject: TypeError: 'module object is not callable' In-Reply-To: <46dbd11e$0$6228$426a74cc@news.free.fr> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> Message-ID: <1360b7230709030234r4fd2b74q789dfd15f128309d@mail.gmail.com> On 9/3/07, Bruno Desthuilliers wrote: > Amit Khemka a ?crit : > (snip) > > The exception is being raised as you are being confused about the > > names ie: you have a class named "Step" in a module named "Step.py" . > > > Actually, the module is named 'Step', not 'Setp.py' !-) > > Yup, My Bad ! Thanks. -- ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in From jscrerar at compuserve.com Sat Sep 29 16:34:34 2007 From: jscrerar at compuserve.com (Jim) Date: Sat, 29 Sep 2007 13:34:34 -0700 Subject: Command-line does work when scheduled Message-ID: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> Hi, I want to schedule a Python program that reads the command line for input. However, when adding an argument to the command line Python will not pick it up when using Windows scheduled tasks. How do I get it to work? Thanks, Jim From openpavilion at openpavilion.org Thu Sep 13 07:23:29 2007 From: openpavilion at openpavilion.org (OpenPavilion Team) Date: Thu, 13 Sep 2007 04:23:29 -0700 (PDT) Subject: wxstyledtextctrl and xml markup Message-ID: <12652955.post@talk.nabble.com> Hello community, I want to create an editor for a self defined xml markup language. I want to use wxpython with wxstyledtextctrl and I have looked around at yellowbrain site, but there are no examples. I also watched the styledtextctrl examples with wxpython 2.8.4. What I am looking for is an example of how to do the autocompletion part for the styledtextctrl based on my self defined XML language. example: [...] Since I don't know styledtextctrl, I fear that I am about to write a complex handler for the autocompletion part, whereas there could be some easy to use features built into styledtextctrl. My problem is that I don't want to externalize the grammar of the XML instead of coding it inside the autocompletion handler. Are there any examples for wxstyledtextctrl, xml and autocompletion ? Regards Pavilion -- View this message in context: http://www.nabble.com/wxstyledtextctrl-and-xml-markup-tf4435096.html#a12652955 Sent from the Python - python-list mailing list archive at Nabble.com. From steven.klass at gmail.com Thu Sep 6 15:31:34 2007 From: steven.klass at gmail.com (rh0dium) Date: Thu, 06 Sep 2007 19:31:34 -0000 Subject: Help setting default class attributes In-Reply-To: <1189101306.620588.89140@r29g2000hsg.googlegroups.com> References: <1189099594.432512.278950@22g2000hsm.googlegroups.com> <1189101306.620588.89140@r29g2000hsg.googlegroups.com> Message-ID: <1189107094.982955.164690@y42g2000hsy.googlegroups.com> On Sep 6, 10:55 am, Arnaud Delobelle wrote: > On Sep 6, 6:26 pm, rh0dium wrote: > > > Hi all, > > > I have the following piece of code and I wanted to set the default > > attributes based on a dictionary. What I am looking for is a way to > > take PIPODEFAULTS and assign each one as an attribute for the class > > pipo. Can someone show me how to do this by iterating over the > > PIPODEFAULTS and assign them. What I would expect to be able to do is > > call the class and modify them. > > Use the setattr(...) function. > > > > > example: > > a = pipo() > > print a.caseSensitivity > > "preserve" > > > a.caseSensitivity = "lower" > > print a.caseSensitivity > > "lower" > > > Lastly - here is my code: > > > class pipo: > > > PIPODEFAULTS={ "caseSensitivity" : "preserve","cellMapTable" : > > "","checkPolygon" : "nil","compression" : "none", > > "convertDot" : "ignore","convertPathToPoly" : > > "nil","convertToGeo" : "nil","dumpPcellInfo" : "nil", > > "snapToGrid" : "nil","techFileChoice" : > > "nil","units": "micron","useParentXYforText" : "nil","viewName" : > > "layout", > > } > > > def __init__(self, *args, **kwargs): > > """This simply will run a PIPO stream out > > """ > > # Setup Logging > > self.pipoargs=self.setdefaults() > > def setdefaults(self): > > for x in self.PIPODEFAULTS: > > self.log.debug("Setting %s to %s" % (x, > > self.PIPODEFAULTS[x])) > > def setdefaults(self): > for key, val in self.PIPODEFAULTS.iteritems(): > setattr(self, key, val) > Hey this is great!!! Simple and clear. I appreciate it!! From http Sat Sep 22 21:10:03 2007 From: http (Paul Rubin) Date: 22 Sep 2007 18:10:03 -0700 Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> <1190484589.890198.266430@y42g2000hsy.googlegroups.com> <13fbahtem90fp99@corp.supernews.com> <1190506229.092718.41690@g4g2000hsf.googlegroups.com> Message-ID: <7xps0achlg.fsf@ruckus.brouhaha.com> richyjsm at gmail.com writes: > And who is it who uses this functionality? I use it but I agree it's easy to implement given the underlying bignum arithmetic. > It's useful in elementary number theory, sure, but I'd argue that if > there are going to be number theoretical functions in the core then > there are other things, like gcd(), that are far more deserving of > inclusion. Certainly xgcd should be in the math library or somewhere similar. > It comes up in the RSA cryptosystem, but if you're using > Python's pow for this then you're surely only writing a toy RSA > implementation, perhaps for educational purposes(?). Not necessarily. See for example http://trevp.net/tlslite From dickinsm at gmail.com Wed Sep 19 20:25:22 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 20 Sep 2007 00:25:22 -0000 Subject: Sets in Python In-Reply-To: <1190244370.741482.6540@y27g2000pre.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <1190239608.835359.51150@22g2000hsm.googlegroups.com> <1190244370.741482.6540@y27g2000pre.googlegroups.com> Message-ID: <1190247922.835055.31950@y42g2000hsy.googlegroups.com> On Sep 19, 7:26 pm, Karthik Gurusamy wrote: > If I did, a = [10, 20] and I did d[a]= 'foo', then a.append(30). > If dict complains key error on d[a] now, I won't be surprised. If I do > d[[10, 20, 30]], I will be surprised if it doesn't find the item. Of > course, in today's behavior the above is syntax error. It sounds as though you're proposing something like the following: >>> k = mylist([1, 2]) >>> d = {k : 'test'} >>> d[k] 'test' >>> k.append(3) >>> d[k] Traceback (most recent call last): File "", line 1, in KeyError: [1, 2, 3] So far, so good. But how do you explain the following to a confused newcomer? >>> d.keys() [[1, 2, 3]] >>> k in d.keys() True >>> k in d False >>> d[k] Traceback (most recent call last): File "", line 1, in KeyError: [1, 2, 3] In other words, to repeat Sion Arrowsmith's question, what would you expect d.keys() to return after a key of d has been modified? Mark From hniksic at xemacs.org Wed Sep 26 04:51:26 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 26 Sep 2007 10:51:26 +0200 Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> Message-ID: <87sl51lshd.fsf@mulj.homelinux.net> Duncan Booth writes: > I that's the point though: you can't write one implementation that has good > performance for all patterns of use An implementation of sorted dict using a balanced tree as the underlying data structure would give decent performance in all the mentioned use cases. For example, red-black trees search, insert, and delete in O(log n) time. From mail at microcorp.co.za Sat Sep 1 02:57:34 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 1 Sep 2007 08:57:34 +0200 Subject: list index() (OT) References: <1188456273.102334.48660@50g2000hsm.googlegroups.com><46d674c2$0$417$426a34cc@news.free.fr><1188496588.750629.208100@g4g2000hsf.googlegroups.com><1188497498.3468.60.camel@dot.uniqsys.com><021801c7eba2$ad429640$03000080@hendrik> <1cnfd31du01el95u70o8mjn9cb5r5aluiu@4ax.com> Message-ID: <007f01c7ec65$605e6700$03000080@hendrik> "Richie Hindle" wrote: > But - the word for someone who posts to the internet with the intention of > stirring up trouble derives from the word for what fishermen do, not from > the word for something that lives under a bridge. It derives from "trolling > for suckers" or "trolling for newbies". So am I right in asserting that there is a difference in pronunciation of the noun and the verb? He is a Troll - like the excellent frolic example He likes to Troll - rhymes with roll? - Hendrik From carsten at uniqsys.com Fri Sep 21 09:16:50 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 21 Sep 2007 09:16:50 -0400 Subject: __contains__() : Bug or Feature ??? In-Reply-To: <1190380085.770828.19400@o80g2000hse.googlegroups.com> References: <1190380085.770828.19400@o80g2000hse.googlegroups.com> Message-ID: <1190380610.3393.1.camel@dot.uniqsys.com> On Fri, 2007-09-21 at 13:08 +0000, sebastien.lannez at gmail.com wrote: > Hi everybody, > > I need to overload the operator in and let him > return an object Why do you think you need to do that? What's the underlying problem you're trying to solve? -- Carsten Haese http://informixdb.sourceforge.net From prudek at bvx.cz Mon Sep 10 09:45:38 2007 From: prudek at bvx.cz (Milos Prudek) Date: Mon, 10 Sep 2007 15:45:38 +0200 Subject: uninstall Message-ID: <200709101545.38785.prudek@bvx.cz> I run "make install" of Python 2.4.4 and now I discovered that I do not like the default placement of my install. The Makefile does not support an "uninstall" option. Is there a way to uninstall Python compiled from sources? -- Milos Prudek From blackmh at gmail.com Sun Sep 2 12:27:45 2007 From: blackmh at gmail.com (Kveldulv) Date: Sun, 02 Sep 2007 09:27:45 -0700 Subject: Glade + Python = No GUI Message-ID: <1188750465.530463.271750@22g2000hsm.googlegroups.com> I made simple GUI in Glade 3 (Ubuntu 7.04) consisting of only 2 buttons. When I run 2buttonsgui.py, no GUI pops out #!/usr/bin/env python import pygtk import gtk.glade class TwoButtonsGUI: def __init__(self): self.window = gtk.glade.XML("/home/myusername/Desktop/ 2buttons.glade", "window1") if __name__ == '__main__': TwoButtonsGUI() gtk.main() When interrupted, I get File "gui.py", line 11, in gtk.main() When GUI coded manually, all works. Thanks in advance From tdwdotnet at gmail.com Thu Sep 13 16:52:16 2007 From: tdwdotnet at gmail.com (Tim Williams) Date: Thu, 13 Sep 2007 21:52:16 +0100 Subject: extract text from log file using re In-Reply-To: References: Message-ID: <9afea2ac0709131352h2f30dac8vc8725e96d2ccf77f@mail.gmail.com> On 13/09/2007, Fabian Braennstroem wrote: > me again... I should describe it better: > the result should be an array with just: > > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 > 3.8545e-03 1.3315e-01 11:14:10 500 > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > > as field values. > > Fabian Braennstroem schrieb am 09/13/2007 09:09 PM: > > Hi, > > > > I would like to delete a region on a log file which has this > > kind of structure: > > > > > > #------flutest------------------------------------------------------------ > > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > reversed flow in 1 faces on pressure-outlet 35. > > > > Writing > > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.cas"... > > 5429199 mixed cells, zone 29, binary. > > 11187656 mixed interior faces, zone 30, binary. > > 20004 triangular wall faces, zone 31, binary. > > 1104 mixed velocity-inlet faces, zone 32, binary. > > 133638 triangular wall faces, zone 33, binary. > > 14529 triangular wall faces, zone 34, binary. > > 1350 mixed pressure-outlet faces, zone 35, binary. > > 11714 mixed wall faces, zone 36, binary. > > 1232141 nodes, binary. > > 1232141 node flags, binary. > > Done. > > > > > > Writing > > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.dat"... > > Done. > > > > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 > > 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 > > > > reversed flow in 2 faces on pressure-outlet 35. > > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > > > #------------------------------------------------------------------ > > > > I have a small script, which removes lines starting with > > '(re)versed', '(i)teration' and '(t)urbulent' and put the > > rest into an array: > > > > # -- plot residuals ---------------------------------------- > > import re > > filename="flutest" > > reversed_flow=re.compile('^\ re') > > turbulent_viscosity_ratio=re.compile('^\ tu') > > iteration=re.compile('^\ \ i') > > > > begin_of_res=re.compile('>\ \ \ i') > > end_of_res=re.compile('^\ ad') > > > > begin_of_writing=re.compile('^\Writing') > > end_of_writing=re.compile('^\Done') > > > > end_number=0 > > begin_number=0 > > > > > > n = 0 > > for line in open(filename).readlines(): > > n = n + 1 > > if begin_of_res.match(line): > > begin_number=n+1 > > print "Line Number (begin): " + str(n) > > > > if end_of_res.match(line): > > end_number=n > > print "Line Number (end): " + str(n) > > > > if begin_of_writing.match(line): > > begin_w=n+1 > > print "BeginWriting: " + str(n) > > print "HALLO" > > > > if end_of_writing.match(line): > > end_w=n+1 > > print "EndWriting: " +str(n) > > > > if n > end_number: > > end_number=n > > print "Line Number (end): " + str(end_number) > > > > > > > > > > > > n = 0 > > array = [] > > array_dummy = [] > > array_mapped = [] > > > > mapped = [] > > mappe = [] > > > > n = 0 > > for line in open(filename).readlines(): > > n = n + 1 > > if (begin_number <= n) and (end_number > n): > > # if (begin_w <= n) and (end_w > n): > > if not reversed_flow.match(line) and not > > iteration.match(line) and not > > turbulent_viscosity_ratio.match(line): > > m=(line.strip().split()) > > print m > > if len(m) > 0: > > # print len(m) > > laenge_liste=len(m) > > # print len(m) > > mappe.append(m) > > > > > > #--end plot > > residuals------------------------------------------------- > > > > This works fine ; except for the region with the writing > > information: > > > > #-----writing information > > ----------------------------------------- > > Writing "/home/fb/fluent-0500.cas"... > > 5429199 mixed cells, zone 29, binary. > > 11187656 mixed interior faces, zone 30, binary. > > 20004 triangular wall faces, zone 31, binary. > > 1104 mixed velocity-inlet faces, zone 32, binary. > > 133638 triangular wall faces, zone 33, binary. > > 14529 triangular wall faces, zone 34, binary. > > 1350 mixed pressure-outlet faces, zone 35, binary. > > 11714 mixed wall faces, zone 36, binary. > > 1232141 nodes, binary. > > 1232141 node flags, binary. > > Done. > > # -------end writing information ------------------------------- > > > > Does anyone know, how I can this 'writing' stuff too? The > > matchingIt occurs a lot :-( > > > > the result should be an array with just: > > > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 > 3.8545e-03 1.3315e-01 11:14:10 500 > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 Sometimes Python is so simple there is a tendancy to overthink the problem Based soley on the input and output in your example and not withstanding errors from the email itself word-wrapping yours and my text: >>> print '\r\n'.join([x.strip() for x in open('c:/flutest.txt') if 'e-0' in x]) 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 >>> HTH :) From jcd at sdf.lonestar.org Mon Sep 17 19:21:19 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 17 Sep 2007 19:21:19 -0400 Subject: adodb with mysql - connection string syntax for filepath In-Reply-To: <33dffc910709162342x49657895t938fb1f8af2834de@mail.gmail.com> References: <33dffc910709162342x49657895t938fb1f8af2834de@mail.gmail.com> Message-ID: <46EF0BEF.3070807@sdf.lonestar.org> Mridula Ramesh wrote: > Dear all, > > Hi. I am not very tech-savvy so please pardon me if this is a stupid > question: so far I have been googling for about 4 days to find help > for this, so now I am desperate! :) > > How do you use adodb with mysql to connect to a file that is on your > machine? > I'm not quite sure what you mean by this. MySQL won't connect you to a file on your machine. It will connect you to a database server, which will possibly access files on your machine, but could just as easily access an in-memory database, that isn't stored in any files. I've also never worked with adodb, but if you use MySQLdb, you do the following: import MySQLdb as db cur = db.connect(host='127.0.0.1', #or whatever your hosts address is user=username, passwd=password, db=database).cursor() cur.execute('SELECT * FROM table') cur.fetchall() If adodb is dbapi 2 compliant, it may be as simple as s/MySQLdb/adodb/ > Also, could you please recommend to me a good resource to learn more > about classes and modules from? i don't understand half of the _init_ > business that many sites mention. (This *is* something even a newbie > needs to learn, right?) > Try this chapter from Diving into Python: http://www.diveintopython.org/object_oriented_framework/defining_classes.html > Thank you! > > M.R.S. Cheers, Cliff From surekap at gmail.com Thu Sep 13 00:38:02 2007 From: surekap at gmail.com (Prateek) Date: Wed, 12 Sep 2007 21:38:02 -0700 Subject: Python Database Apps In-Reply-To: References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> <1189536987.259907.68650@e34g2000pro.googlegroups.com> <1189608814.932322.301950@22g2000hsm.googlegroups.com> Message-ID: <1189658282.646375.160150@19g2000hsx.googlegroups.com> On Sep 13, 4:55 am, Ed Leafe wrote: > On Sep 12, 2007, at 10:53 AM, darien.watk... at gmail.com wrote: > > > Thanks for ideas Ed. I am checking out dabo now. I do have a few > > questions about it. Packaging. Is it easy to package into a quick > > install for windows. The users are going to want to get too in > > depth. > > py2exe is your friend here. I know several developers who have used > this to distribute Dabo apps, so we could certainly help you get your > setup.py working. > > > Second, data sources. When I'm adding a data source to the > > window in class designer, it always picks up the one I created (which > > incidentally was a sample, my form for connection manager isn't > > working at the moment.) My idea is to have the the local sqlite > > database as the only viewable data source, and the server side only > > for syncing. So they logon, sync up, sync down, and view. I'm > > worried about having to get them to install python, dabo, and the app. > > The users would never see any of the Class Designer, connection > editor, or any of the other development tools. I would imagine that > you would need to code the sync parts by getting the current changed > data from the local SQLite database, creating a connection to the > server DB, doing the insert/update as needed, grabbing the latest > from the server, disconnecting from the server, and then updating the > local data. The user would probably need to do nothing more than > click a button to start running your code. > > As far as what the user must install, that's what will happen with > any Python solution. py2exe takes care of all of that, bundling > Python, Dabo, your database modules, and any other dependencies into > a single .exe file. You can then use something like Inno Setup to > create a basic Installer that will look and work like any other > Windows application installer. > > -- Ed Leafe > --http://leafe.com > --http://dabodev.com Have you checked out Brainwave? http://www.brainwavelive.com We provide a schema-free non-relational database bundled with an app server which is basically CherryPy with a few enhancements (rich JS widgets, Cheetah/Clearsilver templates). Free for non-commercial use. --Prateek Sureka From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 28 11:55:48 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 28 Sep 2007 17:55:48 +0200 Subject: Delete spaces In-Reply-To: <1190994234.526554.110870@y42g2000hsy.googlegroups.com> References: <1190994234.526554.110870@y42g2000hsy.googlegroups.com> Message-ID: <46fd23d7$0$28052$426a74cc@news.free.fr> koutoo at hotmail.com a ?crit : > If I have a text file that is delimited by spaces, spaces or tabs ? > how do I import it > and get to comma delimited? Here is a row of data from the text file: > > 1 1 10:55:14 2 65 8.5 > 1.4+1.1 2.5 Class-2 0 > I tried a few examples from the group and it didn't work, since the > file also has a header row and a row of seperators ( -------). The > lengths of each row is something like 130, so there are extra spaces > after the last value as well. I have tried joining and other things, > but I couldn't figure out how to get the values to come together. > Thanks. This should answer your question - but certainly not solve your problem (cf below): f = open('/path/to/file.txt'); file.readline(); # skip headers for line in f: # skip separators if line.startswith('---'): continue parts = filter(line.rstrip().split()) print ';'.join(parts) f.close() Now the problem is that, obviously, the position of a group of data in a line is meaningfull, so just filtering out spaces isn't the solution. Did you check that it's not really a tab-delimited file ? If yes, doing line.split('\t') might help. Or just trying with the csv module FWIW. My 2 cents... From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Sep 14 05:45:35 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 14 Sep 2007 11:45:35 +0200 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <5ksoaoF5am8cU1@mid.individual.net> <1189701793.466307.93210@g4g2000hsf.googlegroups.com> <5ktfjqF5ctrvU2@mid.individual.net> <46e98fd8$0$27757$426a34cc@news.free.fr> <5ktre7F5ig0vU1@mid.individual.net> <46ea3591$0$21741$426a34cc@news.free.fr> Message-ID: <5kv3hvF5mo3hU2@mid.individual.net> Bruno Desthuilliers wrote: > A method is a thin wrapper around a function, usually instanciated > and returned by the __get__ method [1] of the function itself when > the function is looked up as an attribute of a class or an > instance: > [...] That's interesting, thank you for the explanation. > They aren't, and you should perhaps read the manual - all this is > documented. Found it. :) Regards, Bj?rn -- BOFH excuse #144: Too few computrons available. From ebgssth at gmail.com Sat Sep 15 11:04:14 2007 From: ebgssth at gmail.com (js) Date: Sun, 16 Sep 2007 00:04:14 +0900 Subject: How to get headers in urllib2 response In-Reply-To: <1189863876.901048.114410@o80g2000hse.googlegroups.com> References: <1189863876.901048.114410@o80g2000hse.googlegroups.com> Message-ID: How about using httplib? http://docs.python.org/lib/httplib-examples.html HTTPResponse has getheaders() method, too. On 9/15/07, Johny wrote: > Can anyone provide an example how to find out the return code and > header from an urllib2 request? > For example > response = urllib2.urlopen('http://www.google.com').read().strip() > provides data > but I do not know if the return code was 200 or different. > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > From mail at timgolden.me.uk Thu Sep 6 10:20:51 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 06 Sep 2007 15:20:51 +0100 Subject: startswith( prefix[, start[, end]]) Query In-Reply-To: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> References: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> Message-ID: <46E00CC3.6020006@timgolden.me.uk> cjt22 at bath.ac.uk wrote: > Hi > > startswith( prefix[, start[, end]]) States: > > Return True if string starts with the prefix, otherwise return False. > prefix can also be a tuple of suffixes to look for. That particular aspect of the functionality (the multiple prefixes in a tuple) was only added Python 2.5. If you're using <= 2.4 you'll need to use "or" or some other approach, eg looping over a sequence of prefixes. TJG From hassen62 at voila.fr Fri Sep 21 19:52:46 2007 From: hassen62 at voila.fr (hassen62 at voila.fr) Date: Sat, 22 Sep 2007 01:52:46 +0200 (CEST) Subject: How I import xls file Message-ID: <16968966.390651190418766204.JavaMail.www@wwinf4604> Hi, I have installed xlrd for windows but I can't used it succesfully. If I have a file "file.xls", what lines I can write from python to import and visualize this file. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Sep 14 10:47:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Sep 2007 10:47:22 -0400 Subject: recursion In-Reply-To: References: Message-ID: Gigs_ wrote: > Steve Holden wrote: [...] >> >> regards >> Steve > >>> def factorial(n): > print "n =", n > if n==0: > return 1 > else: > return n * factorial(n-1) > > >>> factorial(3) > n = 3 > n = 2 > n = 1 > n = 0 > 6 > > > now i understand. but one question at the end this function return 1. how python > knows that it needs to multiply 1 with all recursive returns. (why python didnt > sum recursive return with 1?) > > > that will be all, thanks in advance Aah, that's the magic of recursion (not that it's really magic at all). When you call factorial(3), the function sees the value of n as 3. So the if condition is false, so it must execute the return statement. In order to do that it has to multiply n by the value of factorial n-1. So it makes a call to a *new copy* of factorial, and this one has the value 2 for n. The if statement again needs to execute the return statement, and before it can do that it needs the value of factorial n-1, so it makes a call to a *new copy* of factorial, and this one has the value 1 for n. The if statement again needs to execute the return statement, and before it can do that it needs the value of factorial n-1, so it makes a call to a *new copy* of factorial, and this one has the value 0 for n. [Are you detecting a pattern here?]. Finally *this* copy of factorial can immediately return the value of 1 to its caller, which then multiplies that by 1 and returns it ti *its caller, which multiplies it by 2 and returns that to *its* caller, when multiplies it by 3 and returns the result, 6. In other words, the computer builds a "stack" of partially-completed functions, and unwinds it when the innermost (topmost, whatever) finally sees that it can return a result without creating another stacked call to factorial. Hope this straightens it out for you, it's a bit of a head-twister when you first come across it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From aleax at mac.com Wed Sep 19 00:07:16 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 18 Sep 2007 21:07:16 -0700 Subject: Using pseudonyms References: <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> <46e97917$0$9014$426a74cc@news.free.fr> <1190013177.473529.167770@o80g2000hse.googlegroups.com> <46ee2d9d$0$26213$426a74cc@news.free.fr> <46ef893c$0$21882$426a34cc@news.free.fr> Message-ID: <1i4nmjz.z9983sibdq42N%aleax@mac.com> Aahz wrote: > For that matter, there are plenty of people who are better known by some > nickname that is not their legal name. Yep. For example, some people whose legal name is "Alessandro" (which no American is ever going to be able to spell right -- ONE L, TWO S's, NOT an X or a J instead, "DRO" ending rather than "DER", etc), might choose to avoid the hassle and go by "Alex" (just to make up a case...). Alex From kay.schluehr at gmx.net Sat Sep 22 09:58:57 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 22 Sep 2007 06:58:57 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <5lkbr8F8gic1U6@mid.uni-berlin.de> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> <1190454275.282176.90830@k79g2000hse.googlegroups.com> <5lkbr8F8gic1U6@mid.uni-berlin.de> Message-ID: <1190469537.393019.133070@k79g2000hse.googlegroups.com> On Sep 22, 1:15 pm, Marc 'BlackJack' Rintsch wrote: > On Sat, 22 Sep 2007 02:44:35 -0700, Kay Schluehr wrote: > > I checked out Io once and I disliked it. I expected Io's prototype OO > > being just a more flexible variant of class based OO but Io couples a > > prototype very closely to its offspring. When A produces B and A.f is > > modified after production of B also B.f is modified. A controls the > > state of B during the whole lifetime of B. I think parents shall not > > do this, not in real life and also not in programming language > > semantics. > > Well it's like Python: inherited slots (attributes) are looked up in the > ancestors. It should be easy to override `Object clone` in Io, so all > slots of the ancestor are shallow copied to the clone, but I guess this > might break existing code. At least for your own code you could introduce > a `realClone` slot. > > Ciao, > Marc 'BlackJack' Rintsch But in class based OO most relevant attributes are defined during object construction and they can't be simply changed by setting a class attribute. Later you often create new attributes as but on object level. You do not overuse the object/class relationship to broadcast changes to all objects. While you might override 'Object clone' I don't believe changing the way how the whole object model works is a good idea and since it happens on source level you will get also a performance hit. From ldo at geek-central.gen.new_zealand Sun Sep 9 01:16:05 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 09 Sep 2007 17:16:05 +1200 Subject: Python syntax wart Message-ID: The one thing I don't like about Python syntax is using backslashes to continue lines. Yes, you can avoid them if you can include parentheses somehow, but this isn't always possible. Possible: if ( quitting and len(client["to_write"]) == 0 and len(client["read"]) + client["to_read"] == 0 ) : close_client(client, "shutting down") #end if Not possible: for \ Link \ in \ GetEachRecord \ ( "links", ("from_episode",), "to_episode = %s", [EpisodeID], "order by when_created" ) \ : out.write \ ( "

Back to episode %d\n" % ( LinkToMe({"ep" : Link["from_episode"]}), Link["from_episode"] ) ) #end for From wdierkes at 5dollarwhitebox.org Mon Sep 24 00:03:19 2007 From: wdierkes at 5dollarwhitebox.org (BJ Dierkes) Date: Sun, 23 Sep 2007 23:03:19 -0500 Subject: Database Abstraction Layer And/Or ORM Message-ID: <6AF3EAAD-55CB-4A0D-9B87-35D5D641F779@5dollarwhitebox.org> Hello all, I am looking for opinions on preferred methods of Database Abstraction Layer or Object Relation Mapper (I'm using Python 2.5). I have found a number of options such as those listed here: http://wiki.python.org/moin/HigherLevelDatabaseProgramming I'm not looking for a holy war based on whether a DAL/ORM *should* be used, and/or if it is preferred over direct access to the database API layer. I understand that can be a lengthy discussion. I would just like to see if there is a common 'preferred choice' in the area. I am coding an application around SQLite, but need to keep the flexibility to allow the use of MySQL (or other). Thoughts? From wanpor at 126.com Sat Sep 15 09:55:25 2007 From: wanpor at 126.com (wanpor at 126.com) Date: Sat, 15 Sep 2007 21:55:25 +0800 (CST) Subject: how could change backcolor of console? Message-ID: <46EBE44D.00006D.20377@bj126app37.126.com> Hi,everyone: I am a c programmer,and want using Python instead of C I can change backcolor using C,like this: ?textbackground(color); How can I do in Python? Best regards ? ? ? ??? ? ? ? 07 ? ? ? ? ? ? ? ? ? ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjt22 at bath.ac.uk Thu Sep 6 10:09:12 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Thu, 06 Sep 2007 07:09:12 -0700 Subject: startswith( prefix[, start[, end]]) Query Message-ID: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> Hi startswith( prefix[, start[, end]]) States: Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of suffixes to look for. However when I try and add a tuple of suffixes I get the following error: Type Error: expected a character buffer object For example: file = f.readlines() for line in file: if line.startswith(("abc","df")) CODE It would generate the above error To overcome this problem, I am currently just joining individual startswith methods i.e. if line.startswith("if") or line.startswith("df") but know there must be a way to define all my suffixes in one tuple. Thanks in advance From dotancohen at gmail.com Sun Sep 9 20:13:52 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 10 Sep 2007 03:13:52 +0300 Subject: Modul (%) in python not like in C? In-Reply-To: <0W%Ei.14427$3x.11615@newssvr25.news.prodigy.net> References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> <46E4466C.2030303@sdf.lonestar.org> <0W%Ei.14427$3x.11615@newssvr25.news.prodigy.net> Message-ID: <880dece00709091713o604d9da4u701eca718c489005@mail.gmail.com> On 10/09/2007, Bryan Olson wrote: > Not according to the C standard: > > When integers are divided, the result of the / operator is > the algebraic quotient with any fractional part discarded.(87) > If the quotient a/b is representable, the expression > (a/b)*b + a%b shall equal a. > [...] > 87) This is often called ''truncation toward zero''. > > [International Standard ISO/IEC 9899:1999, Section 6.5.5 > Multiplicative operators, Paragraph 6 and footnote 87] This seems most logical to me. Turbo C is against the standard, then. > > while Python is always consistent and returns positive remainders. > > Technically: > > The modulo operator always yields a result with the same sign > as its second operand (or zero) > > [http://docs.python.org/ref/binary.html] > Again, logical. Dotan Cohen http://what-is-what.com http://gibberish.co.il From joshua at eeinternet.com Fri Sep 28 15:31:46 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Fri, 28 Sep 2007 11:31:46 -0800 Subject: GUI for viewing/editing python data structures? References: <18c1e6480709272340v13d36916r6d707d64759107cc@mail.gmail.com> Message-ID: On Thursday 27 September 2007 22:40, David wrote: > On 9/27/07, Joshua J. Kugler wrote: >> A while back, I seem to remember coming across a small program that could >> view and edit python data structures via a nice expanding tree view. I'm >> now in need of something like that (to verify data is imported correctly >> into a shelve file) and having a GUI would be much simpler than trying to >> wade through the output of str(d) or repr(d). >> >> I've tried googling with the obvious keywords (gui (view OR edit) python >> data structures) but t didn't get me anywhere. >> >> Pointers? >> > > non-gui alternatives: Try pprint module. Or output as yaml (external > library) into a text file. You could also output as XML (using > built-in python modules), save to file and then use Firefox or another > XML gui to inspect it. I haven't done the latter before but it should > work. I may give those a try. I was also looking at the editing aspect too. But that's a good start. Thanks. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From iclark at mail.ewu.edu Fri Sep 14 18:38:11 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Fri, 14 Sep 2007 15:38:11 -0700 Subject: subclass of integers In-Reply-To: References: <1189780201.692192.291010@k79g2000hse.googlegroups.com> Message-ID: Ian Clark wrote: > Mark Morss wrote: >> I would like to construct a class that includes both the integers and >> None. I desire that if x and y are elements of this class, and both >> are integers, then arithmetic operations between them, such as x+y, >> return the same result as integer addition. However if either x or y >> is None, these operations return None. >> >> (snip) >> >> I would very much appreciate anyone's help. > > My thought would be rather than trying to cram None into a subclass of > int, to use delegation instead... > > (snip) > > Ian A more robust implementation that accounts for ints/longs as well as implementing more operations... -----8<-------------------------------------------------- import operator class NoneInt(object): _LEFT = 1 _RIGHT = 2 def __init__(self, value): self.value = value def _get_arguments(self, other, direction=_LEFT): """ Given a direction (left or right), returns the left hand side and right hand side values. """ if direction == self._LEFT: lhs = self.value if isinstance(other, (int, long, type(None))): rhs = other else: rhs = other.value elif direction == self._RIGHT: rhs = self.value if isinstance(other, (int, long, type(None))): lhs = other else: lhs = other.value else: raise ValueError('direction must be either _LEFT or _RIGHT') return (lhs, rhs) def _operation(op, direction): """ Given a direction and an operation will return a function that calls the operation with the arguments in the correct order. """ def func(self, other): if not isinstance(other, (int, long, NoneInt, type(None))): fmt = "unsupported operand type(s) for %s: 'NoneInt' and '%s'" args = (op.__name__, other.__class__.__name__) raise TypeError(fmt % args) lhs, rhs = self._get_arguments(other, direction) if None in (lhs, rhs): return NoneInt(None) return NoneInt(op(lhs, rhs)) return func __add__ = _operation(operator.add, _LEFT) __radd__ = _operation(operator.add, _RIGHT) __sub__ = _operation(operator.sub, _LEFT) __rsub__ = _operation(operator.sub, _RIGHT) __div__ = _operation(operator.div, _LEFT) __rdiv__ = _operation(operator.div, _RIGHT) __mul__ = _operation(operator.mul, _LEFT) __rmul__ = _operation(operator.mul, _RIGHT) # ... etc def __eq__(self, other): lhs, rhs = self._get_arguments(other) return lhs == rhs def __nonzero__(self): return bool(self.value) def __str__(self): return 'NoneInt(%s)' % str(self.value) __repr__ = __str__ -----8<-------------------------------------------------- Ian From sajmikins at gmail.com Wed Sep 26 13:19:20 2007 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 26 Sep 2007 10:19:20 -0700 Subject: Matplotlib TkAgg WindowsXP ImportError Message-ID: <1190827160.282738.293770@k79g2000hse.googlegroups.com> Hello, I just installed Matplotlib (and NumPy) on a windows XP machine, and I'm getting the following traceback when I try to use the TkAgg backend. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib >>> matplotlib.use('TkAgg') >>> from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\matplotlib\backends \backend_tkagg.py", line 8, in import tkagg # Paint image to Tk photo blitter extension File "C:\Python25\lib\site-packages\matplotlib\backends\tkagg.py", line 1, in import _tkagg ImportError: DLL load failed: The specified module could not be found. >>> I found one old (2004) post http://mail.python.org/pipermail/python-list/2004-April/258963.html that seems to indicate that some sort version mismatch of the Tk/Tcl libraries may be to blame. But I don't know how to diagnose that or what to do about it. FWIW, I installed using matplotlib-0.90.1.win32-py2.5.exe and numpy-1.0.3.1.win32-py2.5.exe. Thanks in advance for any help. Sincerely, ~Simon From Summercoolness at gmail.com Sun Sep 16 13:28:30 2007 From: Summercoolness at gmail.com (Summercool) Date: Sun, 16 Sep 2007 17:28:30 -0000 Subject: where are the .pyc files? Message-ID: <1189963710.714191.74440@n39g2000hsh.googlegroups.com> so i have always heard of the .pyc files.... but for some reason i don't see them on the Windows platform... when i have a program called try.py and after running it for ages, i still don't have a try.pyc file in my folder even if i turn the "show hidden file" to on. From hat at se-162.se.wtb.tue.nl Wed Sep 5 04:09:21 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 05 Sep 2007 10:09:21 +0200 Subject: Calling a matlab script from python References: <1188978068.544030.158010@19g2000hsx.googlegroups.com> Message-ID: On 2007-09-05, n o s p a m p l e a s e wrote: > Suppose I have a matlab script mymatlab.m. How can I call this script > from a python script? use the mlabwrap module Albert From bscrivener42 at gmail.com Fri Sep 7 22:48:11 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Sat, 08 Sep 2007 02:48:11 -0000 Subject: Is a Borg rebellion possible? (a metaclass question) In-Reply-To: References: <1189168282.665210.260840@19g2000hsx.googlegroups.com> <1189180478.257790.60160@g4g2000hsf.googlegroups.com> Message-ID: <1189219691.136842.34900@57g2000hsv.googlegroups.com> On Sep 7, 1:53 pm, Steve Holden wrote: > All you really need is to create your SplinterBorgs with appropriate > group names, you don't neef subclasses at all: > Dang. With that subject heading I thought this was about some post- Singularity, Python-programmed cyborgs rising up to take over the universe. See, e.g. How To Survive A Robot Uprising I am officially misled! rd From steve at holdenweb.com Thu Sep 27 19:37:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 19:37:27 -0400 Subject: Python 3.0 migration plans? Message-ID: I wondered if a straw poll could get some idea of readers' thoughts about when they will be migrating to 3.0 on, so I used the new widget on Blogger to add a poll for that. I'd appreciate if if you would go to http://holdenweb.blogspot.com/ and register your vote on your intended migration timescale. Thanks! -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From steve at REMOVE-THIS-cybersource.com.au Wed Sep 19 22:17:09 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Sep 2007 02:17:09 -0000 Subject: Sets in Python References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> Message-ID: <13f3m15igkstq2e@corp.supernews.com> On Wed, 19 Sep 2007 20:58:03 +0000, Karthik Gurusamy wrote: > While it's easy to explain the behavior, I think the decision to dis- > allow mutable items as keys is a bit arbitrary. There is no need for > dict to recompute hash What??? Of course it does. How else can it look up the key? Because it (somehow) just recognizes that it has seen the key before? How? By magic? > (first of all, a user doesn't even need to know > if underneath 'hashing' is used -- the service is just a mapping between > one item to another item). The user doesn't need to know the mechanism, but the dict does. Dicts are implemented as hash tables. I suppose they could be implemented as something else (what? linear lists? some sort of tree?) but the same considerations must be made: the dict must be able to find keys it has seen before. How is the dict supposed to recognise the key if the key has changed? > Since we know hashing is used, all that is needed is, a well-defined way > to construct a hash out of a mutable. "Given a sequence, how to get a > hash" is the problem. Nonsense. That's not the problem. The problem is how to get exactly the same hash when the sequence has changed. In other words, if you have two mutable objects M1 and M2, then you expect: hash(M1) == hash(M2) if and only if M1 and M2 are equal hash(M1) != hash(M2) if M1 and M2 are unequal but also: if M1 mutates to become equal to M2, hash(M1) must remain the same while still being different from hash(M2). That means that hash() now is a non-deterministic function. hash([1,2,3]) will vary according to how the list [1,2,3] was constructed! Obviously something has to give, because not all of these things are mutually compatible. > If later the given sequence is different, that's > not the dict's problem. Data structures don't have problems. Programmers do. And language designers with sense build languages that minimize the programmers problems, not maximize them. > So if the list changes, it will result in a different hash and we will > get a hash-miss. I doubt this is in anyway less intuitive than dis- > allowing mutable items as keys. The choices for the language designer are: (1) Invent some sort of magical non-deterministic hash function which always does the Right Thing. (2) Allow the hash of mutable objects to change, which means you can use mutable objects as keys in dicts but if you change them, you can no longer find them in the dict. They'll still be there, using up memory, but you can't get to them. (3) Simply disallow mutable objects as keys. Alternative 1 is impossible, as we've seen, because the requirements for the Right Thing are not mutually compatible. Alternative (2) leads to hard-to-find, hard-to-diagnose bugs where you store objects in a dict only for them to mysteriously disappear later. Worse, it could lead to bugs like the following hypothetical: >>> M = [1, 2, 3] >>> D = {M: 'parrot'} # pretend this works >>> D {[1, 2, 3]: 'parrot'} >>> M.append(4) >>> D {[1, 2, 3, 4]: 'parrot'} >>> D[[1, 2, 3, 4]] Traceback (most recent call last): File "", line 1, in KeyError: [1, 2, 3, 4] Try explaining that one to programmers: they can SEE the key in the dict when they print it, but they can't get it or delete it because the hash has changed. Alternative 3 is easy to deal with: simply don't use mutable objects as keys. That's what Python does. Sure, the programmer sometimes needs to work around the lack (convert the list into a tuple, or a string, or pickle it, whatever...) which on rare occasions is hard to do, but at least there are no mysterious, hard to track down bugs. -- Steven. From horpner at yahoo.com Mon Sep 10 09:06:35 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 10 Sep 2007 13:06:35 GMT Subject: Checking if elements are empty References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> <46e2013a$0$7687$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On 2007-09-08, Wildemar Wildenburger wrote: > Lawrence D'Oliveiro wrote: >>>>> if y[0]: >>>> Not a good idea. >>> Why not? >> >> Because there is a situation where your version of the test >> will fail even if the first element of y is non-null. > > Such as? Seriously people, a little more verbosity wouldn't > hurt here. This isn't a mystery game. >>> if "": True ... >>> if 0: True ... >>> if []: True ... >>> if {}: True ... >>> if None: True ... That's may not be all the possibilities. Lots of Python objects can evaluate to false in a boolean context. -- Neil Cerutti The Pastor would appreciate it if the ladies of the congregation would lend him their electric girdles for the pancake breakfast next Sunday morning. --Church Bulletin Blooper From steve at holdenweb.com Fri Sep 28 15:54:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 15:54:48 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191008702.579795.141180@r29g2000hsg.googlegroups.com> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> <1191008702.579795.141180@r29g2000hsg.googlegroups.com> Message-ID: <46FD5C08.7070603@holdenweb.com> George Sakkis wrote: > On Sep 28, 3:29 pm, TheFlyingDutchman wrote: > >> One issue I have with this group and that I encountered many years ago >> in the Perl group is that there is no separate group >> comp.lang.python.beginner where you can ask questions without getting >> hit with RTFM! and the like. > > Which shows once again that you're trying to break the world record of > being wrong in as many sentences as possible: > > http://mail.python.org/mailman/listinfo/tutor > > You would do yourself (and others) a favor by migrating there for a > few weeks or months. > > George > Hopefully with a side dish of alt.attitude.adjustment. It's not that we don't want you. it's just that you don't seem to realize how annoying you can be. n the other hand, if you *do* realize how annoying you can be then please leave now and never come back ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From thomas at jollans.com Sat Sep 22 11:53:09 2007 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 22 Sep 2007 17:53:09 +0200 Subject: can I run pythons IDLE from a command line?? In-Reply-To: <1190475878.971841.253140@k79g2000hse.googlegroups.com> References: <1190475878.971841.253140@k79g2000hse.googlegroups.com> Message-ID: <200709221753.09357.thomas@jollans.com> On Saturday 22 September 2007, tedpottel at gmail.com wrote: > Hi, > Is their a version of pythons IDLE that will run in a dos command > line? > The reason is that I would like to be able to run python code > interactively from my parable by connecting to my desktop using remote > command line or a telnet program. The Python interpreter should do fine. If your PATH environment variable is set up correctly, just run "python", otherwise it's somewhere in your Python installation directory. -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key : v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 From bignose+hates-spam at benfinney.id.au Tue Sep 25 04:41:54 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 25 Sep 2007 18:41:54 +1000 Subject: obtaining multiple values from a function. References: <1190708155.683502.93040@r29g2000hsg.googlegroups.com> Message-ID: <87sl53m90t.fsf@benfinney.id.au> Shriphani writes: > If I have a function that loops over a few elements and is expected to > throw out a few tuples as the output, then what should I be using in > place of return ? If it makes sense for the set of results to be returned all at once, then return the object that collects them all together ? a list of tuples, for example. If, instead, it makes sense for the results to be iterated over, you can write a function that yields results one at a time, without necessarily knowing in advance what the entire set will be:: >>> def fib(max_result): ... """ Yield numbers in the Fibonacci sequence ... to a maximum value of max_result. """ ... prev_results = [0, 0] ... result = 1 ... while result < max_result: ... yield result ... prev_results = [prev_results[1], result] ... result = sum(prev_results) ... The function, when called, will return a generator object that you can either iterate over:: >>> fib_generator = fib(100) >>> for n in fib_generator: ... print n ... 1 1 2 3 5 8 13 21 34 55 89 or directly call its 'next' method to get one result at a time until it raises a 'StopIteration' exception:: >>> fib_generator = fib(5) >>> fib_generator.next() 1 >>> fib_generator.next() 1 >>> fib_generator.next() 2 >>> fib_generator.next() 3 >>> fib_generator.next() Traceback (most recent call last): File "", line 1, in ? StopIteration -- \ "I have one rule to live by: Don't make it worse." -- Hazel | `\ Woodcock | _o__) | Ben Finney From gagsl-py2 at yahoo.com.ar Tue Sep 25 23:12:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Sep 2007 00:12:58 -0300 Subject: Invoking python through C++: How to? References: <496954360709251010q159199a4h9dd2b0e2ecad7a01@mail.gmail.com> Message-ID: En Tue, 25 Sep 2007 14:10:49 -0300, Robert Dailey escribi?: > I have a python script that I would like to invoke through my C++ > application. Does anyone know of a trivial way of doing this? Right now > the > only idea I can come up with is using system("python myscript.py") in > C++. If you don't want to "share" objects between Python and C++, that's the simplest way. Or, look at the document "Extending and Embedding the Python Interpreter" -- Gabriel Genellina From mensanator at aol.com Sun Sep 23 01:39:08 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 22 Sep 2007 22:39:08 -0700 Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <1190517836.766461.29570@g4g2000hsf.googlegroups.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> <1190484589.890198.266430@y42g2000hsy.googlegroups.com> <13fbahtem90fp99@corp.supernews.com> <1190506229.092718.41690@g4g2000hsf.googlegroups.com> <7xps0achlg.fsf@ruckus.brouhaha.com> <1190517836.766461.29570@g4g2000hsf.googlegroups.com> Message-ID: <1190525948.525876.253420@57g2000hsv.googlegroups.com> On Sep 22, 10:23?pm, richy... at gmail.com wrote: > On Sep 22, 9:10 pm, Paul Rubin wrote: > > > Certainly xgcd should be in the math library or somewhere similar. > > It does feel odd to have modular exponentiation in the core but no > other number-theoretic stuff in core+libraries. Perhaps a proposal on > python-ideas is in order... Though it's not clear what else would be > useful; Greatest Common Denominator Least Common Multiple Modular Inverse Linear Congruence (all found in gmpy) > primality testing Also in gmpy. > and factoring Alas, not in gmpy. I work around that by using a custom version I made of factor.exe from the MIRACL library. Which, alas, doesn't work quite right and which I would think is beyond my ability to fix. But this can be fixed in the Python program I use to capture the factors. > are obvious candidates, but I > don't much fancy writing an MPQS factorization algorithm in Python. > Well okay, I take that back---I wouldn't mind *writing* it; I just > wouldn't expect to get much speed from *running* it. Miller-Rabin > probabilistic primality testing would be easy to implement though. > > Anyway, I'm getting way off-topic here... sorry. > > > > > Not necessarily. See for examplehttp://trevp.net/tlslite > > Interesting. Thanks for the link. > > Richard From gagsl-py2 at yahoo.com.ar Fri Sep 7 05:14:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Sep 2007 06:14:23 -0300 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> Message-ID: En Fri, 07 Sep 2007 05:07:03 -0300, gu escribi?: > after two days debugging my code, i've come to the point that the > problem was caused by an unexpected behaviour of python. or by lack of > some information about the program, of course! i've stripped down the > code to reproduce the problem: > > > a = {} > > for x in range(10): > for y in range(10): > a[x,y] = "0" > > copyOfA = a copyOfA is *NOT* a copy - it's just another name pointing to the SAME object as a. Python will never copy anything unless told explicitely. Read this -- Gabriel Genellina From horpner at yahoo.com Wed Sep 26 11:28:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 26 Sep 2007 15:28:53 GMT Subject: An Editor that Skips to the End of a Def References: <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: On 2007-09-26, Jason M Barnes wrote: > Off the top of my head, I can think of a few vim commands that > have come in handy. I can search through a webpage in Firefox > by using the same '/' search command that vim has. The > movement keys (h,j,k,l) are the same as in any paging program > I've ever used. Not to mention that I learned regexes by > learning 's/regex/replacement' first :-) Yup. A huge advantge of learning vi is how much it helps improve your nethack experience. ;) Ignorance was Emacs was an obstacle I had to overcome in order to get into the Lisp world, though. > That's my religion anyway ;-), but I thought this was a python > mailing list ;-) Vim has Python integration if you want to control it with Python scripts. Cool! Of course, Vim needs such a capability more than Emacs, which has the very cool elisp scripting language. I'm not so keen on Vim's built-in scripting language. -- Neil Cerutti From fakeaddress at nowhere.org Wed Sep 5 06:33:24 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 05 Sep 2007 03:33:24 -0700 Subject: creating really big lists In-Reply-To: <87ejhd2zzt.fsf@rudin.co.uk> References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> <87ejhd2zzt.fsf@rudin.co.uk> Message-ID: Paul Rudin wrote: > Dr writes: >> I would like to create a pretty big list of lists; a list 3,000,000 >> long, each entry containing 5 empty lists. My application will append >> data each of the 5 sublists, so they will be of varying lengths (so no >> arrays!). >> >> Does anyone know the most efficient way to do this? I have tried: >> >> list = [[[],[],[],[],[]] for _ in xrange(3000000)] >> >> but its not soooo fast. Is there a way to do this without looping? > > You can do: > > [[[],[],[],[],[]]] * 3000000 > > although I don't know if it performs any better than what you already > have. Actually, that produces list of 3000000 references to the same 5-element list. A reduced example: >>> lst = [[[],[],[],[],[]]] * 3 >>> lst[1][1].append(42) >>> print lst [[[], [42], [], [], []], [[], [42], [], [], []], [[], [42], [], [], []]] -- --Bryan From kyosohma at gmail.com Thu Sep 13 09:19:18 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 13 Sep 2007 06:19:18 -0700 Subject: wx.ToplevelWindow.SetIcon: Native MS Windows error dialog pops up in wxPython app, no exception raised, no stack trace In-Reply-To: References: Message-ID: <1189689558.938858.43970@g4g2000hsf.googlegroups.com> On Sep 13, 6:29 am, Laszlo Nagy wrote: > Hello, > > I wrote a small program that works uses wxPython. The same application > works on Linux and Windows. When I start it from MS Windows, I see this > error message appearing each time I open a window: > > --------------------------- > Warehouseclient Error > --------------------------- > Can't load image from file '': file does not exist. > --------------------------- > OK > --------------------------- > > The message box itself is a native MS Windows dialog. Otherwise the > program works fine, just here is this annoying message. There is no > exception raised in the Python program. Nothing printed on console. I > figured out that this happens only when I set the icon of the window > using this code: > > self.SetIcon(icon) > > However, the error dialog is not displayed right after the SetIcon call > and no exception is raised. The dialog is displayed after __init__ has > been called, and probably before EVT_SHOW gets called. Documentation of > SetIcon > (http://wxwidgets.org/manuals/stable/wx_wxtoplevelwindow.html#wxtoplev...) > says that it is safe to delete the icon after calling this function. Now > here are the wreid things: > > 1. The icon is displayed correctly in the left top corner, so where is > the error? > 2. The error message complains about a file. What has > wx.ToplevelFrame.SetIcon do with files? > > I'm using: Windows XP Professional, Python 2.5, wxPython 2.8 > > Thanks, > > Laszlo Normally I would recommend posting to the wxPython list, but it's down at the moment. Keep an eye on their website as I'm sure they'll let the community know when it's back up. In the meantime, I'd look at how the demo does the icon displaying. It looks like they created the icon they use using the img2py script which basically creates a python file representation of the image. See main.py of the Demo, line 1129. img2py is in the following default location: C:\Python24\Lib\site-packages\wx-2.8-msw-unicode\wxPython\tools Without seeing how you create the image, it's hard to troubleshoot, but I would guess that you have an absolute path that you're using in your script that is different than what the exe is looking for. Mike From istvan.albert at gmail.com Fri Sep 7 14:58:06 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 07 Sep 2007 18:58:06 -0000 Subject: Speed of Python In-Reply-To: References: Message-ID: <1189191486.253328.269220@50g2000hsm.googlegroups.com> On Sep 7, 12:42 pm, "wang frank" wrote: > Is my conclusion correct that Python is slower than matlab? There are ways to speed up code execution, but to see substantial improvement you'll need to use numpy and rework the code to operate on vectors/matrices rather than building the result one step at the time. This applies to Octave as well. See the example code at the end of the message. With that code computing 1 million logarithms showed the following tendency original => 648.972728 msec per pass optimized => 492.613773 msec per pass with numpy => 120.578616 msec per pass The "slowness of python in this example mainly comes from the function call (math.log) as it seems about 30% of the runtime is spent calling the function. import timeit setup = """ import math from numpy import arange, log size = 1000 """ code1 = """ #original code for i in range(size): for j in range(size): a = math.log(j+1) """ code2 = """ # minor improvements lead to 15% faster speed from math import log for i in xrange(size): for j in xrange(size): a = log(j+1) """ code3 = """ # applying via a universal function makes it 5 times faster for i in xrange(size): nums = arange( size ) a = log( nums + 1) """ N = 3 codes = [ code1, code2, code3 ] for stmt in codes: timer = timeit.Timer(stmt=stmt, setup=setup) msec = 1000.0 * timer.timeit(number=N)/N print "%f msec per pass" % msec From dandolls at yahoo.co.in Sat Sep 22 07:43:14 2007 From: dandolls at yahoo.co.in (Amit Kumar Saha) Date: Sat, 22 Sep 2007 17:13:14 +0530 Subject: Writing Object Data to Disk In-Reply-To: References: Message-ID: <1190461394.6587.4.camel@ubuntu-laptop> > > From: Lawrence D'Oliveiro > > In message , > > Amit Kumar > > Saha wrote: > > > > > I would like to know if "Pickling" the class object is the only > > way of > > > writing it to disk for persistent storage. > > > > Wouldn't it be better to use a language-independent data > > representation that > > wasn't tied to Python? Also tying your external data representation > > to your > > internal program structure (objects) makes it harder to change the > > program > > in future. Actually, language independence is really not a consideration here. I am happy at having it tied to Python :-) BTW, do we have something like array of objects here? -- Amit Kumar Saha me blogs@ http://amitksaha.blogspot.com URL:http://amitsaha.in.googlepages.com From bj_666 at gmx.net Sat Sep 22 02:39:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2007 06:39:17 GMT Subject: I could use some help making this Python code run faster using only Python code. References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> <1190394011.148384.106280@q3g2000prf.googlegroups.com> <1190417120.723579.267560@22g2000hsm.googlegroups.com> Message-ID: <5ljrklF8gic1U3@mid.uni-berlin.de> On Fri, 21 Sep 2007 16:25:20 -0700, Python Maniac wrote: > On Sep 21, 3:02 pm, "Matt McCredie" wrote: > >> Isn't D compiled to machine code? I would expect it to win hands down. >> That is, unless it is horribly unoptimized. >> >> > Well D code is compiled into machine code that runs via a VM. About which D are we talking here? Not digital mars' successor to C++, right!? Ciao, Marc 'BlackJack' Rintsch From zzbbaadd at aol.com Sat Sep 22 23:24:48 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Sat, 22 Sep 2007 20:24:48 -0700 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <874phou1pa.fsf@benfinney.id.au> Message-ID: <1190517888.875672.18650@50g2000hsm.googlegroups.com> On Sep 20, 8:47 pm, "W. Watson" wrote: > How about in the case of MS Win? > Try Wing IDE at http://www.wingware.com. It can run and debug programs and has a free version. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 17 10:59:14 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 17 Sep 2007 16:59:14 +0200 Subject: Python "with" In-Reply-To: <13et3kv409e355d@corp.supernews.com> References: <13et3kv409e355d@corp.supernews.com> Message-ID: <46ee9640$0$9002$426a74cc@news.free.fr> Grant Edwards a ?crit : > On 2007-09-17, Laurent Pointal wrote: > >> Note3: Its funny to see how Python users tries to change the language, >> does this occure with C, C++, Java, C# ? > > Yes. I remember somebody I worked with once who write a C > program using a whole pile of macros to make it look like BASIC: > > #define IF if ( > #define THEN ) { > #define ELSE } else { > #define ENDIF } > > and so on... FWIW and IIRC, one of the rationales for C preprocessor macros was to let Pascal programmers make C looks like Pascal !-) From maly.bzyczek at gmail.com Wed Sep 19 07:47:39 2007 From: maly.bzyczek at gmail.com (Bzyczek) Date: Wed, 19 Sep 2007 04:47:39 -0700 Subject: UTF-8 characters in doctest Message-ID: <1190202459.229197.297350@n39g2000hsh.googlegroups.com> Hello, I have problems with running doctests if I use czech national characters in UTF-8 encoding. I have Python script, which begin with encoding definition: # -*- coding: utf-8 -*- I have this function with doctest: def get_inventary_number(block): """ >>> t = u'''28. ?esk? kr?lovsk? insignie ... m?dirytina, grafika je zcela vy?ez?na z pap?ru - max. rozm?r ... 420?582 nezna?eno ... text: opis v lev?m medailonu: CAROL VI IMP.ELIS.CHR. AVG. P.P.''' >>> get_inventary_number(t) (u'nezna\xc4\x8deno', u'28. \xc4\x8cesk\xc3\xa9 kr\xc3\xa1lovsk \xc3\xa9 insignie\nm\xc4\x9bdirytina, grafika je zcela vy\xc5\x99ez \xc3\xa1na z pap\xc3\xadru \xe2\x80\x93 max. rozm\xc4\x9br \n420\xc3\x97582 \ntext: opis v lev\xc3\xa9m medailonu: CAROL VI IMP.ELIS.CHR. AVG. P.P.') """ m = RE_INVENTARNI_CISLO.search(block) if m: return m.group(1), block.replace(m.group(0), '') else: return None, block After running doctest.testmod() I get this error message: File "vizovice_03.py", line 417, in ? doctest.testmod() File "/usr/local/lib/python2.4/doctest.py", line 1841, in testmod for test in finder.find(m, name, globs=globs, extraglobs=extraglobs): File "/usr/local/lib/python2.4/doctest.py", line 851, in find self._find(tests, obj, name, module, source_lines, globs, {}) File "/usr/local/lib/python2.4/doctest.py", line 910, in _find globs, seen) File "/usr/local/lib/python2.4/doctest.py", line 895, in _find test = self._get_test(obj, name, module, globs, source_lines) File "/usr/local/lib/python2.4/doctest.py", line 985, in _get_test filename, lineno) File "/usr/local/lib/python2.4/doctest.py", line 602, in get_doctest return DocTest(self.get_examples(string, name), globs, File "/usr/local/lib/python2.4/doctest.py", line 616, in get_examples return [x for x in self.parse(string, name) File "/usr/local/lib/python2.4/doctest.py", line 577, in parse (source, options, want, exc_msg) = \ File "/usr/local/lib/python2.4/doctest.py", line 648, in _parse_example lineno + len(source_lines)) File "/usr/local/lib/python2.4/doctest.py", line 732, in _check_prefix raise ValueError('line %r of the docstring for %s has ' ValueError: line 17 of the docstring for __main__.get_inventary_number has inconsistent leading whitespace: 'm\xc4\x9bdirytina, grafika je zcela vy\xc5\x99ez\xc3\xa1na z pap\xc3\xadru \xe2\x80\x93 max. rozm \xc4\x9br' I try to fill expected output in docstring according to output from Python shell, from doctest (if I bypass it in docstring, doctest says me what he expect and what it get), I try to set variable t as t='some text' together t=u'some unicode text'. But everything fails. So my question is: Is it possible to run doctests with UTF-8 characters? And if your answer will be YES, tell me please how... Thank you for any advice. Regards Michal From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Sep 14 19:59:48 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 15 Sep 2007 01:59:48 +0200 Subject: Https conversation - debug? References: <1189799482.314951.238470@r34g2000hsd.googlegroups.com> Message-ID: <5l0ljkF5lfd3U1@mid.individual.net> Johny wrote: > Is there any good sniffer for https protocol? Yes. > How can be watched https conversation? As a matter of principle, with every working sniffer. I'd use wireshark's "follow TCP stream" function. Regards, Bj?rn -- BOFH excuse #198: Post-it Note Sludge leaked into the monitor. From slinkp at gmail.com Tue Sep 11 10:47:11 2007 From: slinkp at gmail.com (slinkp) Date: Tue, 11 Sep 2007 07:47:11 -0700 Subject: Python 2 releases after 2.6 Message-ID: <1189522031.823544.111670@k79g2000hse.googlegroups.com> This seems to be a bit of a FAQ (at least among worried Zope developers :-) ... What are the plans for Python 2 releases after Python 2.6 / Python 3 are released? First, in the 2006 State of Python, Guido said: """ # 2.7: likely; may contain some 3.0 backports # 2.9 is as far as we'll go (running out of digits :-) """ Then there's PEP 3000, which says: """ I expect that there will be parallel Python 2.x and 3.x releases for some time; the Python 2.x releases will continue for a longer time than the traditional 2.x.y bugfix releases. Typically, we stop releasing bugfix versions for 2.x once version 2.(x+1) has been released. But I expect there to be at least one or two new 2.x releases even after 3.0 (final) has been released, probably well into 3.1 or 3.2. This will to some extent depend on community demand for continued 2.x support, acceptance and stability of 3.0, and volunteer stamina. """ Has any of that changed (insofar as anyone can predict the future of course)? Thanks, -PW From erik at myemma.com Thu Sep 27 13:29:08 2007 From: erik at myemma.com (Erik Jones) Date: Thu, 27 Sep 2007 12:29:08 -0500 Subject: True of False In-Reply-To: <5m254hFatlbuU2@mid.uni-berlin.de> References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> <5m254hFatlbuU2@mid.uni-berlin.de> Message-ID: On Sep 27, 2007, at 11:47 AM, Marc 'BlackJack' Rintsch wrote: > On Thu, 27 Sep 2007 09:33:34 -0700, koutoo wrote: > >> I tried writing a true and false If statement and didn't get >> anything? I read some previous posts, but I must be missing >> something. I just tried something easy: >> >> a = ["a", "b", "c", "d", "e", "f"] >> >> if "c" in a == True: >> Print "Yes" >> >> When I run this, it runs, but nothing prints. What am I doing wrong? > > Wow that's odd: > > In [265]: a = list('abcdef') > > In [266]: a > Out[266]: ['a', 'b', 'c', 'd', 'e', 'f'] > > In [267]: 'c' in a > Out[267]: True > > In [268]: 'c' in a == True > Out[268]: False > > In [269]: ('c' in a) == True > Out[269]: True > > In [270]: 'c' in (a == True) > ---------------------------------------------------------------------- > ----- > Traceback (most recent > call last) > > /home/bj/ in () > > : argument of type 'bool' is not iterable > > > What's going on there? That is weird. Given 270, what's happening in 268. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From aisaac at american.edu Sun Sep 2 12:14:12 2007 From: aisaac at american.edu (Alan Isaac) Date: Sun, 02 Sep 2007 16:14:12 GMT Subject: create Powerpoint via com In-Reply-To: <1188500822.869925.194430@e9g2000prf.googlegroups.com> References: <1188500822.869925.194430@e9g2000prf.googlegroups.com> Message-ID: Well, my needs were very limited so the result is too, but in case someone else just needs to get started: http://econpy.googlecode.com/svn/trunk/utilities/mso.py Comments, suggestions, additions welcom. Alan Isaac From hatspin at gmail.com Thu Sep 13 06:37:58 2007 From: hatspin at gmail.com (hatspin at gmail.com) Date: Thu, 13 Sep 2007 10:37:58 -0000 Subject: Can You Program? Message-ID: <1189679878.271415.88700@w3g2000hsg.googlegroups.com> We are offering $2000 USD for the best website developed with www.hatspin.com Are you up to it?? From exhuma at gmail.com Fri Sep 7 04:24:40 2007 From: exhuma at gmail.com (exhuma.twn) Date: Fri, 07 Sep 2007 01:24:40 -0700 Subject: Changing data in an QAbstractListModel In-Reply-To: <1189118539.748092.250140@g4g2000hsf.googlegroups.com> References: <1189095176.973314.227720@r29g2000hsg.googlegroups.com> <1189118539.748092.250140@g4g2000hsf.googlegroups.com> Message-ID: <1189153480.760570.273800@r34g2000hsd.googlegroups.com> On Sep 7, 12:42 am, Jonathan Gardner wrote: > On Sep 6, 9:12 am, "exhuma.twn" wrote: > > > I defined a simple "update" method in the model which I call on > > certain events to fetch the new data in the DB. I tried to "emit" the > > "dataChanged()" signal of the Model without success. I don't know > > where I should get the two required "index" parameters from. > > > Any hints? > > Shouldn't the index method give you the indexes you need? Right... The update method now looks like this: def update(self): c = db_con.cursor() # SELECT only the most recent entry for each company c.execute("SELECT DISTINCT ON (unit_id) nom FROM unit ORDER BY unit_id, year DESC") for unit in c.fetchall(): self.__units.append( unit[0] ) c.close() si = self.index(0) se = self.index(len(self.__units)-1) self.emit(Signal("dataChanged()"), si, se) Still, nothing is happening when I call this method. Do I still need to handle the "dataChanged" signal somehow? Or does the ListView take care of this? From see.signature at no.spam Thu Sep 27 04:45:14 2007 From: see.signature at no.spam (Eric Brunel) Date: Thu, 27 Sep 2007 10:45:14 +0200 Subject: Tkinter / Tk 8.5 References: <13fm60kbhr28fa8@corp.supernews.com> Message-ID: On Thu, 27 Sep 2007 04:41:48 +0200, Scott David Daniels wrote: > Michal Bozon wrote: >> Today has been released a first beta of Tk 8.5, including a Ttk >> (tile) style engine, which makes possible the native look >> of widgets on MS platform, without having to install any extension. >> Is there a chance it will be included in 2.5.x, 2.6 or 3.0 ? > > This is just a guess, but: > The beta: no way for anything. > 2.5.x: also very unlikely > 2.6: unlikely unless release is _soon_ (first alpha of 2.6 is out) It won't be: tcl/tk development is quite slow. There have been several months between each 5 or 6 alpha release and between the last alpha and the beta. So don't expect the official release to come soon... > 3.0: much more likely, 3.0 won't be out for some time. This would be my guess too... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From koutoo at hotmail.com Wed Sep 26 16:25:11 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Wed, 26 Sep 2007 13:25:11 -0700 Subject: Delete values from a string using the index Message-ID: <1190838311.630506.64670@y42g2000hsy.googlegroups.com> How do I delete or remove values from a list or string using the index. If a = [1,2,3,4,5,6,7,8] and I want to get rid of 1 -5, how would I do that? Thanks. From openopt at ukr.net Sun Sep 2 02:21:21 2007 From: openopt at ukr.net (dmitrey) Date: Sat, 01 Sep 2007 23:21:21 -0700 Subject: howto compile recursively all *.py files to *.pyc (from a directory my_dir)? Message-ID: <1188714081.476816.310350@50g2000hsm.googlegroups.com> howto compile recursively all *.py files to *.pyc (from a directory my_dir)? Thank you in advance, D. From puredata at 11h11.com Sun Sep 30 22:56:02 2007 From: puredata at 11h11.com (patrick) Date: Sun, 30 Sep 2007 22:56:02 -0400 Subject: call for collaboration (python / freesound) Message-ID: <470061C2.4000009@11h11.com> hi, i have an idea, who doesn't have? the technologies required: gtk+ glade gobject Queue threading gstreamer (GNonLin) config here's the result of my week-end trying to understand how it's working: http://www.workinprogress.ca/pd/freesound.png the idea is to make a bridge from python to freesound: http://freesound.iua.upf.edu/ here's the class i used: http://www.leonard-ritter.com/freesound_integration there's some already solutions, but they are linked to an application: http://www.jokosher.org/screenshots http://trac.zeitherrschaft.org/aldrin/wiki/AldrinScreenshots if anybody is interested into "working / helping" on this project, i would be very happy. cheers guys, pat From piet at cs.uu.nl Tue Sep 11 04:22:58 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 11 Sep 2007 10:22:58 +0200 Subject: Checking if elements are empty References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> <46e2013a$0$7687$9b4e6d93@newsspool2.arcor-online.net> Message-ID: >>>>> "Chris Mellon" (CM) wrote: >CM> On 9/10/07, Neil Cerutti wrote: >>> Agreed; but I prefer 'if y[0] == ""', absent more context and >>> better names. >CM> Probably should use u"" if you're going to take that route, as this >CM> will fail spuriously if y[0] contains a unicode string that can't be >CM> implicitly converted to ascii. Personally, I prefer the boolean check >CM> and I'll let operations fail elsewhere if there's a type mismatch. >>> x=u"?" >>> x == "" False >>> -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From anuraguniyal at gmail.com Fri Sep 28 03:26:39 2007 From: anuraguniyal at gmail.com (Anurag) Date: Fri, 28 Sep 2007 07:26:39 -0000 Subject: marshal bug? In-Reply-To: References: <1190961020.258850.215130@g4g2000hsf.googlegroups.com> Message-ID: <1190964399.196877.299630@19g2000hsx.googlegroups.com> Thanks for the reply. It seems problem is due to """ Any string in Python can be "interned" or not, the difference being how/where the value is stored internally. The marshal module includes such information in its output. What you are doing is probably considered a misuse of the marshal module. I'd suggest using the pickle (or cPickle) modules instead. """ as mentioned by Gary Herron Now is there a easy way to by pass it (hack around it) I tried various options but all fail e.g. i= 123; marshal.dumps("%d"%123) != marshal.dumps("%d"%i) So maybe I have to change all my code to use pickle, which also consumes for memory per string. From ptmcg at austin.rr.com Wed Sep 26 22:20:49 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 26 Sep 2007 19:20:49 -0700 Subject: Using closures and partial functions to eliminate redundant code In-Reply-To: References: Message-ID: <1190859649.250300.74740@o80g2000hse.googlegroups.com> On Sep 26, 9:01 pm, Matthew Wilson wrote: > I wrote some code to create a user and update a user on a remote box by > sending emails to that remote box. When I was done, I realized that my > create_user function and my update_user function were effectively > identical except for different docstrings and a single different value > inside: > > ### VERSION ONE > > def create_user(username, userpassword, useremail): > "Send an email that will create a user in the remote system." > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject="CREATE", body=email_body) > > def update_user(username, userpassword, useremail): > "Send an email that will update a user's password in the remote system." > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject="UPDATE", body=email_body) > > ### END > > Then I came up with this approach to avoid all that redundant text: > > ### VERSION TWO > > def _f(mode): > > if mode not in ("create", "update"): > raise ValueError("mode must be create or update!") > > def _g(username, userpassword, useremail): > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject=mode.upper(), body=email_body) > > # Seems goofy, but other ways are there? > > docstrings = {'create': "Send an email that will create a user in the remote system.", > 'update': "Send an email that will update a user's password in the remote system."} > > _g.__doc__ = docstrings[mode] > > return _g > > # Then I created my functions like this: > > v2_create_user = _f("create") > v2_update_user = _f("update") > > ### END > > Finally, I came up with this approach: > > ### VERSION THREE > > from functools import partial > > def _h(mode, username, userpassword, useremail): > > if mode not in ("create", "update"): > raise ValueError("mode must be create or update!") > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject=mode.upper(), body=email_body) > > # I can't figure out how to set up the docstring on these. > > v3_create_user = partial(_h, mode="create") > v3_update_user = partial(_h, mode="update") > > ### END > > I'm interested to hear how other people deal with really similar code. > The similarity just bugs me. However, I wonder if using stuff like > closures or partial function application is needlessly showy. > > Also, I hope anyone here can help me figure out how to attach a > meaningful docstring for my version three code. > > Thanks in advance! > > Matt Haven't used partial yet, but I'm very interested. Of course, I think this will work just as well: def make_method(mode,docstring): def _inner(username, userpassword, useremail): # implementation of common routine code goes here # note: no need to clutter arg list with 'mode' now _inner.__name__ = mode + "_user" _inner.__doc__ = docstring return _inner Does this not work? v3_create_user = partial(_h, mode="create") v3_create_user.__doc__ = "Send an email that will create a user in the remote system." v3_update_user = partial(_h, mode="update") v3_update_user.__doc__ = "Send an email that will update a user's password in the remote system." -- Paul From deets at nospam.web.de Sun Sep 2 04:22:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 02 Sep 2007 10:22:55 +0200 Subject: How best to dynamically define methods (and functions)? In-Reply-To: References: Message-ID: <5jva77F1cgp6U1@mid.uni-berlin.de> Kenneth McDonald schrieb: > I can see an obvious but hacky way to define a Python function at > runtime. I can't see any obvious way to add a method to a class at > runtime (though I'm sure one could do just about anything by digging > into the metaclass stuff, which I will do if needed). But pointers to > cleaner or easier existing ways to do this would be most appreciated. > > In case it's of interest in the context of the question, I need to > define a largish set of functions (and similar methods) that define a > XML-type markup language. Most of these functions will just be of the form > > def fun(...): > return Node('fun', ...) > > so it'd definitely be nice to just create most of them automatically, > and only do the special cases by hand. Then don't do it that way, but use __getattr__. It will exactly do what you want: class Foo(object): def __getattr__(self, name): return Node(name, ....) def some_node(self): ... # hand coded stuff Diez From __peter__ at web.de Fri Sep 7 07:49:43 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 7 Sep 2007 13:49:43 +0200 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> Message-ID: Am Fri, 07 Sep 2007 10:40:47 +0000 schrieb Steven D'Aprano: > Python doesn't have any pointers. Thinking of python variables or "names" as pointers should get you a long way when trying to understand python's behaviour. As long as you keep in mind that python doesn't have pointers to pointers, and no pointer arithmetic either... Peter From steve at holdenweb.com Wed Sep 26 18:52:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 26 Sep 2007 18:52:17 -0400 Subject: setuptools without unexpected downloads In-Reply-To: <1190840682.716950.131830@r29g2000hsg.googlegroups.com> References: <87ejgmklep.fsf@benfinney.id.au><5lumarFae888U1@mid.uni-berlin.de> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> <5luv0iFaai82U1@mid.uni-berlin.de> <1190808836.056298.232640@57g2000hsv.googlegroups.com> <1190840682.716950.131830@r29g2000hsg.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Sep 26, 8:30 am, Steve Holden wrote: >> Fredrik Lundh wrote: >>> Paul Boddie wrote: >>>> P.S. Of course, the package maintainer problem manifests itself most >>>> prominently on Windows where you often see people asking for pre-built >>>> packages or installers. >>> for the record, I'd love to see a group of volunteers doing stuff like >>> this for Windows. there are plenty of volunteers that cover all major >>> Linux/*BSD distributions (tons of thanks to everyone involved in this!), >>> but as far as I can remember, nobody has ever volunteered to do the same >>> for Windows. >> I'd like to see something like this happen, too, and if a group of >> volunteers emerges I'll do what I can through the PSF to provide >> resources. Activities that benefit the whole community (or a large part >> of it) are, IMHO, well worth supporting. > > What would it entail to do this? Using py2exe + some installer (like > Inno Setup) to create an installer that basically copies/installs the > files into the site-packages folder or wherever the user chooses? If > that's all it is, I would think it would be fairly easy to create > these. Maybe I'm over-simplifying it though. > > What are a some examples of packages that need this? > MySQLdb and psycopg are two obvious examples I have had to grub around or produce my own installers for. There's generally some configuration work to do for packages that have been produced without considering Windows requirements, and ideally this will be fed back to the developers. I think you may be oversimplifying a little. Pure Python packages aren't too problematic, it's mostly the extension modules. Unless a copy of Visual Studio is available (and we *might* get some cooperation from Microsoft there) that means resorting to MingW, which isn't an easy environment to play with (in my occasional experience, anyway). There's going to be increasing demand for 64-bit implementations too. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From paddy3118 at googlemail.com Tue Sep 18 03:12:51 2007 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 18 Sep 2007 07:12:51 -0000 Subject: Getting indented code snippets into blogger Message-ID: <1190099571.872701.136360@57g2000hsv.googlegroups.com> I got tired of Bloggers inadequate comment editor so wrote this for transforming code snippets: ========================= ''' blogspace.py Turns leading spaces into HTML   tokens which shows as correct indentation on Blogger comment fields (and maybe other blogs). Donald. 'Paddy' McCarthy Sept 2011 ''' import fileinput, re for l in fileinput.input(): print re.sub(r'^(\s*)\s', lambda m: ' '*m.end(), l.rstrip()) ========================= If you find it works on other blogs then please reply.to this thread. - Paddy. From rjagodic at gmail.com Mon Sep 24 15:13:05 2007 From: rjagodic at gmail.com (Ratko) Date: Mon, 24 Sep 2007 19:13:05 -0000 Subject: Can a base class know if a method has been overridden? In-Reply-To: <46f7e8df$0$21052$426a74cc@news.free.fr> References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> <46f7d897$0$25150$426a74cc@news.free.fr> <1190648887.051630.168520@r29g2000hsg.googlegroups.com> <46f7e8df$0$21052$426a74cc@news.free.fr> Message-ID: <1190661185.359967.78610@w3g2000hsg.googlegroups.com> > Ok. The simplest solution, then, is simply to not implement the method > in the base class, ie: > > class EvtHandler: > def __init__(self): > if hasattr(self, 'onKey'): > register_for_key_events() > > #def onKey(self): > # pass > > class MyHandler(EvtHandler): > def onKey(self): > # do something here.... > > Another solution is to compare the functions wrapped by the methods: > > class EvtHandler: > def __init__(self): > onKey = getattr(self, 'onKey') > if onKey.im_func is EvtHandler.onKey.im_func: > register_for_key_events() > > def onKey(self): > pass > > class MyHandler(EvtHandler): > def onKey(self): > # do something here.... > > HTH The second solution works beautifully! Thank you very much. I was aware that not implementing the onKey method in the first place is the simplest solution but it's much cleaner to offer the methods in advance so that the user can see what is possible. Ratko From adonisv at REMOVETHISearthlink.net Wed Sep 5 21:21:57 2007 From: adonisv at REMOVETHISearthlink.net (Adonis Vargas) Date: Wed, 05 Sep 2007 21:21:57 -0400 Subject: How to do python and RESTful In-Reply-To: <1189022079.403495.175800@g4g2000hsf.googlegroups.com> References: <1189022079.403495.175800@g4g2000hsf.googlegroups.com> Message-ID: <13dulhpfo4gb236@corp.supernews.com> MarkyMarc wrote: > Hi all, > > I want to make a web service application in python and keywords are > RESTful, python and nice urls(urls mapped to python objects). > > I don't want a big framework but a nice small one, that can just do > the things I want. > > I have be looking at quixote, but is this uptodate? "plain" > mod_python, can this make url to http put,get,delete and post? > > Can some one here point me some where I can read about python and > RESTful or have some experiences with other? > > Any help is apricieted. > > Regards Marc > Here is a crude version, if you check out CherryPy there exists a RESTful module for it floating around. Plus you will get the power or CherryPy for your apps. I do not have the urls offhand but google should yeild exactly what you need. import BaseHTTPServer class REST(BaseHTTPServer.BaseHTTPRequestHandler): """ You can implement and do_* method you want """ def do_GET(self): self.wfile.write("get") def do_POST(self): self.wfile.write("post") def do_PUT(self): self.wfile.write("put") def do_DELETE(self): self.wfile.write("delete") def main(server_class=BaseHTTPServer.HTTPServer, handler_class=REST): server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.serve_forever() if __name__ == '__main__': main() Not fully tested but should get on your feet. Hope this helps. Adonis Vargas From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Sep 5 13:15:37 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 05 Sep 2007 19:15:37 +0200 Subject: So what exactly is a complex number? References: <451mq4-les.ln1@ozzie.tundraware.com> Message-ID: <5k86hqF2if1hU1@mid.individual.net> Grzegorz S?odkowicz wrote: > In fact, a proper vector in physics has 4 features: point of > application, magnitude, direction and sense. No -- a vector has the properties "magnitude" and direction. Although not everything that has magnitude and direction is a vector. It's very unusual to have a fixed point of application as a vector's property (at least I haven't seen it so far). That would complicate equality tests. > In case of a vector in two dimensions (a special case, which you > also fail to stress not to mention that you were talking about > space) the magnitude and sense can be described by one number Actually, the "magnitude" and "sense" you use here are redundant. What's the difference between a vector with magnitude "1" and sense "-", and magnitude "-1" and sense "+"? > and the direction as another. Represent the direction as one number? Only in a one-dimensional space. Regards, Bj?rn -- BOFH excuse #441: Hash table has woodworm From steve at REMOVE-THIS-cybersource.com.au Sun Sep 30 06:36:00 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Sep 2007 10:36:00 -0000 Subject: Can you please give me some advice? References: Message-ID: <13fuv0gh7342r27@corp.supernews.com> On Sun, 30 Sep 2007 19:22:07 +0900, Byung-Hee HWANG wrote: > Hi there, > > What is different between Ruby and Python? I am wondering what language > is really mine for work. Somebody tell me Ruby is clean or Python is > really easy! Anyway I will really make decision today what I have to > study from now on. What I make the decision is more difficult than to > know why I have to learn English. Yeah I do not like to learn English > because it is just very painful.. > > Can you please give me some advice? Hello World in Ruby (and a few other languages): http://www.oreillynet.com/ruby/blog/2005/12/hello_world.html More here: http://en.wikibooks.org/wiki/Programming:Ruby_Creating_Ruby_programs Hello World in Python: http://python.about.com/od/gettingstarted/ss/helloworld.htm A Python tutorial: http://docs.python.org/tut/ Sorry about the English. -- Steven From eric at abrahamsen.com Wed Sep 5 23:18:29 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Thu, 6 Sep 2007 11:18:29 +0800 Subject: ??????urllib post???????????? In-Reply-To: <20070906024041.GA6599@gmail.com> References: <1188993813.330662.174660@w3g2000hsg.googlegroups.com> <20070906024041.GA6599@gmail.com> Message-ID: <0665EB55-E95B-4DEA-876B-E6DD95228137@abrahamsen.com> It's in Chinese, so ASCII is no go. If anyone's interested in answering his question (he's trying to download a linked file using the post method from urllib tools, not something I know about) I can translate it, and pass the answer back to him once there's some kind of consensus. E On Sep 6, 2007, at 10:40 AM, O.R.Senthil Kumaran wrote: > If possible, please post your query in ASCII. > > -- > Senthil > > > * liangxuliang79 at gmail.com [2007-09-05 > 05:03:33]: > >> ????www.mmmppp333.com??????????http://ishare.iask.sina.com.cn/cgi- >> bin/ >> fileid.cgi?fileid=844050 >> ??????post fileid=844050???????? >> >> ????post????????????fileid=844050??????server??????????header?? >> header????local????location???? >> ?????????????????????????????????????????????? >> mp3????????????????????????????local???????????? >> mp3?????????????????????????????????? >> ?????????????????????????????? >> >> ??????????????python??urllib????????urllib??????????????????????? >> local????????????????local????????mp3???????? >> ????????????????mp3.?? >> >> ??post????????/download.php?? post???????? >> fileid=844050???????????????????????????????????????????????????? >> ????????????????????web?????????????????????? >> -- >> http://mail.python.org/mailman/listinfo/python-list > -- > O.R.Senthil Kumaran > http://uthcode.sarovar.org > -- > http://mail.python.org/mailman/listinfo/python-list From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 18 08:28:30 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 14:28:30 +0200 Subject: can Python be useful as functional? In-Reply-To: <1190106829.680544.159250@g4g2000hsf.googlegroups.com> References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> <46ef8895$0$21882$426a34cc@news.free.fr> <1190106829.680544.159250@g4g2000hsf.googlegroups.com> Message-ID: <46efc468$0$21740$426a34cc@news.free.fr> Kay Schluehr a ?crit : > On 18 Sep., 10:13, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Lorenzo Stella a ?crit : >> >>> Hi all, >>> I haven't experienced functional programming very much, but now I'm >>> trying to learn Haskell and I've learned that: 1) in functional >>> programming LISTS are fundmental; >> Not exactly. They are used quite a lot, yes, but that's also the case in >> other paradigms. What's important in functional programming is *functions*. > > Functional lists are not quite the same. They are actually recursive > datastructes. Linked lists, most of the time, yes. (snip) > In order to access an element you already need a recursive function > defintion ( unless you just want to examine the head or the tail > only ) and this makes functional programming and "consed" lists a > perfect match. Indeed. And that's also why some FP idioms don't translate directly in Python. > [...] > >> Strictly speaking, a language is functional if it has functions as first >> class objects. Period. > > No, not period and not strictly speaking. Ok, even on c.l.functional - where the above definition comes from BTW -, nobody really agree on the "correct" definition of functional !-) From alex at spam.me.not Mon Sep 24 15:30:54 2007 From: alex at spam.me.not (alex) Date: Mon, 24 Sep 2007 15:30:54 -0400 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <874phou1pa.fsf@benfinney.id.au> <46f3708c$0$32593$426a74cc@news.free.fr> Message-ID: W. Watson wrote: > Well, you may. Unfortunately, there are many NGs that do the opposite. > > Bruno Desthuilliers wrote: >> W. Watson a ?crit : >>> How about in the case of MS Win? >>> >>> Ben Finney wrote: >>>> >>>> (Please don't top-post. Instead, reply below each point to which >>>> you're responding, removing quoted text irrelevant to your response.) >>>> >> >> Wayne, may I second Ben on his suggestion to stop top-posting ? > *plonk* From steve at holdenweb.com Wed Sep 26 09:36:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 26 Sep 2007 09:36:31 -0400 Subject: Packaging and dependencies In-Reply-To: <87zlz9kfw3.fsf_-_@benfinney.id.au> References: <87ejgmklep.fsf@benfinney.id.au> <878x6ukkvq.fsf@benfinney.id.au> <5luhb0Faal8aU1@mid.uni-berlin.de> <87zlz9kfw3.fsf_-_@benfinney.id.au> Message-ID: Ben Finney wrote: > "Diez B. Roggisch" writes: > >> In my opinion, python is steering here to a direction like Java with >> it's classpath: scripts like workingenv and it's successor (forgot >> the name) provide hand-tailored environments for a specific >> application. > > What a silly waste of resources. So, if fifteen different programs > depend on library X, we'd have fifteen *separate* installations of > library X on the same machine? > You need to get your opinions up to date. Fifteen copies of a single library is nothing in terms of the code bloat that has happened over the last forty years, and most of that bloat is for programmer convenience, either in package development or distribution. While it's all very well to say that there should only ever be one true version of a library this requires that developers constrain themselves (sometimes in ways they consider unreasonable) to backwards compatibility for the entire lifetime of their code. > And when it comes time to upgrade library X because a security flaw is > discovered, each of the fifteen instances must be upgraded separately? > Yes. Better than upgrading a single library shared between fifteen applications and having two of them break. >> So maybe you should rather try and bundle your app in a way that it >> is self-contained. > > That entirely defeats the purpose of having packages declare > dependencies on each other. The whole point of re-usable library code > is to *avoid* having to re-bundle every dependency with every separate > application. > Agreed, but until we reach the ideal situation where everybody is using the same package dependency system what's your practical solution? "Self-contained" has the merit that nobody else's changes are going to bugger about with my application on a customer's system. The extra disk space is a small price to pay for that guarantee. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From musiccomposition at gmail.com Tue Sep 25 22:48:18 2007 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 26 Sep 2007 02:48:18 -0000 Subject: stopping a while True: with the keyboard In-Reply-To: References: Message-ID: <1190774898.348656.190760@y42g2000hsy.googlegroups.com> On Sep 25, 8:19 pm, patrick wrote: > hi all, > > i am looking for a way to break a while True: when pressing "s" on my > keyboard. how can i do this? > > pat Ctrl-C From ironfroggy at gmail.com Sat Sep 15 18:25:44 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sat, 15 Sep 2007 18:25:44 -0400 Subject: Needless copying in iterations? In-Reply-To: References: Message-ID: <76fd5acf0709151525j1eeea975p41d7cbdcc10ecb61@mail.gmail.com> This is a case where its up to the type involved. For example, xrange() slices the way you want but range() does not. Maybe a type would return for slices a proxy object that got the value by index or maybe it knows that it makes more sense to give you a copy because changes during the iteration should not be reflected in the iteration. It would be really easy to make a generic slicer. On 9/15/07, James Stroud wrote: > Hello all, > > I was staring at a segment of code that looked like this today: > > for something in stuff[x:y]: > whatever(something) > > and was wondering if the compiler really made a copy of the slice from > stuff as the code seems to suggest, or does it find some way to produce > an iterator without the need to make a copy (if stuff is a built-in > sequence type)? Or would it be more efficient to do the more clumsy (in > my opinion): > > for i in xrange(x, y): > whatever(stuff[i]) > > James > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From mridula.ccpl at gmail.com Fri Sep 21 03:03:30 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Fri, 21 Sep 2007 12:33:30 +0530 Subject: global name is not defined - but this is actually a function's name Message-ID: <33dffc910709210003h587be4c7tab0201a536cfdff@mail.gmail.com> thanks! that fixed it :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From e.expelliarmus at yahoo.com Tue Sep 25 05:23:47 2007 From: e.expelliarmus at yahoo.com (e.expelliarmus) Date: Tue, 25 Sep 2007 02:23:47 -0700 Subject: hacking,anti-hacking,registry tweaks,compter tricks Message-ID: <1190712227.677288.177740@g4g2000hsf.googlegroups.com> check this out buddies. kool website for: * hacking and anti hacking tricks * anti hackng tricks. * registry tweaks * orkut tricks * small virus * computer tricks and loads of different tricks... www.realm-of-tricks.blogspot.com www.registrydecoded.blogspot.com From jorgen.maillist at gmail.com Fri Sep 7 11:40:44 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Fri, 7 Sep 2007 17:40:44 +0200 Subject: How to determine the bool between the strings and ints? Message-ID: <11e49df10709070840ifb89ec1x852063669689fc05@mail.gmail.com> Hi All, I have a dictionary with settings. The settinfgs can be strings, ints or bools. I would like to write this list dynamically to disk in a big for loop, unfortunately the bools need to be written as 0 or 1 to the config with WriteInt, the integers also with WriteInt and the strings with a simple Write. The list is something like; options[A] = True options[B] = 1 options[C] = "Hello" I wanted to use isinstance to determine if it is a bool or an int or a string. However I am confused trying it out in the interactive editor; >>> a = False >>> if isinstance(a, bool): ... print "OK" ... OK >>> if isinstance(a, int): ... print "OK" ... OK >>> I don't get it. is the bool derived from 'int' in some way? What is the best way to check if the config I want to write is an int or a bool ? Regards, - Jorgen From hniksic at xemacs.org Sat Sep 8 05:38:35 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 08 Sep 2007 11:38:35 +0200 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> <7x3axq7a8a.fsf@ruckus.brouhaha.com> <7xodgejx3l.fsf@ruckus.brouhaha.com> <13e43ups034ld13@corp.supernews.com> Message-ID: <873axpxzs4.fsf@mulj.homelinux.net> Steven D'Aprano writes: > Should garbage-collecting 16 million strings really take 20+ > minutes? It shouldn't. For testing purposes I've created a set of 16 milion strings like this: s = set() for n in xrange(16000000): s.add('somerandomprefix' + str(n)) # prefix makes the strings a bit larger It takes maybe about 20 seconds to create the set. Quitting Python takes 4-5 seconds. This is stock Python 2.5.1. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 18 04:22:12 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 10:22:12 +0200 Subject: adding a static class to another class In-Reply-To: References: <46eef7d2$0$13879$426a74cc@news.free.fr> Message-ID: <46ef8aae$0$12885$426a74cc@news.free.fr> Nathan Harmston a ?crit : > Hi, > > I guess my description was a bit rubbish in retrospec, I dont even > think the title of my email made sense....it doesnt to me now: > > class Manager(object): > def __init__(self): > pass > def dosomething(self): > return "RESULTS" > > class Foo(object): > def __init__(self): > self.a = "NEE" > > What I m trying to do is end up with the following syntax: > > f = Foo() # instantiates a Foo object > g= Foo.objects.dosomething() # returns "RESULTS" > > The best way I ve found of doing this is overriding new > > class Foo(object): > def __new__(cls, *args, **kw): > cls.objects = Manager() > You're obviously overcomplexifying things here... # the canonical pythonic way class Foo(object): objects = Manager() def __init__(self): self.a = "NEE" # the monkeypatch way class Foo(object): def __init__(self): self.a = "NEE" Foo.objects = Manager() HTH From JeffHua at aol.com Fri Sep 7 11:57:25 2007 From: JeffHua at aol.com (JeffHua at aol.com) Date: Fri, 7 Sep 2007 11:57:25 EDT Subject: why should I learn python Message-ID: In a message dated 2007-9-7 7:50:32, bgates at microsoft.com writes: Tom Brown wrote: > On Thursday 06 September 2007 15:44, Torsten Bronger wrote: >> Hall?chen! >> >> Tom Brown writes: >> > [...] Python has been by far the easiest to develop in. Some >> > people might say it is not "real programming" because it is so >> > easy. >> >> I can't believe this. Have you really heard such a statement? > > Yes. I was told this by a C programmer. Something about doing it all > yourself and not using provided packages. I countered with something about > reinventing the wheel. :) Point this so-called "C Programmer" toward Henry Spencer's "Ten Commandments of C Programming". Note in particular rule 7: 7. Thou shalt study thy libraries and strive not to reinvent them without cause, that thy code may be short and readable and thy days pleasant and productive. You can find the whole list here: http://www.everything2.com/index.pl?node_id=783755 -- _http://mail.python.org/mailman/listinfo/python-list_ (http://mail.python.org/mailman/listinfo/python-list) _bgates at microsoft.com_ (mailto:bgates at microsoft.com) ? This seems like Bill Gates' email,does he also like Python? :-) ************************************** Get a sneak peek of the all-new AOL at http://discover.aol.com/memed/aolcom30tour -------------- next part -------------- An HTML attachment was scrubbed... URL: From gtcopeland at gmail.com Sat Sep 1 09:23:37 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: Sat, 01 Sep 2007 06:23:37 -0700 Subject: Fast socket write In-Reply-To: References: <1187744469.240933.149610@r23g2000prd.googlegroups.com> <46cba22b$1_1@news.chariot.net.au> <1187787707.377952.322280@57g2000hsv.googlegroups.com> Message-ID: <1188653017.937988.189010@o80g2000hse.googlegroups.com> On Aug 22, 8:30 am, paul wrote: > Greg Copeland schrieb:> On Aug 21, 9:40 pm, Bikal KC wrote: > >> Greg Copeland wrote: > >>> I'm having a brain cramp right now. I can't see to recall the name of > >> Is your cramp gone now ? :P > > > I wish. If anyone can remember the name of this module I'd realy > > appreciate it. > > http://tautology.org/software/python-modules/sendfileprobably... That's it. Thanks guys! Greg From deets at nospam.web.de Sat Sep 22 13:56:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Sep 2007 19:56:54 +0200 Subject: Who can develop the following Python script into working application ? In-Reply-To: References: <1190334828.210230.293980@50g2000hsm.googlegroups.com> <1190372423.768184.60080@19g2000hsx.googlegroups.com> <5lho31F84jgjU1@mid.uni-berlin.de> <1190419744.390216.19040@w3g2000hsg.googlegroups.com> <5lk9e0F8leeeU1@mid.uni-berlin.de> Message-ID: <5ll3c1F7k6d3U2@mid.uni-berlin.de> Andrey Khavryuchenko schrieb: > DBR> And as you said yourself: > > DBR> """ > DBR> Frankly speaking I would prefer to pay for your kind assistance > DBR> as it may take me to much time to learn some Python and understand the > DBR> following script. > DBR> """ > > DBR> Now, again: http://www.guru.com/ There you can get devlopers for > DBR> money. So what again is your problem? > > Actually, I am a python (and django) developer, looking for a contract, > owning Nokia 770 and contacted original poster with no response. Well, I presume the above quoted wasn't exactly true - in the end, the whole attitude of the OP smelled after "I want you to do work for me for free that I'm unwilling to bother myself with - as it would mean putting effort into it." Diez From gslindstrom at gmail.com Tue Sep 18 15:09:56 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Tue, 18 Sep 2007 14:09:56 -0500 Subject: Newbie question Message-ID: > > I see. It's so hard to imagine the world of python than from VB. > It's like looking at VB is in 2 dimensions, where with Python, it's > more 3D. The code is so simple, yet it's hard for me to envision how > to do something so simple. I guess it's because the rules or the way > of looking at things in Python, things can be stripped down to the > bare bones and in so many ways. Thanks. > > Kou Indeed. A common phrase you will here around here is "reset your mind". Python, like most languages, has it's own way of looking at the world. You may want to look at the tutors list, too (tutor at python.org). You'll like it there (I do). --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From mridula.ccpl at gmail.com Tue Sep 25 01:50:01 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Tue, 25 Sep 2007 11:20:01 +0530 Subject: calling the function of one class from another class In-Reply-To: <33dffc910709220024l74b14267v93564df10f5af9a6@mail.gmail.com> References: <33dffc910709220024l74b14267v93564df10f5af9a6@mail.gmail.com> Message-ID: <33dffc910709242250n6d39836fo7704f879980806e9@mail.gmail.com> thanks! ... sorry, i lacked access to the internet for a bit there... um, no, i'm not trying to write in java style in python, because i don't even know java!! i tried the "self" thing but that wasnt enough. I had to (as Furkan Kuru said) use a new instance of that class and only then call the function - that worked fine. so a big belated thanks, everyone! On 22/09/2007, Mridula Ramesh wrote: > > hi. > > i currently have code structured like this: > > classA(): > > def __init__(): > > .............. > > .............. > > > > def fnc1(): > > .................... > > .................... > > > > > > classB(): > > def __init__(): > > ........................ > > ........................ > > classA.fnc1() #this is where i get an error > > > > TypeError: unbound method fnc1() must be called with classA instance as > first argument (got nothing instead) > > when i do fnc1(classA) i get: > > NameError: global name 'fnc1' is not defined > > am i violating some programming rule by trying to call fnc1 in classB? i > am only now learning OO alongside python, so i'm not sure! also, can someone > please tell me where to go for more articles on the classes and functions > and calling them from other places? > > thanks a lot! > > mridula. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at jmcneil.net Sat Sep 8 21:25:37 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Sat, 8 Sep 2007 21:25:37 -0400 Subject: help - error when trying to call super class method In-Reply-To: <584090.28836.qm@web51105.mail.re2.yahoo.com> References: <584090.28836.qm@web51105.mail.re2.yahoo.com> Message-ID: <82d28c40709081825l2da03767ie8e6c8d58b750b88@mail.gmail.com> You shouldn't even need the call to super in that method, a simple 'len(self)' ought to be sufficient. Note that using the list object's append method is going to be much more efficient than handling it yourself anyways. There are a few problems in your call to super. First, it's a callable - it doesn't work like the Java equivalent. Next, as the superclass of Stackx is list, and there is no 'len' attribute on list, you'll bomb with an AttributeError. Lastly, you'll also generate an AttributeError when you increment 'my_len.' Here's a quick example using 'super.' class X(object): def meth(self): print "Hello" class Y(X): def meth(self): super(Y, self).meth() Y().meth() $ python test.py Hello For a bit more information on the use of super, check out http://docs.python.org/lib/built-in-funcs.html. Lastly, super will only work with new-style classes (which yours is, due to the subclass of list). -Jeff On 9/8/07, dontknowwhy88 wrote: > > > I am trying to extend list class to build a stack class -- see code > below--- > but I got an error when I try to call len method from list class here.. > why? > Thanks in advance! > --------------------- > > class Stackx(list): > > def push(self,x): > indx= super.len(x) > self.insert(my_len+1,x) > > def pop(self): > return self[-1] > > def test(): > > myStack = Stackx([1, 2 ,3 ,4]) > print myStack > myStack.push(9) > print myStack > print myStack.pop() > > > if __name__=='__main__': > test() > > > ''' > > Traceback (most recent call last): > File "C:\Python25\Stack2.py", line 20, in > test() > File "C:\Python25\Stack2.py", line 14, in test > myStack.push(9) > File "C:\Python25\Stack2.py", line 4, in push > indx= super.len(x) > AttributeError: type object 'super' has no attribute 'len' > ''' > > ------------------------------ > Be a better Heartthrob. Get better relationship answers > from > someone who knows. > Yahoo! Answers - Check it out. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Sep 28 12:30:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Sep 2007 18:30:57 +0200 Subject: Python 3.0 migration plans? References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> Message-ID: <5m4oi1Fbic8sU1@mid.uni-berlin.de> > You said it was a most basic language feature. I still haven't heard > anything that leads me to believe that statement is correct. What > languages implemented decorators as a most basic language feature? I was talking about Python, the programming language that is discussed in this NG. > Python didn't have them for over a decade so it doesn't qualify. Says who? For further comments, see below. >> >> >> Maybe you should start using python more and _then_ start discussions >> >> about it's features, when you have good grounds and can provide viable >> >> alternatives? But I guess that's a wish that won't be granted.... >> >> > static and abstract keywords would seem to be very viable >> > alternatives. Viable enough that several language designers used them. >> >> As I said - you don't get it. The decorators (in conjunction with the >> descriptor protocol - ever heard of that?) are very powerful yet lead as >> an artifact to simple, declarative implementations of features you like, >> namely static and abstract methods. > > You said I had to provide a viable alternative. I did that. I haven't > heard of the descriptor protocol. Where did you do provide that alternative? > One of the problems with "getting" decorators is that they are not in > older books at all and newer books like Beginning Python from Novice > to Professional (c) 2005 Magnus Lie Hetland, that I own, devote almost > nothing to them. Out of 640 pages they are only mentioned > in one paragraph that is in a section titled "Static Methods and Class > Methods",(and followed by a class example with @staticmethod and > @classmethod). > > So it seems like Magnus Lie Hetland didn't think they were very > important and he had Professional in his book title. I consider "core features of a language" the features that are part of the specification and implementation. Neither do I care if there is anecdotal evidence of prior usage in other languages, nor who or who not thinks they are important enough to be dealt with in a book. And above all, I don't consider the time things have been around _without_ any feature as proof of their irrelevance - or do you consider cars being not core to western culture because they only have been around about 100 years, whereas horses have been there for thousands of years? Happy riding, cowboy! Python 2.4 has been released in 2003, btw - so decorators are around for 4 years now. So unless you come up with a definition of "core feature of a language" that someone respectable in the CS-community wrote that features "time being around" or "random book authors consider worthy" or "persons lacking the motivation to really dig into do finally get it", I consider your definition worthless. Agreed? >> >> And as you seem being so reluctant to let new features creep into the >> language, the introduction of new keywords you like? > > I'm not against additions on principle. > >> >> Besides, those 'several language designers' seem to think that the >> introduction of keywords isn't enough, but a general purpose annotation >> scheme seems to be viable - or how do you explain e.g. JDK 1.5 >> Annotations? > > I certainly wouldn't call them a basic language feature. Java 1.0 came > out in January 1996, Java 1.5 in September 2004. It doesn't appear > that the language designer of Java, James Gosling, is still at the > wheel or BDFL. But yes, Java is showing signs of "complexity creep". > You'll be happy to know that I really dislike the C++ template syntax > and Java has decided to add something similar. Again, your anecdotal language feature definition is nonsense. By the way, considering generics and C++-templates as "something similar" shows the inclined beholder that there are other languages out there you don't really understand. Diez From aleax at mac.com Wed Sep 12 11:29:55 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 12 Sep 2007 08:29:55 -0700 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> Message-ID: <1i4bjb8.63ihk49vs6c8N%aleax@mac.com> Duncan Booth wrote: ... > As for omitting 'self' from method definitions, at first site you might > think the compiler could just decide that any 'def' directly inside a > class could silently insert 'self' as an additional argument. This > doesn't work though because not everything defined in a class has to be > an instance method: static methods don't have a self parameter at all, > class methods traditionally use 'cls' instead of 'self' as the name of > the first parameter and it is also possible to define a function inside > a class block and use it as a function. e.g. Actually you could do the "magic first-parameter insertion" just when returning a bound or unbound method object in the function's __get__ special method, and that would cover all of the technical issues you raise. E.g.: > class Weird: > def factory(arg): > """Returns a function based on its argument""" > > foo = factory("foo") > bar = factory("bar") > del factory > > When factory is called, it is a simple function not a method. If it had Sure, that's because the function object itself is called, not a bound or unbound method object -- indeed. factory.__get__ never gets called here. > class C: > def method(self): pass > > and > > def foo(self): pass > class C: pass > C.method = foo > > both of these result in effectively the same class (although the second > one has a different name for the method in tracebacks). And exactly the same would occur if the self argument was omitted from the signature and magically inserted when __get__ does its job. > That consistency really is important. Whenever I see a 'def' I know > exactly what parameters the resulting function will take regardless of > the context. And this non-strictly-technical issue is the only "true" one. > Another area to consider is what happens when I do: > > foo = FooClass() > > foo.bar(x) > # versus > f = foo.bar > f(x) > > Both of these work in exactly the same way in Python: the self parameter And so they would with the "__get__ does magic" rule, NP. > My point here is that in Python the magic is clearly defined and > overridable (so we can have static or class methods that act > differently). And so it would be with that rule, since staticmethod &c create different descriptor objects. Really, the one and only true issue is that the Python community doesn't like "magic". It would be perfectly feasible, we just don't wanna:-). Alex From cai.haibin at gmail.com Wed Sep 12 05:07:39 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 12 Sep 2007 09:07:39 -0000 Subject: setattr vs readonly property Message-ID: <1189588059.059818.301090@y42g2000hsy.googlegroups.com> hi, My main purpose for using setattr(object, attr, value) for assign values from a dict that has some keys that may not be present on some object's attibute, which makes it work for me. My problem is dealing with read only attribute like sample_attribute = property(f_get=_get_sample_attribute). what approach should I use? Or is my first approach In the first place right? Thanks james From steve at holdenweb.com Thu Sep 6 06:57:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Sep 2007 03:57:20 -0700 Subject: SQLite and coercing to Unicode - please help. In-Reply-To: <46dfcbea$0$89178$7b0f0fd3@mistral.news.newnet.co.uk> References: <46dfcbea$0$89178$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: special_dragonfly wrote: > Hello! > First, the problem: the program below falls over with the following error: > TypeError: coercing to Unicode: need string or buffer, NoneType found. > and gives the following line: > "' WHERE secBoardId='"+Values[0]+"'" > My first thought was that Values[0] was containing nothing at all, that > would allow a NoneType to be found, but it has data in that position of the > list - you'll see below. > So I thought that Values[0] was 'losing' its type somewhere, so I checked it > just by having the program print out type(Values[0]), it says it's a > string - also seen below. > So given it's not a NoneType and it's a string, I don't understand why I'm > getting the error. I tried forcing it to a particular type (I think that's > the right word), so I put lines like: > Values[0]=unicode(Values[0]) or > WHERE ... ='"str(Values[0]+"'" > but neither worked. > I've put my code below, I'm sorry it's so long, I've commented the line > where it's falling over. > If it's useful, I am using Python 2.5.1, ElementTree 1.2.6 and pySQLite > 2.3.5 > If this is a silly mistake ( one where RTFM is a valid response, can you > point me at the place where I can get the answer please?), otherwise any > help is greatly appreciated as I'm out of ideas. :( > Dominic > OK, the first problem is that you appear to be obsessing about Values[0] when there doesn't appear to be any evidence that value in particular is causing the problem. The line number being reported is simply that of the last line in a single long statement, and the issue could be anywhere in that statement. Sorry, you just have to know (or guess) that, it's not a particularly admirable feature of Python. In point of fact it is the None values that are causing the problem: $ /usr/bin/python Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> "a string"+None Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'NoneType' objects >>> u"a string"+None Traceback (most recent call last): File "", line 1, in TypeError: coercing to Unicode: need string or buffer, NoneType found >>> The XML values you are retrieving will be Unicode strings, but you are mixing them with plain string values, hence the (somewhat unhelpful) error message.. Secondly, you are trying to construct a SQL UPDATE statement yourself, instead of parameterising it like you did your INSERT statement. This is also usually asking for trouble, and is vulnerable to SQL injection errors (use Google if you don't know what they are). Thirdly, I'm not quite sure why you are using a list for the values, and another one for the Elements, when it would seems to make more sense to use a named variable for the former and just use the necessary string literals for the latter. What's the advantage of using try: branch=dom.getiterator(Elements[1]) Values.append(branch[0].text) # currencyID except: Values.append(" "*3) when you could just as easily say try: branch = dom.getiterator("currencyID") currencyID = branch[0].text except (..., ..., ...): # see below currencyID = " " The usual shorthand for (Values[0],Values[1],Values[2],Values[3],Values[4],Values[5],\ Values[6],Values[7],Values[8],Values[9],Values[10],Values[11],\ Values[12],Values[13],Values[14]) would, by the way, be tuple(Values) Note also that your INSERT statement assumes a specific ordering to the columns, which is asking for trouble when the database goes into production, as a DBA might re-order the fields during a reorganization or restructuring of the data, and then your code will break. Finally, and almost completely irrelevant to the issue at hand, all those "except" clauses will catch *absolutely any error* that may occur in your code, which is almost always a bad idea, since this behavior will mask certain errors that you really want to know about. The XML analysis code is frankly pretty horrible, but we can address that issue once you start to get some results. Sorry to bash what could well be your first significant program in Python, but my main interest is in setting you off down the right path. It will save time and grief in the end. Hope this has helped. regards Steve > > The output: > At top of function: GBP/PLUS-ofn-GB00B12T7004 > Values list contains: ['GBP/PLUS-ofn-GB00B12T7004', u'GBP', u'GB00B12T7004 > ', u'All Star Minerals plc ', 'ASMO', 'DE', 'PLUS', > u'B12T700', u' ', u'A', None, None, None, '000000000000000000', '0', > '0'] > > Type of Values[0] is: > > The code: > def dealwithSecBRep(text_buffer): > # text_buffer contains a sequential string of xml > Elements=['secBoardId','currencyId','issuerId','secName','secShortName','secClassId',\ > 'sectorId','isin','issueDate','inheritedState','bidPrice','offerPrice','midPrice',\ > 'standardMarketSize','openPrice','closePrice'] > Values=[] > dom=get_a_document(text_buffer) # this function returns an xml document. > branch=dom.getiterator(Elements[0]) > Values.append(GetUniqueId(branch[0])) # Combo of secCode and secBoardId > print "At top of function:",Values[0] > sql=cursor.execute('SELECT*FROM SecB WHERE > secBoardId='+"'"+Values[0]+"'").fetchall() > SQL2=sql > flag=0 > if len(sql)>0: > #Prior database exists > try: > branch=dom.getiterator(Elements[1]) > Values.append(branch[0].text) # currencyID > except: > value=GetFromDB('currencyCode',text_buffer) > Values.append(value) > try: > branch=dom.getiterator(Elements[2]) > Values.append(branch[0].text) # issuerName > except: > value=GetFromDB('issuerName',text_buffer) > Values.append(value) [other horrible code elided ...] > try: > branch=dom.getiterator(Elements[15]) > value=string.ljust(string.rjust(branch[0][0].text,10,"0"),18,"0") > Values.append(branch[0].text) # Stock Close > except: > Values.append("0") # Stock Open > flag=1 > if flag==0: > print "Values list contains:",Values,"\n" > print "Type of Values[0] is:",type(Values[0]),"\n" > longstring="UPDATE SecB SET > currencyCode='"+Values[1]+"',issuerName='"+Values[2]+"',instrName='"+Values[3]+\ > "',instrShortName='"+Values[4]+"',instrType='"+Values[5]+"',secCode='"+Values[6]+\ > "',SEDOL='"+Values[7]+"',Date='"+Values[8]+"',SuspendedState='"+Values[9]+\ > "',bidPrice='"+Values[10]+"',offerPrice='"+Values[11]+"',midPrice='"+Values[12]+\ > "',standardMarketSize='"+Values[13]+"',openOrClosed='"+Values[14]+\ > "' WHERE secBoardId='"+Values[0]+"'" # This is the line > it falls over on. > cursor.execute(longstring) > connection.commit() > currentStatus=SQL2[0][13] #current Stock Status > if currentStatus==1: # Open > if Values[14]!='0': # xml says open > oldStart("",text_buffer) #5SE > elif Values[15]!='0': # xml says closed > oldStart("",text_buffer) > elif Values[14]==0 and Values[15]==0: # neither openPrice nor > closePrice exist in xml > oldStart("",text_buffer) # just 5ER and 5IS > else: # currently Closed > if Values[14]!='0': #xml says open > oldStart("",text_buffer) # 5PR > else: #xml says closed > oldStart("",text_buffer) # 5ER,5IS > else: > cursor.execute('INSERT INTO SecB VALUES > (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',\ > (Values[0],Values[1],Values[2],Values[3],Values[4],Values[5],\ > Values[6],Values[7],Values[8],Values[9],Values[10],Values[11],\ > Values[12],Values[13],Values[14])) > connection.commit() > if Values[14]!='0': # xml says open > test=dom.getiterator('openPrice') > oldStart("",text_buffer) # 5ER, 5IS > oldStart("",text_buffer) # 5PR > else: # xml says closed, or neither options exist. > oldStart("",text_buffer) # 5ER, 5IS > > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 17 03:32:44 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 17 Sep 2007 09:32:44 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <1190013177.473529.167770@o80g2000hse.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> <46e97917$0$9014$426a74cc@news.free.fr> <1190013177.473529.167770@o80g2000hse.googlegroups.com> Message-ID: <46ee2d9d$0$26213$426a74cc@news.free.fr> TheFlyingDutchman a ?crit : >> >> >> Hi, I'm new to Python, I don't even fully know the language, never done >> a full project in Python. What's more, probably I'll never will. >> But that's not the point, the point is I want YOU people to modify the >> language you know in and out, the program with which you've done many >> systems, I want you to change it to suit my whims, so that I'll be >> comfortable with the 3 ten liners I'll write. >> TIA >> >> > > > Hi, I've used Python and have fallen in love with it. I know exactly > how Guido pronounces his name and since I saw him use the obtuse > phrase syntactic sugar I try and work it into every discussion I have > on Python syntax. I hate it when anyone offers criticism of Guido's > language. I have a picture of Bruce Eckel with a red universal not > sign over it on my wall and I throw my mechanical pencils at it every > night. I am especially upset when someone talks bad about kluges like > @staticmethod or FunctionName = staticmethod(FunctionName). Sure "def > static" or "static def" would be so much cleaner, simpler and clearer > but let's face it my fellow Pythonistas, this language may have > started out based on what was easy for people to learn and use but > we're in Nerdville now and clean and clear have become roadblocks! I > have so much more respect for Perl and the way it developed now! > > Hi, I'm totally unable to understand the difference between higher order functions and language statements, nor why the first approach is way better than the second. I'm totally clueless about Python's object model despite many posts explaining it and pointing to relevant documentation. And, ho, yes, I don't even understand the expression "syntactic sugar", but I guess it must some dummy concept invented by the guy that wrote Python whatever his name might be. So I insist on posting that all this is a kludge and that Python should be how I think it could be instead of trying to understand why it is the way it is and why people actually using it like the way it is. But what, given that I'm an AOL user still thinking it's kewl to hide behind a pseudo, what else would you expect ? From paul at boddie.org.uk Wed Sep 19 18:51:23 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 19 Sep 2007 15:51:23 -0700 Subject: compile for ARM In-Reply-To: <1190226961.806875.205530@i13g2000prf.googlegroups.com> References: <5ld5avF7ne3mU1@mid.uni-berlin.de> <1190226961.806875.205530@i13g2000prf.googlegroups.com> Message-ID: <1190242283.372338.253440@22g2000hsm.googlegroups.com> On 19 Sep, 20:36, Paul McGuire wrote: > > The gumstix buildroot requires a Linux platform - I was able to build > Python for gumstix using a Debian environment. The gumstix mailing > list and wiki were very helpful. The inquirer might also consider crosstool, which is good at building cross-compilers for GNU/Linux targeting "Embedded Linux": http://www.kegel.com/crosstool/ As for building Python itself, searching the Python bug tracker for "cross-compile" might provide some patches and advice: http://bugs.python.org/ Also try looking at the python.org Wiki for information, starting here: http://wiki.python.org/moin/EmbeddedPython Paul From jeff at jmcneil.net Thu Sep 27 15:56:27 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 27 Sep 2007 15:56:27 -0400 Subject: How to Catch Errors in SimpleXMLRPCServer In-Reply-To: <82d28c40709271255s1039e861xf9abbc80e1b56b09@mail.gmail.com> References: <1190921745.575519.53560@y42g2000hsy.googlegroups.com> <82d28c40709271255s1039e861xf9abbc80e1b56b09@mail.gmail.com> Message-ID: <82d28c40709271256p21eaad7bk5458616bc09af8dc@mail.gmail.com> getattr, not self.getattr. On 9/27/07, Jeff McNeil wrote: > Instead of register_function, use register_instance and provide a > _dispatch method in that instance that handles your exception logging. > > Pseudo: > > class MyCalls(object): > def _dispatch(self, method, args): > try: > self.getattr(self, method)(*args) > except: > handle_logging() > > server = SimpleXMLRPCServer(("localhost", 8000)) > server.register_instance(MyCalls()) > server.serve_forever() > > There might be an easier way... but this works for me. > > -Jeff > > On 9/27/07, gregpinero at gmail.com wrote: > > I have a pretty simple XMLRPCServer, something along the lines of the > > example: > > > > server = SimpleXMLRPCServer(("localhost", 8000)) > > server.register_function(pow) > > server.register_function(lambda x,y: x+y, 'add') > > server.serve_forever() > > > > Now what I want to do is catch any errors that happen on requests, and > > ideally have them emailed to me. I have the email part all taken care > > of, I just need to know how to get at the exceptions. > > > > Thanks in advance for any help, > > > > Greg > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From larry.bates at websafe.com Thu Sep 6 19:15:50 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 06 Sep 2007 18:15:50 -0500 Subject: Subclassing zipfile (new style class) Message-ID: I'm trying to learn about subclassing new style classes and the first project I went to do needs to subclass zipfile to add some methods. Why does this: import zipfile class walkZip(zipfile): pass if __name__ == "__main__": print "Hello World" Traceback (most recent call last): File "", line 192, in run_nodebug File "", line 2, in TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) >>> Thanks in advance. -Larry From fakeaddress at nowhere.org Sun Sep 30 15:36:08 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 30 Sep 2007 19:36:08 GMT Subject: which language allows you to change an argument's value? In-Reply-To: <1191149233.346818.246170@22g2000hsm.googlegroups.com> References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> Message-ID: Summercool wrote: > I wonder which language allows you to change an argument's value? > like: > > foo(&a) { > a = 3 > } > > n = 1 > print n > > foo(n) # passing in n, not &n > print n > > and now n will be 3. I think C++ and PHP can let you do that, using > their reference (alias) mechanism. And C, Python, and Ruby probably > won't let you do that. What about Java and Perl? I think you've missed how Python works, and probably others. A Python function receives a reference to the argument, and can modify the object if the object is mutable. Nevertheless, assigning to the parameter's name will not change the passed object. This function does nothing: def clear_list_wrong(lst): lst = [] # useless re-binding of local name This version empties the passed list: def clear_list(lst): del lst[:] > is there any way to prevent a function from changing the argument's > value? Sure. First choice: Don't change the value in the function. Alternatives include making a copy to use as the argument. > isn't "what i pass in, the function can modify it" not a desireable > behavior if i am NOT passing in the address of my argument? For one > thing, if we use a module, and call some functions in that module, and > the module's author made some changes to his code, then we have no way > of knowing what we pass in could get changed. Don't rely on undocumented behavior. Modules worth using are by good programmers. Authors of library modules tend to be zealous about not breaking client code. -- --Bryan From bj_666 at gmx.net Sat Sep 22 07:15:53 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2007 11:15:53 GMT Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> <1190454275.282176.90830@k79g2000hse.googlegroups.com> Message-ID: <5lkbr8F8gic1U6@mid.uni-berlin.de> On Sat, 22 Sep 2007 02:44:35 -0700, Kay Schluehr wrote: > I checked out Io once and I disliked it. I expected Io's prototype OO > being just a more flexible variant of class based OO but Io couples a > prototype very closely to its offspring. When A produces B and A.f is > modified after production of B also B.f is modified. A controls the > state of B during the whole lifetime of B. I think parents shall not > do this, not in real life and also not in programming language > semantics. Well it's like Python: inherited slots (attributes) are looked up in the ancestors. It should be easy to override `Object clone` in Io, so all slots of the ancestor are shallow copied to the clone, but I guess this might break existing code. At least for your own code you could introduce a `realClone` slot. Ciao, Marc 'BlackJack' Rintsch From lasses_weil at klapptsowieso.net Thu Sep 13 15:56:00 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 13 Sep 2007 21:56:00 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <46e9921e$0$26251$426a74cc@news.free.fr> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> <5ktfb5F5ctrvU1@mid.individual.net> <46e98e01$0$30383$9b4e6d93@newsspool4.arcor-online.net> <46e9921e$0$26251$426a74cc@news.free.fr> Message-ID: <46e995d1$0$16120$9b4e6d93@newsspool1.arcor-online.net> Bruno Desthuilliers wrote: > OTHO, simple math-illeterate programmers like me will have hard time > maintaining such a code. Certainly, but again: Such main people are not the intended audience. The code is for people that know how to read these equations. I think a general rule of (any form of) writing is to write with your audience in mind. I always do that and happily, that audience is usually naked. > Also and FWIW, it's not always possible to make > a direct translation of a mathematic formula|algorithm in Python, and > even when it is, it's not always the best thing to do wrt/ perfs (I > recently had such a case, and after a pythonic rewrite the code was > about 75% shorter, 50% faster, and 200% more readable for average joe > programmer). > Your point. Different game, but still your point. ;) >> ... my 2 sents, anyway ... > > May I add my 2 cents - or should I send them ?-) > No, actually you're supposed to smell them. Oh, how I love homophones! /W From grante at visi.com Sat Sep 15 18:36:08 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Sep 2007 22:36:08 -0000 Subject: how to join array of integers? References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <46EBE498.9040800@ehas.org> <13eo1rb73mg8b77@corp.supernews.com> Message-ID: <13eoniohphkjs95@corp.supernews.com> On 2007-09-15, Robert Kern wrote: > Grant Edwards wrote: >> On 2007-09-15, Erik Jones wrote: >> >>>>> print ''.join([str(i) for i in [1,2,3]]) >>>> It's better to use generator comprehension instead of LC: >>>> >>>> ",".join(str(i) for i in [1, 2, 3]) >>> Why is that? That entire expression must be evaluated to >>> obtain the result, so what is the advantage of using a >>> generator comprehension v. a list comprehension? >> >> The generator avoids creating the intermediate list -- it >> generates the intermediate values on the fly. For short >> sequences it probably doesn't matter much. For a very long >> list it's probably noticable. > > Not true. str.join() creates a list from the iterator if it is > not already a list or a tuple. So the iterator avoids creating an intermediate list, but the join method goes ahead and does it anyway? > In Objects/stringobject.c, look at string_join(); it calls > PySequence_Fast() on the argument. Looking in > Objects/abstract.c, we see that PySequence_Fast() > short-circuits lists and tuples but builds a full list from > the iterable otherwise. So what's the point of iterables if code is going to do stuff like that when it wants to iterate over a sequence? > map() seems to reliably be the fastest option, Which is apparently going away in favor of the slower iterator approach? > and list comprehensions seem to slightly edge out generator > comprehensions if you do the timings. -- Grant Edwards grante Yow! Clear the at laundromat!! This visi.com whirl-o-matic just had a nuclear meltdown!! From __peter__ at web.de Sat Sep 29 07:36:26 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 29 Sep 2007 13:36:26 +0200 Subject: question about for cycle References: <1191062383.322949.55300@d55g2000hsg.googlegroups.com> Message-ID: Ant wrote: > On Sep 29, 11:04 am, "fdu.xia... at gmail.com" > wrote: > ... >> What should I do if I want the outer "for" cycle to continue or break ? If I >> put a "continue" or "break" in the inner cycle, it has no effect on the outer >> cycle. > > I'd also be interested in the idiomatic solution to this one. I can > see a number of solutions, from the ugly: > > for i in range(10): > do_break = True > for j in range(10): > if j == 6: > break > else: > do_break = False > > if do_break: > break Here's a variant that doesn't need the flag >>> inner = "abc" >>> outer = "xbz" >>> for i in outer: ... for k in inner: ... if i == k: ... print "found", i ... break ... else: ... print i, "not found" ... continue ... break ... x not found found b but I usually prefer a helper function like this > def get_value(): > for i in range(10): > for j in range(10): > print i, j > if j == 6: > return fn(i, j) or this: >>> def f(i, inner): ... for k in inner: ... if i == k: ... print "found", i ... return True ... >>> for i in outer: ... if f(i, inner): ... break ... print i, "not found" ... x not found found b Peter From m.n.summerfield at googlemail.com Fri Sep 14 05:07:36 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Fri, 14 Sep 2007 09:07:36 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189753968.917636.310120@19g2000hsx.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> <1189753968.917636.310120@19g2000hsx.googlegroups.com> Message-ID: <1189760856.449420.60750@y42g2000hsy.googlegroups.com> I forgot one item in the proposed API: ordereddict.delete(index : int) Also, the API for keys() should be ordereddict.keys(firstindex : int = None, secondindex : int = None) If called with no args, returns list of all keys (in key order of course); if one arg is given, returns keys with indexes in range(0, firstindex); if two args are given, returns keys with indexes in range(firstindex, secondindex). Below is a stripped-down implementation in pure python that is just 84 lines long. (I have a proper version with blank lines and doctests which is 482 lines but I thought that was a bit long to post.) It should work as a drop-in replacement for dict (apart from performance), but with the keys ordered by <, so that every list or iterator that it returns is always in key order. The get(), has_key(), __contains__(), len(), and __getitem__() methods are not reimplemented because the base class versions work fine. I'm only posting it to give a better feel for the API---if someone did a better (faster) implementation (e.g., in C), that'd be great, but best to get consensus on an API first I think (if consensus is possible at all!). import bisect class ordereddict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__keys = sorted(dict.keys(self)) def update(self, *args, **kwargs): dict.update(self, *args, **kwargs) self.__keys = sorted(dict.keys(self)) @classmethod def fromkeys(cls, iterable, value=None): dictionary = cls() for key in iterable: dictionary[key] = value return dictionary def key(self, index): return self.__keys[index] def item(self, index): key = self.__keys[index] return key, self[key] def value(self, index): return self[self.__keys[index]] def set_value(self, index, value): self[self.__keys[index]] = value def delete(self, index): key = self.__keys[index] del self.__keys[index] dict.__delitem__(self, key) def copy(self): dictionary = ordereddict(dict.copy(self)) dictionary.__keys = self.__keys[:] return dictionary def clear(self): self.__keys = [] dict.clear(self) def setdefault(self, key, value): if key not in self: bisect.insort_left(self.__keys, key) return dict.setdefault(self, key, value) def pop(self, key, value=None): if key not in self: return value i = bisect.bisect_left(self.__keys, key) del self.__keys[i] return dict.pop(self, key, value) def popitem(self): item = dict.popitem(self) i = bisect.bisect_left(self.__keys, item[0]) del self.__keys[i] return item def keys(self, firstindex=None, secondindex=None): if firstindex is not None and secondindex is None: secondindex = firstindex firstindex = 0 else: if firstindex is None: firstindex = 0 if secondindex is None: secondindex = len(self) return self.__keys[firstindex:secondindex] def values(self): return [self[key] for key in self.__keys] def items(self): return [(key, self[key]) for key in self.__keys] def __iter__(self): return iter(self.__keys) def iterkeys(self): return iter(self.__keys) def itervalues(self): for key in self.__keys: yield self[key] def iteritems(self): for key in self.__keys: yield key, self[key] def __delitem__(self, key): i = bisect.bisect_left(self.__keys, key) del self.__keys[i] dict.__delitem__(self, key) def __setitem__(self, key, value): if key not in self: bisect.insort_left(self.__keys, key) dict.__setitem__(self, key, value) def __repr__(self): return "ordereddict({%s})" % ", ".join( ["%r: %r" % (key, self[key]) for key in self.__keys]) From martin at v.loewis.de Mon Sep 24 16:13:02 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Sep 2007 22:13:02 +0200 Subject: Building Python with VC8 on x64 Vista In-Reply-To: <1190646833.144905.40030@19g2000hsx.googlegroups.com> References: <1190299551.573204.322440@57g2000hsv.googlegroups.com> <46F52FFD.3040500@v.loewis.de> <1190646833.144905.40030@19g2000hsx.googlegroups.com> Message-ID: <46F81A4E.4030101@v.loewis.de> > It doesn't look like these are x86, though. Ok. Can you then check symbol lists also?: undefined symbols in the object file, and defined symbols in the library, wrt. PyExc_IndexError (say). Regards, Martin From __peter__ at web.de Mon Sep 24 03:13:40 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Sep 2007 09:13:40 +0200 Subject: scope, modyfing outside object from inside the method References: Message-ID: Marcin St?pnicki wrote: > Hello. > > I thought I understand this, but apparently I don't :(. I'm missing > something very basic and fundamental here, so redirecting me to the > related documentation is welcomed as well as providing working code :). > > Trivial example which works as expected: > >>>> x = {'a':123, 'b': 456} >>>> y = x >>>> x['a']=890 >>>> y > {'a': 890, 'b': 456} > > Now, let's try something more sophisticated (it's not real world example, > I've made up the problem which I think illustrates my issue). Let's say > I've got such a structure: > > results = [ {'a': 12, 'b': 30 }, > {'a': 13, 'b': 40 } ] > > I'd like to have each row and column in separate object of self-made > classes.: > > class mycolumn(): > def __init__(self, resultset, row, col): > self.value = resultset[row][col] > def __str__(self): > return 'Column value: %s' % self.value > > class myrow(): > def __init__(self): > self.container = {} > def __str__ (self): > return self.container > > results = [ > {'a': 12, 'b' :30 }, > {'a': 13, 'b' :40 } > ] > > mystruct = [] > > for row in results: > mystruct.append ( myrow() ) > for col in row: > mystruct [len(mystruct)-1].container[col] = \ > mycolumn(results, results.index(row), col) > > print mystruct[0].container['b'] # 12 > results[0]['b'] = 50 # > print mystruct[0].container['b'] # also 12 :/ > > In other words, I'd like to "map" the results to myrow and mycolumn > objects, and have these new objects' values changed when I change "results". Instead of copying a value, you can tell your objects where to look it up. Your mycolumn class would then become class MyColumn(object): def __init__(self, resultset, row, col): self._resultset = resultset self._row = row self._col = col @property def value(self): return self._resultset[self._row][self._col] def __str__(self): return 'Column value: %s' % self.value Peter From gagsl-py2 at yahoo.com.ar Thu Sep 13 02:09:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Sep 2007 03:09:09 -0300 Subject: Setting stdout encoding References: <1189416350.069995.220250@w3g2000hsg.googlegroups.com> Message-ID: En Tue, 11 Sep 2007 07:58:03 -0300, Fabio Zadrozny escribi?: >> You could place code like that on sitecustomize.py >> I think this should be fixed on Eclipse/pydev. If they replace >> sys.stdout >> with a different object - they should make sure it has the right >> behavior. >> Same for IDLE if it's broken too. >> > > Thanks for the tip... I wasn't aware of sitecustomize.py (site.py does > call > that just before removing setdefaultencoding() from sys, so I can still > use > sys.setdefaultencoding)... actually, setencoding() from site.py does have > what I would like to execute: > if 0: > # Enable to support locale aware default string encodings. > import locale > loc = locale.getdefaultlocale() > if loc[1]: > encoding = loc[1] > > I just don't get why the code has that "if 0:" instead of getting it from > some user-config (like env variable or parameters passed)... > > Anyways, thanks a lot... I think I can arrange in providing a > sitecustomize.py from pydev with that structure. But I don't think it's a good idea. Changing the default encoding will change it for *all* scripts, *all* users, *all* objects. And AFAIK you have trouble ONLY with sys.std* - one should fix those objects, not mess with a global configuration. -- Gabriel Genellina From perl4hire at softouch.on.ca Sat Sep 15 10:18:24 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Sat, 15 Sep 2007 10:18:24 -0400 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: Bryan Olson wrote: > Amer Neely wrote: >> This seems to indicate that maybe my host needs to configure Apache to >> run python scripts? But I didn't need to do anything with mine. > > Another possibility: If it works on Windows but not Unix, check > the end-of-line characters. Windows ends each line with the two > character sequence carriage-return + newline, which in Python > is "\r\n". Unix uses newline alone, "\n". > > Most Unixies will choke on a #! line with a carriage return. > The Python interpreter will accept source files with either > end-of-line on either system, but of course you'll not get > that far unless the operating system respects the shebang line. > > Maybe you already checked that. Hmmm...other possiblities... > > Do you have shell access? Can you executing it directly from > the shell? Do you get a Python error, or some other? > > Did you: chmod ugo+rx > > Is Python in /usr/bin? What does "which python" say? > > Generally, most experts seem to prefer: > > #!/usr/bin/env python > > You might try changing the the extension of your script from .py > to .cgi. Windows uses the .py to choose the executable, but Unix > does not care; it used the shebang line. > > I tried `which python` and `whereis python` and got 0 back as a result. So it seems Python is not installed at all. -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From super.sgt.pepper at gmail.com Fri Sep 21 19:02:21 2007 From: super.sgt.pepper at gmail.com (Cristian) Date: Fri, 21 Sep 2007 23:02:21 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> Message-ID: <1190415741.380795.259050@y42g2000hsy.googlegroups.com> On Sep 21, 3:44 pm, Ron Adam wrote: > I think key may be to discuss names and name binding with your friend. How > a name is not the object it self, like a variable is in other languages. > For example show him how an object can have more than one name. And discus > how names can be bound to nearly anything, including classes and functions. I could discuss name binding but it would be great if Python said this itself. After all, you can even bind a module with the foo = bar syntax by using __import__ function. If function definitions followed the same pattern, I think a beginner would subconsciously (maybe even consciously) realize that function names are just like everything else. Actually, this would be helpful for many people. If you come from a language like Java you're used to thinking of attributes and methods as living in different namespaces. I think a new syntax will encourage seasoned programmers think in a more Pythonic way. Python has done a very good job in easing people into programming. My friend doesn't come to me very often because the syntax is clear and simple and the builtin datatypes allow you to do so much. My goal is that I would never have to explain to him about name binding; that he'd pick it up by learning the language on his own. He's learned lists, dictionaries and even some OOP without me. I don't think name binding would be a stretch. > You could also discus factory functions with him. Once he gets that a > function can return another function, then it won't be so much of a leap > for a function to take a function as an argument. I think this isn't the most intuitive way of approaching first order functions. It's true that if a function can return another function then a function must be first order (i.e., it's just like any other variable), but that seems almost backwards to me. I think it would make more sense to have beginners _know_ that functions are like all other variables and can therefore be passed by other functions or returned by other functions. That I think would be better accomplished if they define functions the same way you would define other variables that you know can be passed and returned. From steve at holdenweb.com Mon Sep 17 19:51:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Sep 2007 19:51:36 -0400 Subject: adodb with mysql - connection string syntax for filepath In-Reply-To: <46EF0BEF.3070807@sdf.lonestar.org> References: <33dffc910709162342x49657895t938fb1f8af2834de@mail.gmail.com> <46EF0BEF.3070807@sdf.lonestar.org> Message-ID: J. Cliff Dyer wrote: > Mridula Ramesh wrote: >> Dear all, >> >> Hi. I am not very tech-savvy so please pardon me if this is a stupid >> question: so far I have been googling for about 4 days to find help >> for this, so now I am desperate! :) >> >> How do you use adodb with mysql to connect to a file that is on your >> machine? >> > I'm not quite sure what you mean by this. MySQL won't connect you to a > file on your machine. It will connect you to a database server, which > will possibly access files on your machine, but could just as easily > access an in-memory database, that isn't stored in any files. > > I've also never worked with adodb, but if you use MySQLdb, you do the > following: > > import MySQLdb as db > > cur = db.connect(host='127.0.0.1', #or whatever your hosts address is > user=username, > passwd=password, > db=database).cursor() > cur.execute('SELECT * FROM table') > cur.fetchall() > > If adodb is dbapi 2 compliant, it may be as simple as s/MySQLdb/adodb/ > It won't be quite that simple, as adodb requires connection strings. A good place to start would be http://www.carlprothman.net/Default.aspx?tabid=81 >> Also, could you please recommend to me a good resource to learn more >> about classes and modules from? i don't understand half of the _init_ >> business that many sites mention. (This *is* something even a newbie >> needs to learn, right?) >> > Try this chapter from Diving into Python: > > http://www.diveintopython.org/object_oriented_framework/defining_classes.html >> Thank you! >> Dive Into Python might seem intimidating at first glance, but it's worth persevering with. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From larry.bates at websafe.com Mon Sep 17 11:08:30 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 17 Sep 2007 10:08:30 -0500 Subject: Processing drag & drop on the desktop In-Reply-To: <1189961614.510561.194610@w3g2000hsg.googlegroups.com> References: <1189961614.510561.194610@w3g2000hsg.googlegroups.com> Message-ID: <1uSdnaNGwMvgBXPbnZ2dnUVZ_tjinZ2d@comcast.com> Pierre Quentel wrote: > Hi all, > > I would like to create an application on a Windows machine, such that > when a document is dragged and dropped on the application icon on the > desktop, the document is processed by the application > > For instance, if I drag & drop an Outlook message or a PPT > presentation, the application would propose to tag the document with > keywords taken from a database > > Is it possible to do this with a Python script, and how ? > > Regards, > Pierre > If you write a python application and put a shortcut on the desktop, when you drop any file on it in Windows it is passed into the program via the sys.argv list as the second (e.g. sys.argv[1]) argument. If you drop multiple files, they are passed in sys.argv[1] sys.argv[n]. All you need to do is to pick up the filename and do your processing. -Larry From bdesth.quelquechose at free.quelquepart.fr Mon Sep 17 07:00:04 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 17 Sep 2007 13:00:04 +0200 Subject: adding a static class to another class In-Reply-To: References: Message-ID: <46eef7d2$0$13879$426a74cc@news.free.fr> Nathan Harmston a ?crit : > HI, > > I m trying to start an api in a similar way to the djangic way of > Class.objects.all(). Ie objects is a "Manager" class. > > So: > > class Foo(object): > def __init__(self): > self.test = "NEE" > > class Manager(object): > def __init__(self): > pass > def all(self): > return "COCONUTS" > > Because of how some of the code is set up I cant use > metaclasses........so I try to use a decorator: > > def addto(instance): > def decorator(f): > import new > f = new.instancemethod(f, instance, instance.__class__) > setattr(instance, "objects", f) > return f > return decorator > > class Manager(object): > @addto(Foo) > def __init__(self): > ............. > > however this only binds the init method to the Foo.objects, so not > what I want. Indeed. > If I try using classmethod...then it just says the > Foo.objects doesnt exist. You mean decorating Manager.__init__ with classmethod ??? I may be wrong, but I suspect you don't have a clear idea of what you're doing here. > Does anyone have any ideas how I can accomplish this using decorators? Yes : don't use a decorator !-) Instead of asking for how to implement what you think is the solution, you might be better explaining the problem you're trying to solve. > And also preventing more than one Manager instance instantiated at one > time. Q&D: class Singleton(object): def __new__(cls): if not hasattr(cls, '_inst'): cls._inst = object.__new__(cls) return cls._inst Same remark as above... From steve at holdenweb.com Sat Sep 1 11:49:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Sep 2007 11:49:20 -0400 Subject: Important Research Project In-Reply-To: References: <13ddcvm1bsu3s94@corp.supernews.com> <46D6CA0E.E66ED5C8@yahoo.com> <13deq9nj9atft62@corp.supernews.com> Message-ID: Kenny McCormack wrote: > In article , > Keith Thompson wrote: >> "E.D.G." writes: >>> "CBFalconer" wrote in message >>> news:46D6CA0E.E66ED5C8 at yahoo.com... >>>> "E.D.G." wrote: >>>> Where is Perl described in the C standard? This seems rather OT. >>> It has been my experience that a person who is an expert with one computer >>> language can usually do reasonably well when working with other languages. >>> I am trying to find some people who can assist with getting a Perl program >>> running. It would probably be easier for expert programmers in any language >>> to help with this type of work compared with people such as myself who are >>> not experts in any programming language. >> CBFalconer's point is that this newsgroup (comp.lang.c, where he and I >> are both reading this) is for discussion of the C programming >> language. If you want to discuss something other than C, please find >> another forum. Massive cross-posts like this are rarely appropriate. > > IOW (for the OP and for the various readers in all these groups): > > The rod up Keith's butt has a rod up its butt. > > Note, incidentally, that this thread is yet the latest occurrence of a > phenomenon that I've observed many times in the past, and have > described here in clc on more than a few occasions. That is, somebody > starts a thread, posted to several different groups, in the hope of > getting help from at least one of them. The thread is pretty much > on-topic for most of the groups, primarily because the keepers of most > of the groups do not have rods up their butts. > > However, and this is the big however, one of the groups listed just > happens to be clc, where rod-filled butts are the norm. The result is > that all of the responses come from clc (including, of course, this one) > and, as we see, it's all topicality BS, and nobody ever ends up > discussing the original subject. Really a pity, that. > Well I am reading your response "here" on c.l.py, where there are no keepers because the lunatics have taken over the asylum. If clc has to deal with attitudes like yours then it seems there are two sides to the problem. Your own behavior would also be considered marginally acceptable, containing as it does an unsubstantiated ad hominem attack. Quite what you think you were doing to encourage the thread back on-topic I have no idea. While the OP may have been uninformed about the nature of usenet, at least he made his request in a polite and unobjectionable fashion. He received some good advice together with a certain amount of predictable but probably not fully-deserved hostility. Everybody makes mistakes. Just let them go by and give your fingers a rest. You can't police everyone, and you would be foolish to try. Save your efforts for the real trolls like Xah Lee, or are you fortunate enough to miss his folk wisdom on clc? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From b83503104 at yahoo.com Sun Sep 30 10:11:50 2007 From: b83503104 at yahoo.com (bahoo) Date: Sun, 30 Sep 2007 14:11:50 -0000 Subject: notify when process finishes (on unix) Message-ID: <1191161510.764656.244540@57g2000hsv.googlegroups.com> Hi, I'd like to write a script that sends me an email when a unix (Linux) process ends running (or CPU drops below some threshold). Could anyone point me to the relevant functions, or show me an example? Thanks bahoo From ldo at geek-central.gen.new_zealand Sun Sep 9 22:59:59 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 10 Sep 2007 14:59:59 +1200 Subject: Python syntax wart References: <5khuq4F3ij9eU1@mid.individual.net> Message-ID: In message <5khuq4F3ij9eU1 at mid.individual.net>, Bjoern Schliessmann wrote: > What's wrong with this: > > for Link in GetEachRecord( Then you're no longer showing the syntax structure in two dimensions. From Caseyweb at gmail.com Fri Sep 28 13:03:56 2007 From: Caseyweb at gmail.com (Casey) Date: Fri, 28 Sep 2007 17:03:56 -0000 Subject: getopt with negative numbers? In-Reply-To: <871wcj4ib9.fsf@benfinney.id.au> References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <1190915197.390247.313590@57g2000hsv.googlegroups.com> <1190930134.780005.68510@22g2000hsm.googlegroups.com> <1190944143.521085.66910@g4g2000hsf.googlegroups.com> <871wcj4ib9.fsf@benfinney.id.au> Message-ID: <1190999036.588941.165610@g4g2000hsf.googlegroups.com> On Sep 27, 10:47 pm, Ben Finney wrote: > I believe they shouldn't because the established interface is that a > hyphen always introduced an option unless (for those programs that > support it) a '--' option is used, as discussed. Not "THE" established interface; "AN" established interface. There are other established interfaces that have different behaviors. I'm a pragmatist; I write software for users, not techies. I suspect most users would expect a command like "abc -a -921 351 175" to treat the "-921" as a negative integer and not abort the program with some obscure error about option 921 not being known. > > > But I think it is a simple and clever hack and still allows getopt > > or optparse to function normally. > > Except that they *don't* function normally under that hack; they > function in a way contradictory to the normal way. Again, it depends on who is defining "normal" and what they are basing it on. I suspect many (probably most) users who are familiar with command line input are unaware of the "--" switch which was mainly designed to support arbitrary arguments that might have an initial hyphen, a much broader problem than supporting negative values. I'm not asking that the default behavior of getopt or optparse change; only that they provide an option to support this behavior for those of us who find it useful. Software libraries should be tools that support the needs of the developer, not rigid enforcers of arbitrary rules. From BjornSteinarFjeldPettersen at gmail.com Thu Sep 20 01:37:30 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Thu, 20 Sep 2007 05:37:30 -0000 Subject: super() doesn't get superclass In-Reply-To: <1190209294.584372.173410@o80g2000hse.googlegroups.com> References: <8764281uea.fsf@benfinney.id.au> <13f196qktorgc88@corp.supernews.com> <873axbxl2f.fsf@benfinney.id.au> <1190209294.584372.173410@o80g2000hse.googlegroups.com> Message-ID: <1190266650.894172.234710@57g2000hsv.googlegroups.com> On Sep 19, 3:41 pm, Michele Simionato wrote: > On Sep 19, 3:22 pm, Sion Arrowsmith > wrote: > > > Ben Finney wrote: > > > > If a function is named 'super' and operates on > > >classes, it's a pretty strong implication that it's about > > >superclasses. > > > But it doesn't (under normal circumstances) operate on classes. > > It operates on an *instance*. And what you get back is a (proxy > > to) a superclass/ancestor of the *instance*. > > > (And in the super(A, B) case, you get a superclass/ancestor of > > *B*. As has just been said somewhere very near here, what is > > misleading is the prominence of A, which isn't really the most > > important class involved.) > > Happily A (and B too) will become invisible in Python 3000. > > Michele Simionato This is great news! Since it is for Py3K it seems clear to me that super should be a keyword as well (but historically I'm not the best at channeling Guido ;-) -- bjorn From orsenthil at gmail.com Thu Sep 6 23:45:44 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Fri, 7 Sep 2007 09:15:44 +0530 Subject: ??????urllib post???????????? In-Reply-To: <0665EB55-E95B-4DEA-876B-E6DD95228137@abrahamsen.com> References: <1188993813.330662.174660@w3g2000hsg.googlegroups.com> <20070906024041.GA6599@gmail.com> <0665EB55-E95B-4DEA-876B-E6DD95228137@abrahamsen.com> Message-ID: <20070907034544.GB3519@gmail.com> * Eric Abrahamsen [2007-09-06 11:18:29]: > It's in Chinese, so ASCII is no go. If anyone's interested in > answering his question (he's trying to download a linked file using > the post method from urllib tools, not something I know about) I can Python doc explains urllib post method: http://docs.python.org/lib/module-urllib.html import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) >>> print f.read() Hope this helps. - Senthil > On Sep 6, 2007, at 10:40 AM, O.R.Senthil Kumaran wrote: > > > If possible, please post your query in ASCII. > > > > -- > > Senthil > > > > > > * liangxuliang79 at gmail.com [2007-09-05 > > 05:03:33]: > > > >> ????www.mmmppp333.com??????????http://ishare.iask.sina.com.cn/cgi- > >> bin/ > >> fileid.cgi?fileid=844050 > >> ??????post fileid=844050???????? > >> > >> ????post????????????fileid=844050??????server??????????header?? > >> header????local????location???? > >> ?????????????????????????????????????????????? > >> mp3????????????????????????????local???????????? > >> mp3?????????????????????????????????? > >> ?????????????????????????????? > >> > >> ??????????????python??urllib????????urllib??????????????????????? > >> local????????????????local????????mp3???????? > >> ????????????????mp3.?? > >> > >> ??post????????/download.php?? post???????? > >> fileid=844050???????????????????????????????????????????????????? > >> ????????????????????web?????????????????????? > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > > -- > > O.R.Senthil Kumaran > > http://uthcode.sarovar.org > > -- > > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list -- O.R.Senthil Kumaran http://uthcode.sarovar.org From carsten at uniqsys.com Sat Sep 8 13:28:10 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 08 Sep 2007 13:28:10 -0400 Subject: /dev/null as a file-like object, or logging to nothing In-Reply-To: <87k5r1jdzq.fsf@wilson.homeunix.com> References: <87k5r1jdzq.fsf@wilson.homeunix.com> Message-ID: <1189272490.3094.11.camel@localhost.localdomain> On Sat, 2007-09-08 at 18:52 +0200, Torsten Bronger wrote: > Hall?chen! > > Is there a portable and simply way to direct file-like IO to simply > nothing? I try to implement some sort of NullLogging by saying > > --8<---------------cut here---------------start------------->8--- > import logging > if options.logging: > logging.basicConfig(level=logging.DEBUG, filename=options.logfile, filemode="w", > format='%(asctime)s %(name)s %(levelname)s %(message)s') > else: > # redirect logging to a memory buffer in order to simply ignore it. > import StringIO > logging.basicConfig(stream=StringIO.StringIO()) > --8<---------------cut here---------------end--------------->8--- > > However, this consumes memory. Is there a better way? This might work: class LogSink(object): def write(self, *args, **kwargs): pass def flush(self, *args, **kwargs): pass logging.basicConfig(stream=LogSink()) I haven't tested this thoroughly, so it's possible that there are more methods that the stream is expected to implement. HTH, -- Carsten Haese http://informixdb.sourceforge.net From benyang22 at gmail.com Mon Sep 3 20:32:23 2007 From: benyang22 at gmail.com (Ben) Date: Tue, 04 Sep 2007 00:32:23 -0000 Subject: Python is overtaking Perl Message-ID: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> Here are the statistics from Google Trends: http://benyang22a.blogspot.com/2007/09/perl-vs-python.html From robert.kern at gmail.com Tue Sep 4 11:13:10 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 04 Sep 2007 10:13:10 -0500 Subject: scipy.org website In-Reply-To: <46DCE027.1010708@biochem.ucsf.edu> References: <46DCE027.1010708@biochem.ucsf.edu> Message-ID: Hiten Madhani wrote: > Hi, > > The scipy.org website has been down. Does anyone know whether it is > coming back up? It is back up now. We're working on making it more stable. We're getting a lot more traffic than we used to. http://projects.scipy.org/pipermail/scipy-user/2007-September/013573.html -- 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 jstroud at mbi.ucla.edu Fri Sep 14 16:05:16 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 14 Sep 2007 13:05:16 -0700 Subject: How to Start In-Reply-To: <1189748073.196112.254870@w3g2000hsg.googlegroups.com> References: <1189748073.196112.254870@w3g2000hsg.googlegroups.com> Message-ID: Paul McGuire wrote: > Do "neophytes" just dive in and try stuff? I think a lot of us coming from other fields actually slithered in, in true python style. From andrew.arobert at gmail.com Mon Sep 3 10:45:27 2007 From: andrew.arobert at gmail.com (andrew.arobert at gmail.com) Date: Mon, 03 Sep 2007 14:45:27 -0000 Subject: Automation and scheduling of FrontPage publishing using Python In-Reply-To: <1188764575.438204.117420@r34g2000hsd.googlegroups.com> References: <1188517723.279932.299400@x40g2000prg.googlegroups.com> <1188698223.393723.151140@d55g2000hsg.googlegroups.com> <1188701337.798785.188420@19g2000hsx.googlegroups.com> <1188764575.438204.117420@r34g2000hsd.googlegroups.com> Message-ID: <1188830727.452933.180610@y42g2000hsy.googlegroups.com> On Sep 2, 4:22 pm, "andrew.arob... at gmail.com" wrote: > On Sep 1, 10:48 pm, Jerry wrote: > > > andrew, > > > I would try looking into Windows automation with Python.http://www.google.com/search?q=windows+automation+pythonshouldget > > you started. The winGuiAuto package may help you out as it is like > > have a human click and move throughout the interface. The only > > downside is that there is no recorder to help you build the script, so > > I would try to do as much in VBA as you can (does FrontPage even > > support VBA?) and then just write your python script to get through > > the program enough to execute the macro. > > Yes.. Front page can be run by VB macro but I really did not want to > go down that road if it could be avoided. > > This looks very promising. > > I've installed the module and run a couple of the basic examples.. > > Very cool. After a bit of patience, I was able to get this to work. Still fine-tuning the process but the basic elements are there. What is interesting is that once I submitted the proof-of-concept code, management decided that they would like to see what other companies are doing for this requirement and weigh the pros/cons of this approach. From kar1107 at gmail.com Wed Sep 19 16:58:03 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Wed, 19 Sep 2007 20:58:03 -0000 Subject: Sets in Python In-Reply-To: References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> Message-ID: <1190235483.412972.81280@v23g2000prn.googlegroups.com> On Sep 19, 6:16 am, Sion Arrowsmith wrote: > sapsi wrote: > > Why can't lists be hashed? > > Several people have answered "because they're mutable" without > explaining why mutability precludes hashing. So: > > Consider a dict (dicts have been in Python a *lot* longer than > sets, and have the same restriction) which allowed lists as > keys: > > d = {} > k = [1, 2] > d[k] = None > > Now, if I were to do: > > k.append(3) > > what would you expect: > > d.keys() > > to return? Did d magically rehash k when it was modified? Did d[k] > take a copy of k, and if so, how deep was the copy (consider > d[[1, k]] = None followed by a modification to k)? Leaving the hash > unchanged and relying on collision detection to resolve won't work, > since you may go directly for d[[1, 2, 3]] and not spot that > there's already an entry for it since it's been hashed under [1, 2]. > > "Practicality beats purity" and the design decision was to simply > sidestep these issues by disallowing mutable dict keys. And as the > set implementation is based on the dict implementation, it applies > to sets to. While it's easy to explain the behavior, I think the decision to dis- allow mutable items as keys is a bit arbitrary. There is no need for dict to recompute hash (first of all, a user doesn't even need to know if underneath 'hashing' is used -- the service is just a mapping between one item to another item). Since we know hashing is used, all that is needed is, a well-defined way to construct a hash out of a mutable. "Given a sequence, how to get a hash" is the problem. If later the given sequence is different, that's not the dict's problem. >>> d = {} a = 10 >>> d[a] = 'foo' >>> d[5+5] = 'bar' >>> d[10] 'bar' aren't the '5+5' which is 10, is different from the previous line's a?.. so why not allow similar behavior with lists/other sequence/even other collections. As long as two objects compare equal the hash-result must be the same. I guess this takes us to defining the equality operation for lists-- which I think has a very obvious definition (ie same length and the ith element of each list compare equal). So if the list changes, it will result in a different hash and we will get a hash-miss. I doubt this is in anyway less intuitive than dis- allowing mutable items as keys. Karthik > > -- > \S -- si... at chiark.greenend.org.uk --http://www.chaos.org.uk/~sion/ > "Frankly I have no feelings towards penguins one way or the other" > -- Arthur C. Clarke > her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From gandalf at shopzeus.com Mon Sep 10 12:36:13 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 10 Sep 2007 18:36:13 +0200 Subject: Question about PEP 8 Message-ID: <46E5727D.6080403@shopzeus.com> Hi All, Here is what I read in PEP 8: > Package and Module Names > > Modules should have short, all-lowercase names. Underscores can be used > in the module name if it improves readability. Python packages should > also have short, all-lowercase names, although the use of underscores is > discouraged. > > Since module names are mapped to file names, and some file systems are > case insensitive and truncate long names, it is important that module > names be chosen to be fairly short -- this won't be a problem on Unix, > but it may be a problem when the code is transported to older Mac or > Windows versions, or DOS. > > When an extension module written in C or C++ has an accompanying Python > module that provides a higher level (e.g. more object oriented) > interface, the C/C++ module has a leading underscore (e.g. _socket). Here is my problem. There is ConfigParser, StringIO, Queue, HTMLParser etc. They are all part of the standard library. Most of these are modules with only a "main class" defined. ConfigParser module contains ConfigParser class, Queue module contains Queue class etc. Should I use CapWords for the module (and file) name or not? E.g. should I from mess.wxmegaeidgets.GenericDialog import GenericDialog or from mess.wxmegaeidgets.genericdialog import GenericDialog (suppose that the module contains only the GenericDialog class. BTW, will Py3K change the standard library names in order to follow PEP 8?) I also have problems with function and method names: > Function Names > > Function names should be lowercase, with words separated by underscores > as necessary to improve readability. > > mixedCase is allowed only in contexts where that's already the > prevailing style (e.g. threading.py), to retain backwards compatibility. Great, but what if I subclass wx widgets? They all have CapWords. (wx.Window.ShowModal, wx.Window.Bind etc.) I must use CapitalizedWords for method names because sometimes I have to override inherited methods, and it is not possible to change their name. Where should be the limit? If I create a composite widget then should I use lowercase and underscores? If I create a class that is not itself a widget, but works with widgets? The PEP defines the "theoretically good" coding style, but what is the correct style in an environment where you have third party libraries that are not following the PEP? Thanks, Laszlo From ahmad at baitalmal.com Wed Sep 19 20:41:34 2007 From: ahmad at baitalmal.com (=?UTF-8?Q?Ahmad_=E3=8B=A1_Baitalmal?=) Date: Wed, 19 Sep 2007 17:41:34 -0700 Subject: python-mcrypt install on Mac OSX Message-ID: <56DAC153-975E-4C02-9EFD-B8F1394244C1@baitalmal.com> Hi, I'm having a hard time getting python-mcrypt extension to build. I installed libmcrypt with --prefix=/usr and I checked that the library exists -rwxr-xr-x 1 root wheel 352K Sep 19 16:53 /usr/lib/libmcrypt. 4.4.8.dylib* lrwxr-xr-x 1 root wheel 21B Sep 19 16:53 /usr/lib/libmcrypt. 4.dylib@ -> libmcrypt.4.4.8.dylib lrwxr-xr-x 1 root wheel 21B Sep 19 16:53 /usr/lib/ libmcrypt.dylib@ -> libmcrypt.4.4.8.dylib -rwxr-xr-x 1 root wheel 801B Sep 19 16:53 /usr/lib/libmcrypt.la* But this is the output from setting up python-mcrypt # python setup.py build running build running build_ext building 'mcrypt' extension creating build creating build/temp.macosx-10.3-fat-2.5 gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk - fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd - fno-common -dynamic -DNDEBUG -g -O3 -DVERSION="1.1" -I/usr/include -I/ Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c mcrypt.c -o build/temp.macosx-10.3-fat-2.5/mcrypt.o creating build/lib.macosx-10.3-fat-2.5 gcc -arch i386 -arch ppc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -g -bundle -undefined dynamic_lookup build/temp.macosx-10.3-fat-2.5/ mcrypt.o -lmcrypt -o build/lib.macosx-10.3-fat-2.5/mcrypt.so /usr/bin/ld: for architecture ppc /usr/bin/ld: can't locate file for: -lmcrypt collect2: ld returned 1 exit status /usr/bin/ld: for architecture i386 /usr/bin/ld: can't locate file for: -lmcrypt collect2: ld returned 1 exit status lipo: can't open input file: /var/tmp//ccGRKjU2.out (No such file or directory) error: command 'gcc' failed with exit status 1 What am I missing here? I linked PHP with the same libmcrypt library just fine. This is only happening for this extension only. Would appreciate any help, thx Ahmad Baitalmal From steve at REMOVE-THIS-cybersource.com.au Wed Sep 19 21:46:15 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Sep 2007 01:46:15 -0000 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> <1190241711.344058.238380@57g2000hsv.googlegroups.com> <1190242799.954176.279440@22g2000hsm.googlegroups.com> Message-ID: <13f3k77d7fljbb4@corp.supernews.com> On Wed, 19 Sep 2007 15:59:59 -0700, TheFlyingDutchman wrote: > Paul it's a pleasure to see that you are not entirely against > complaints. I'm not against complaints either, so long as they are well-thought out. I've made a few of my own over the years, some of which may have been less well-thought out than others. > The very fastest Intel processor of the last 1990's that I found came > out in October 1999 and had a speed around 783Mhz. Current fastest > processors are something like 3.74 Ghz, with larger caches. Memory is > also faster and larger. It appears that someone running a non-GIL > implementation of CPython today would have significantly faster > performance than a GIL CPython implementation of the late 1990's. That's an irrelevant comparison. It's a STUPID comparison. The two alternatives aren't "non-GIL CPython on 2007 hardware" versus "GIL CPython on 1999 hardware" because we aren't using GIL CPython on 1999 hardware, we're using it on 2007 hardware. *That's* the alternative to the non-GIL CPython that you need to compare against. Why turn your back on eight years of faster hardware? What's the point of getting rid of the GIL unless it leads to faster code? "Get the speed and performance of 1999 today!" doesn't seem much of a selling point in 2007. > Correct me if I am wrong, but it seems that saying non-GIL CPython is > too slow, while once valid, has become invalid due to the increase in > computing power that has taken place. You're wrong, because the finishing line has shifted -- performance we were satisfied with in 1998 would be considered unbearable to work with in 2007. I remember in 1996 (give or take a year) being pleased that my new computer allowed my Pascal compiler to compile a basic, bare-bones GUI text editor in a mere two or four hours, because it used to take up to half a day on my older computer. Now, I expect to compile a basic text editor in minutes, not hours. According to http://linuxreviews.org/gentoo/compiletimes/ the whole of Openoffice-ximian takes around six hours to compile. Given the speed of my 1996 computer, it would probably take six YEARS to compile something of Openoffice's complexity. As a purely academic exercise, we might concede that the non-GIL version of CPython 1.5 running on a modern, dual-core CPU with lots of RAM will be faster than CPython 2.5 running on an eight-year old CPU with minimal RAM. But so what? That's of zero practical interest for anyone running CPython 2.5 on a modern PC. If you are running a 1999 PC, your best bet is to stick with the standard CPython 1.5 including the GIL, because it is faster than the non-GIL version. If you are running a 2007 PC, your best bet is *still* to stick with the standard CPython (version 2.5 now, not 1.5), because it will still be faster than the non-GIL version (unless you have four or more processors, and maybe not even then). Otherwise, there's always Jython or IronPython. -- Steven. From fdu.xiaojf at gmail.com Sat Sep 29 06:04:06 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Sat, 29 Sep 2007 18:04:06 +0800 Subject: question about for cycle Message-ID: <46FE2316.2040502@gmail.com> Hi all, I have the following code: for i in generator_a: # the first "for" cycle for j in generator_b: if something_happen: # do something here ..., I want the outer cycle to break break What should I do if I want the outer "for" cycle to continue or break ? If I put a "continue" or "break" in the inner cycle, it has no effect on the outer cycle. And I have another question. Which is the most efficient way to check if there are duplicate items in a list ? The items in the list may cannot be hashed, so set() may not work on the list. Regards, From super.sgt.pepper at gmail.com Fri Sep 21 20:08:40 2007 From: super.sgt.pepper at gmail.com (Cristian) Date: Sat, 22 Sep 2007 00:08:40 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> Message-ID: <1190419720.811685.145880@r29g2000hsg.googlegroups.com> On Sep 21, 4:47 pm, "Sean Tierney" wrote: > Just tell him that "functions are like all other variables and can > therefore be passed by other functions or returned by other functions. > " > I could """Just tell him that "functions are like all other variables and can therefore be passed by other functions or returned by other functions. " """ but wouldn't it be great if Python did this for me? It seems to me that the ability for Python to explicitly state that functions-are- like-other-variables is there so why not expose it? > If your friend understands variables and functions and he can't make > the "leap" (and assuming you're right, of course) then your friend > doesn't understand variables and functions. To say that you understand variables and functions is language specific. You can't translate your knowledge of variables and functions from Python to Java and vice-versa. They are treated completely different. Perhaps you can translate your Python understanding of functions and variables to Javascript but not to C. From shriphanip at gmail.com Tue Sep 25 02:05:15 2007 From: shriphanip at gmail.com (Shriphani) Date: Tue, 25 Sep 2007 06:05:15 -0000 Subject: Making a small change to a large XML document In-Reply-To: References: Message-ID: <1190700315.084594.281180@19g2000hsx.googlegroups.com> Dan Stromberg wrote: > Say I want to take an existing XML document, and change the value="9997" > and value="9998" to two different numbers, without changing any of the > rest of the document - not even changing comments or indentation, if > avoidable. > > What's the best way of doing it in python? > > > > > > > > > My .xml file is full of such beans. > > I've played around with minidom a little in the past, and I'm targetting > python 2.5.1. > > Thanks! Hello, I hope this works: #!/usr/bin/python from BeautifulSoup import BeautifulStoneSoup #If the XML you provided is in a file named 'problem' xml_struc = open('problem','r') soup = BeautifulStoneSoup(xml_struc) list_of_tags = soup.findAll('property') for tag in list_of_tags: if tag['value'] == "9998": tag['value'] = "9999" #or whatever number you like soup_str = str(soup) f = open('output', 'w') f.write(soup_str) f.close() xml_struc.close() From paul at boddie.org.uk Mon Sep 17 17:01:59 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 17 Sep 2007 14:01:59 -0700 Subject: Extracting xml from html In-Reply-To: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> References: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> Message-ID: <1190062919.998077.112810@19g2000hsx.googlegroups.com> On 17 Sep, 22:31, kyoso... at gmail.com wrote: > > What's the best way to get at the XML? Do I need to somehow parse it > using the HTMLParser and then parse that with minidom or what? Probably easiest is to use an XML processing toolkit or library which supports HTML parsing. Since the libxml2 library (written in C) makes a fairly good job of HTML parsing, I would suggest either libxml2dom (for a DOM-like API) or lxml (for an ElementTree-like API) as suitable Python wrappers of libxml2. Of course, HTMLParser or SGMLParser should work, but the programming style is a bit more convoluted unless you're used to XML processing using a SAX-like API. Paul P.S. I'm biased towards libxml2dom, being the developer, but I use it routinely and it generally does the job for me. From wolf_tracks at invalid.com Wed Sep 19 09:23:08 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 19 Sep 2007 06:23:08 -0700 Subject: Tutorial or Example (or Tutorial) of Using Canvas to Produce a Plot In-Reply-To: <1190185249.235840.263260@50g2000hsm.googlegroups.com> References: <13evohih7rkd030@corp.supernews.com> <13f0b2qlvj5ige6@corp.supernews.com> <9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com> <1190185249.235840.263260@50g2000hsm.googlegroups.com> Message-ID: I'm just trying to get some feel for how canvas works. I'm about to modify a program I use for meteor work. It uses canvas to display images, and I plan to draw on the image. For example, I plan to draw compass headings on a circle every 30 degrees. Just warming up to the task. exhuma.twn wrote: > On Sep 18, 11:58 pm, Richard Townsend wrote: >> On Tue, 18 Sep 2007 13:18:36 -0700, "W. Watson" >> >> wrote: >>> Tk is it. I'm really not interested in the others at this point. >> John Grayson's book 'Python and Tkinter Programming' has a chapter on >> plotting Graphs and Charts. You can even download that chapter as a >> PDF file: >> >> http://www.manning-source.com/books/grayson/grayson_ch11.pdf >> >> Seehttp://www.manning.com/grayson/for more info about the book. > > Also, if the graph is really all you need, matplotlib might be a very > interesting choice: > http://matplotlib.sourceforge.net/ > > It's got some user-interface facilities as well. But I never used > those so far. > -- Wayne Watson (Nevada City, CA) Web Page: From f.guerrieri at gmail.com Wed Sep 19 05:23:31 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Wed, 19 Sep 2007 11:23:31 +0200 Subject: How to know the starting point In-Reply-To: <96489.19792.qm@web8706.mail.in.yahoo.com> References: <96489.19792.qm@web8706.mail.in.yahoo.com> Message-ID: <79b79e730709190223o167b4b8g46f12e5ae66a5661@mail.gmail.com> On 9/19/07, Raj kumar wrote: > Hi, > I need help regarding the starting point in python project, > As we can find main() function in java class to know the starting class in > java, > what is the starting point in python project? > How to find the starting point. > Thank you > There is no such thing, you can start where you like: try to write a simple .py file defining some functions and classes and then using them. Then launch the app by python your_file.py, and it will just work. You will often find a test like if __name__ == '__main__': do_something() __name__ is the variable which contains the name of the module. If the module is being run as python your_module.py, the __name__ becomes '__main__' and the condition of the if statement is satisfied. This is a common method to define a starting point for a python application. Keep in mind that many python modules are intended to be imported by other modules and not to be used as standalone applications, but rather as libraries. As such, they don't have a starting point, and the if __name__ == '__main__': test could be used for instance to start a test suite. francesco From gagsl-py2 at yahoo.com.ar Thu Sep 13 00:54:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Sep 2007 01:54:26 -0300 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <1189416604.902880.24370@g4g2000hsf.googlegroups.com> <46e7cdc6$0$12298$426a74cc@news.free.fr> Message-ID: En Wed, 12 Sep 2007 08:30:14 -0300, Bruno Desthuilliers escribi?: > neoedmund a ?crit : >> On Sep 7, 4:07 pm, gu wrote: > (snip pb and code) >>> now, in the second "for" cycle and in functionA() i only 'touch' >>> copyOfA >>> (altering it). as i don't touch the variable "a", i expect it not to be >>> affected by any change, but copyOfA acts like a pointer to a and >>> altering copyOfA's values result in altering the values of "a", so the >>> result that i expect is: > (snip) >> no language act like want you tought, or the assignment operation will >> be too expensive. > > IIRC, php4 was doing copies for arrays... Pascal does copy arrays and structs (records) too. -- Gabriel Genellina From perl4hire at softouch.on.ca Thu Sep 13 10:54:29 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Thu, 13 Sep 2007 10:54:29 -0400 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: Richie Hindle wrote: > [Amer] >> Can you or anyone see anything in the posted code that might be the >> cause? > >> #!/usr/bin/python >> import cgitb; cgitb.enable(display=0, logdir=".") >> import sys >> sys.stderr = sys.stdout >> print "Content-Type: text/html" >> print > > My guess would be that you don't have cgitb in your server environment, or > that you have a bogus one. Rearrange things like this: > > #!/usr/bin/python > print "Content-Type: text/html" > print > import sys > sys.stderr = sys.stdout > import cgitb; cgitb.enable(display=0, logdir=".") > Nope. Same error. Is cgitb not in the standard distribution? Is it needed to print HTML? On my home PC I changed the Apache error logging to 'debug' and got this nugget: [Thu Sep 13 04:16:03 2007] [error] [client 0.0.0.0] (OS 2)The system cannot find the file specified. : couldn't create child process: 720002: hello.py I suspect it would be similar on my hosting server. Is this saying it can't find hello.py or one of the modules? -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From as at hut.at Wed Sep 12 11:26:37 2007 From: as at hut.at (hyena) Date: Wed, 12 Sep 2007 17:26:37 +0200 Subject: is it possible to use different font within one wxpython static text widget? Message-ID: problem is as title, bear me if this too silly or too naive. I use wx.statictext widget to show some information in GUI, there are some numbers in the text to be emphasized in bigger other color. For example, in sentence "the travel speed of this car is 40 km /hour", I would like "40" to be bigger and in red color. I know I can use several statictext to get this effect. But i am quite relucktant to do so since I am quite unfamiliar with manageing the layout of widgets. Is there a convinient way to have this done? Thanks for any .input From newsgroups at debain.org Mon Sep 10 16:04:04 2007 From: newsgroups at debain.org (Samuel) Date: Mon, 10 Sep 2007 20:04:04 +0000 (UTC) Subject: ANNOUNCE: Exscript 0.9.8 Message-ID: Introduction ------------- Exscript is a scripting language for automating Telnet or SSH sessions. It supports a wide range of features, such as parallelization, AAA authentication methods, TACACS, and a very simple template language. Python developers can easily extend Exscript templates using standard Python modules. This release comes with many new features, and the documentation was also greatly improved. Please refer to the project page for documentation. Release 0.9.8 is now feature complete and expected to be the last release before 1.0 stable. New since Exscript 0.9 ----------------------- * Full support for SSH was added. * Greatly improved the prompt detection. This should now work by default with Unix, IOS, JunOS and many more. * Support for assigning variables in the Exscript template. * URL-style hostnames are now supported. * The exscript interpreter now checks regular expressions for correctness at compiled time, not only at runtime. * The "loop" statement now supports iterating over multiple lists in one run. * A deadlock when using TACACS authentication was fixed. * Character noise from telnet control characters is now properly filtered. * Exscript no longer deadlocks if an error occurs while writing to a logfile. * Performance was improved when many hosts are loaded from a text file. Dependencies ------------- Python 2.2 or better Python Crypto module Python pexpect module For SSH support, the "ssh" command line utility (OpenSSH). Download Exscript ------------------ Release: http://exscript.googlecode.com/files/exscript-0.9.8.tgz SVN instructions: http://code.google.com/p/exscript/source Links ------ Exscript project page: http://code.google.com/p/exscript/ Mailing list: http://groups.google.com/group/exscript Bug tracker: http://code.google.com/p/exscript/issues/list Browse the source: http://exscript.googlecode.com/svn/trunk/ From george.sakkis at gmail.com Fri Sep 28 16:08:45 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 28 Sep 2007 20:08:45 -0000 Subject: Python 3.0 migration plans? In-Reply-To: References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <%q0Li.725$ih1.539@nlpi068.nbdc.sbc.com> <1i555ag.9ez4uvf4583jN%aleax@mac.com> Message-ID: <1191010125.107578.67700@g4g2000hsf.googlegroups.com> On Sep 28, 11:53 am, John Nagle wrote: > Alex Martelli wrote: > > John Nagle wrote: > > >> TheFlyingDutchman wrote: > >>> It seems that Python 3 is more significant for what it removes than > >>> what it adds. > > >>> What are the additions that people find the most compelling? > >> I'd rather see Python 2.5 finished, so it just works. > > > And I'd rather see peace on Earth and goodwill among men than _either_ > > Python 3 or your cherished "finished" 2.5 -- the comparison and implied > > tradeoff make about as much sense as yours. > > Insofar as Python has an organization, it's not adequately managing > extension modules. Each extension module has its own infrastructure, > with its own build procedures, its own bug list, and its own maintainers. > There's not even an archive. Unlike CPAN, Cheese Shop is just a directory of > URLs. > > Take a look at how Perl does it. Here are the instructions on > how to contribute to CPAN: > > http://www.cpan.org/modules/04pause.html > > There's a way to get your module into the system, a standardized format, > build, and installation procedure, and an archive which is mirrored. > There's a common bug reporting system. Modules abandoned by their > original developers are not lost, and can be "adopted" by someone else. > > Python doesn't have any of this. And that's far more of a problem > than Python 3.x. Does Perl support extension modules, and if so, are they so prevalent as in Python ? Either case, bringing up CPAN is moot in this case; nothing can force an external open source contributor to maintain or provide binaries for his packages. How is this a problem of the *language* ? George From paddy3118 at googlemail.com Fri Sep 7 03:06:51 2007 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 07 Sep 2007 07:06:51 -0000 Subject: Python and CUDO In-Reply-To: References: <46E05DC0.7090102@glocalnet.net> Message-ID: <1189148811.336283.72920@50g2000hsm.googlegroups.com> On Sep 6, 10:12 pm, Robert Kern wrote: > Veronika Lindstrand Kant wrote: > > Hi! > > I just wonder if there are any plans for building any support using > > NIVIDAS CUDO plattform into python? > > Not into Python itself, but we are working on interfacing with NVIDIA's CUDA, > yes (presuming you actually meant "NVIDIA's CUDA" rather than "NIVIDAS CUDO"). > > http://code.google.com/p/pystream/ > > -- > 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 Maybe you and the CorePy guys at http://www.corepy.org/ could swap notes and give us a similar way to work with these accellerators? - Paddy. From jfine at pytex.org Tue Sep 18 16:06:39 2007 From: jfine at pytex.org (Jonathan Fine) Date: Tue, 18 Sep 2007 21:06:39 +0100 Subject: can Python be useful as functional? (off topic) References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Message-ID: <46F02FCF.7080209@pytex.org> Steve Holden wrote: > You remind me of the conversation between the philosopher and an > attractive lady whom he was seated next to at dinner. He asked her if > she would sleep with him for a million dollars, to which she readily > agreed. So he followed this by asking her if she'd sleep with him for a > dollar. She replied: "No. Do you take me for a prostitutte?", to which > his riposte was "We have already established that fact, and are now > merely haggling about the price". I've seen this before, and it is witty. However, it is perhaps unfair towards the woman. The man, after all, is someone who has offered a woman money in return for sex. The whole story reads differently if we replace 'philosopher' by 'man' and 'attractive lady' by 'woman'. -- Jonathan From yosuke at ccwf.cc.utexas.edu Mon Sep 3 22:31:56 2007 From: yosuke at ccwf.cc.utexas.edu (yosuke at ccwf.cc.utexas.edu) Date: Tue, 4 Sep 2007 02:31:56 +0000 (UTC) Subject: trap setting attribute when the attribute is dict References: <1188845236.417709.307160@50g2000hsm.googlegroups.com> <1188855177.466618.53640@22g2000hsm.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > On Sep 3, 8:47 pm, wrote: > [...] >> My intention was to have a propery 'sum' in my object, and which has sum >> of all the values() of the dict (i have code to make sure that the value >> of dict are all numeric). I could just the propery being calculated >> everytime the property got __getattr__. But I thought that it was >> inefficient to calculate the same number over and over when the value is >> already known. So I was thiking of calculating the number only when the >> dict got modified. >> >> I also experimented with the idea of subclassing dict itself to >> calculate the sum. Is this what would be better solution? > Why not simply have a method to update the dictionary that also keeps > the sum up to date? Something like that: >>>> class MyObj(object): > ... def __init__(self): > ... self._d = {} > ... self._sum = 0 > ... def set_key(self, key, val): > ... self._sum += val - self._d.get(key, 0) > ... self._d[key] = val > ... def get_key(self, key): > ... return self._d[key] > ... def sum(self): > ... return self._sum > ... >>>> a = MyObj() >>>> a.set_key(1, 2) >>>> a.sum() > 2 >>>> a.set_key('a', 10) >>>> a.set_key(1, 5) >>>> a.sum() > 15 >>>> > Of course this is only worth it if you need to use the sum often > enough. > If you update the dictionary a lot but only need the sum from time to > time, then it might not be worth it at all. > Of course you could subclass dict: > class MyDict(dict): > def __init__(self, *args, **kwargs): > self._sum = sum(self.itervalues()) > def __setitem__(self, key, val): > self._sum += val - self.get(key, 0) > dict.__setitem__(self, key, val) > def sum(self): > return self._sum > # overload all other methods that mutate the dict > # to keep _sum up to date >>>> d = MyDict() >>>> d.sum() > 0 >>>> d['a']=5 >>>> d.sum() > 5 >>>> d['b']=10 >>>> d['a']=8 >>>> d.sum() > 18 >>>> Thank you. I will go with subclassing method. -- yosuke kimura Center for Energy and Environmental Resources The Univ. of Texas at Austin, USA From pyth0nc0d3r at gmail.com Tue Sep 18 19:33:51 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Tue, 18 Sep 2007 18:33:51 -0500 Subject: Regular Expressions Message-ID: I'm trying to get the Javascript output on when I match the given value in a var, I want to output that value that I tried to match: Example JS: x = '';//some INNERHTML in a document if(x.innerHTML.match(/(.*)/i)) { valuefound = RegEx.$1; } I've been reading my python book and tutorials and google search and google code search trying to understand and I'm still not quite understanding how to do it. -Lamonte. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Sep 15 00:54:09 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Sep 2007 00:54:09 -0400 Subject: How to avoid overflow errors References: <13em8vnr527rq20@corp.supernews.com> <7xmyvoag7j.fsf@ruckus.brouhaha.com> Message-ID: <46eb6ad1$0$7493$4c368faf@roadrunner.com> On Fri, 14 Sep 2007 22:59:13 -0300, Eduardo O. Padoan wrote: > On 14 Sep 2007 18:08:00 -0700, Paul Rubin > <"http://phr.cx"@nospam.invalid> wrote: >> "Eduardo O. Padoan" writes: >> > Not totally unrelated, but in Py3k, as it seems, overflows are really >> > things of the past: >> > >> > >> > Python 3.0a1 (py3k:58061, Sep 9 2007, 13:18:37) [GCC 4.1.3 20070831 >> > (prerelease) (Ubuntu 4.1.2-16ubuntu1)] on linux2 Type "help", >> > "copyright", "credits" or "license" for more information. >> > >>> class MyInt(int): >> > ... pass >> > ... >> > >>> import sys >> > >>> MyInt(sys.maxint) >> > 2147483647 >> > >>> MyInt(sys.maxint+1) >> > 2147483648 >> >> I'd be interested in knowing what happens in 3.0a1 with >> >> a = itertools.count(sys.maxint) >> print a.next() >> print a.next() > > >>>> print(next(a)) > Traceback (most recent call last): > File "", line 1, in > OverflowError: cannot count beyond PY_SSIZE_T_MAX > > Hum, you've got me there. it is the same as in 2.x. Maybe the message > should be less crypt, at least - nothing that googling for > PY_SSIZE_T_MAX cant help. This should demonstrate that OverflowError will not disappear entirely even in Python 3. Even if we were to get rid of all OverflowErrors resulting from integer operations in Python, there are going to be some C extensions--including some in the Python standard library--that will store 32-bit integers. Modules such as array and struct will still raise it, and probably other modules were a long integer sometimes doesn't make sense (socket, for instance). itertools.count() should work for arbitrary integers, though. Carl Banks From news at sandipan.com Tue Sep 4 21:11:50 2007 From: news at sandipan.com (Sandipan News) Date: Tue, 4 Sep 2007 21:11:50 -0400 Subject: Setting Current Dir in Python In-Reply-To: References: <000001c7eeec$d9341470$8b9c3d50$@net> Message-ID: <012401c7ef59$bf8c9de0$3ea5d9a0$@com> Tim and Gabriel, Thank you so much. I was able to find and remove the special character from the line below and another one after it. The error has now gone away. Thanks also for the chdir solution, though I did not need it this time. The fix above was exactly what it needed to work. I have my utilities chugging along again - What a relief! Thanks again. Sandipan -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of Gabriel Genellina Sent: Tuesday, September 04, 2007 3:27 PM To: python-list at python.org Subject: Re: Setting Current Dir in Python En Tue, 04 Sep 2007 09:12:22 -0300, Sandipan Gangopadhyay escribi?: > I have recently installed Python 2.5.1 and Pythonwin (without any > errors) on > Windows Vista Ultimate. > > Now, the programs run fine within Pythonwin IDE when current directory is > set to the program's directory. > > But, when I double click them from Windows Explorer, the program is not > run. First, fix your source code (either removing the non-ascii character or adding an encoding line at the top, see ) (PEP0263 is enforced from Python 2.5 and up; you got a warning on earlier versions). os.getcwd() returns the current directory. os.chdir() changes the current directory. A shortcut on the desktop may use the desktop itself as the initial directory. If you want to run your script from within the same directory as it resides, try this: os.chdir(os.path.dirname(__file__)) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From gagsl-py2 at yahoo.com.ar Fri Sep 28 00:02:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Sep 2007 01:02:15 -0300 Subject: Emailing the attachment created with the Quick Screenshots Script (Python + PIL) References: <000001c8010b$81864eb0$eafca8c0@tfccorp.intra> Message-ID: En Thu, 27 Sep 2007 10:37:05 -0300, Mark Bratcher escribi?: > The Quick Screenshots Script (Python + PIL) is a "dream come true", and > yet > so simple to use reliably. Does anyone have a suggestion or know how to > include in the script, the ability to email the attachment? This would > make > the dream perfect! Thanks! See the second example from the email package; it creates a MIME message with an attachment and sends it using SMTP. -- Gabriel Genellina From ldo at geek-central.gen.new_zealand Tue Sep 11 02:41:10 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Sep 2007 18:41:10 +1200 Subject: urllib2: handle an error (302) References: Message-ID: In message , Antoni Villalonga wrote: > There are any way to handle a 302 error? I assume the answer you seek is here . From bdesth.quelquechose at free.quelquepart.fr Fri Sep 7 12:28:28 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 07 Sep 2007 18:28:28 +0200 Subject: Organizing Code - Packages In-Reply-To: <1189183088.922537.18290@r34g2000hsd.googlegroups.com> References: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> <46e17143$0$6189$426a74cc@news.free.fr> <1189183088.922537.18290@r34g2000hsd.googlegroups.com> Message-ID: <46e41174$0$21562$426a74cc@news.free.fr> xkenneth a ?crit : >>Ah, yes, a couple of things: >>- avoid the 'one-class-per-file' syndrom. It's perfectly ok to have tens > > > Yes but i find it hard to edit classes easily when I have more than > one class per file. Why so ? Could it be that your classes are growing too fat ? From pavlovevidence at gmail.com Wed Sep 12 12:18:41 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Sep 2007 09:18:41 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: <13efnmi4n959a59@corp.supernews.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <13efnmi4n959a59@corp.supernews.com> Message-ID: <1189613921.112030.243050@k79g2000hse.googlegroups.com> On Sep 12, 8:42 am, Steven D'Aprano wrote: > On Wed, 12 Sep 2007 07:33:45 +0000, Mark Summerfield wrote: > > I feel that Python lacks one useful data structure: an ordered > > dictionary. > > > I find such data structures v. useful in C++. > > [snip] > > Personally, I've never missed an ordered dict. What do people use them > for? I once had a GUI that displayed the contents of a dict as a tree. The user could add entries, and the entries would display at the end. Hence, the ordered dict. I could have kept the order separately, but what was the point? I just whipped up a homemade ordered dict class, it worked fine, and I didn't have to worry about keeping them synchronized. Carl Banks From garyjefferson123 at yahoo.com Fri Sep 21 00:20:59 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: Fri, 21 Sep 2007 04:20:59 -0000 Subject: distutils, extensions, and missing headers In-Reply-To: References: <1190268535.052437.226240@v23g2000prn.googlegroups.com> <1190297193.864613.13890@i13g2000prf.googlegroups.com> Message-ID: <1190348459.466864.179870@e34g2000pro.googlegroups.com> On Sep 20, 12:08 pm, Robert Kern wrote: > Gary Jefferson wrote: > > On Sep 20, 1:22 am, Robert Kern wrote: > >> Use the "headers" keyword to setup() to list theheaderfiles you want installed. > > > I've tried "headers=['header1.h', 'header2.h']" in setup() as well > > as in Extension(), and neither seem to get the files into the bdist or > > bdist_rpm tarball. Am I doing it wrong? I can't seem to find any > > examples that use this via google. > > You might need an accurate relative path. I'm assuming that you don't actually > keep header1.h and header2.h in the top-level directory next to the setup.py. I think I've got it, just needed to do a MANIFEST.in file as in http://groups.google.com/group/comp.lang.python/browse_thread/thread/64ed59544c4c047e/e329ad06c50cff46?lnk=gst&q=distutils+header&rnum=1#e329ad06c50cff46 . Apparently, the headers arg doesn't affect sdist or bdist. With that, the headers get included in the tarballs, and bdist_rpm no longer complains about them. Unfortunately, it now complains about missing .o files. These .o's are built automatically via 'setup.py build', but not via 'setup.py bdist_rpm', for reasons I can't fathom at the moment. But if I figure it out, I'll post here. Gary From pyth0nc0d3r at gmail.com Fri Sep 14 16:12:44 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 14 Sep 2007 15:12:44 -0500 Subject: Just bought Python in a Nutshell In-Reply-To: <1189784843.896396.108960@g4g2000hsf.googlegroups.com> References: <1189784843.896396.108960@g4g2000hsf.googlegroups.com> Message-ID: Right, I like reading books it comes handier then reading ebooks, less programs and its right there in your hands. Main reason I'm going to use it for is to find questions without asking them on the python list or tutor list for a quicker referrence. On 9/14/07, DouhetSukd at gmail.com wrote: > > I respectfully disagree with Shawn, in this case. > > Don't skim Nutshell, unless you know very little Python, and even then > it is really the wrong book. It is rather dry reading and provides > very little of the usual user-friendly introductions to language > features by solving simple problems. > > Doesn't sound like that much of an endorsement, does it? Well, in > fact, it is pretty much my most used Python book (out of 7 or 8 > others). > > If you read Alex's posts in this newsgroup, you'll see that he is one > of the most pragmatic and rigorous posters who usually contributes > code that elegantly and simply solves the issue at hand with the > minimum amount of clutter. > > What Python in a Nutshell is really good at is showing you exactly > what Python is capable of doing, feature by feature, in a thoroughly > Pythonic way for the feature. With code and exact implication. For > example, I know Python well but I am kinda lacking in metaclass > comprehension. If I were to write some non-trivial metaclasses I > would surely have his 3 or 4 pages open on my desk as I write code and > skim through other internet postings. Those 3-4 pages have kinda made > my brain shrivel every time I've looked at them, but they are the > clearest overview I've seen of what is probably one of the hardest > Python features to understand. > > For normal, easy-to-understand Python, Nutshell really dissects the > languages with new insight. The information is dense, because each > word has its place and there very little filler. That's why skimming > it does not work for me, I just don't have the requisite sustained > attention span. > > So, although I read almost all other computer books like Shawn does, I > don't think it applies in this particular case. When you have a > particular aspect of Python in mind, use Nutshell. Read up on 'look > before you leap' in it if you really want a sample of how it is > written. > > Cheers > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Sat Sep 1 03:19:16 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 19:19:16 +1200 Subject: Automation and scheduling of FrontPage publishing using Python References: <1188517723.279932.299400@x40g2000prg.googlegroups.com> Message-ID: In message , Steve Holden wrote: > Lawrence D'Oliveiro wrote: > >> If they were using FrontPage extensions, they deserve everything they >> get. > > While possibly justifiable, given that FrontPage has had holes you could > drive a London double-decker but through since time immemorial, it isn't > a terribly helpful observation. Just to remove any possible doubt: FrontPage must die. But if you want that expressed in less confrontational, more customer-friendly words, how about this: They need to engage the services of an expensive consultant or two, who will bill them lots of hours working out an approach which may involve migrating to a technology with better long-term prospects, or simply stitching together a Frankenhack or two to eke a bit more life out of their existing system, until it finally collapses altogether. Either way, they need to spend the folding stuff, and lots of it. Asking for help on a forum where people are more liable to throw brainpower rather than money at problems, is a waste of time. From piyushj at cse.iitk.ac.in Thu Sep 27 12:52:39 2007 From: piyushj at cse.iitk.ac.in (Piyush Jain) Date: Thu, 27 Sep 2007 22:22:39 +0530 Subject: making run time changes.. In-Reply-To: References: <000001c80107$4f9ff120$eedfd360$@iitk.ac.in> Message-ID: <002f01c80126$d08aee10$71a0ca30$@iitk.ac.in> Hi, It seems that pyro provides remote access to object acting as middleware. My requirement is a bit different. It need not be remote. But I need to make run time changes at the running program, say changing it's functionality. More in lines of dynamic modules, but triggered by messages from outside. Regards, Piyush -----Original Message----- From: python-list-bounces+piyushj=cse.iitk.ac.in at python.org [mailto:python-list-bounces+piyushj=cse.iitk.ac.in at python.org] On Behalf Of Steve Holden Sent: Thursday, September 27, 2007 9:05 PM To: python-list at python.org Subject: Re: making run time changes.. Piyush Jain wrote: > Hi, > > I am new(almost) to python. I wish to making a server in which I can > make changes at run time. For example , add a method to a > class/attribute to object etc. by sending it messages. > > Can anyone help me with what features to look into and how to go about > it. Are there any similar projects? > Take a look at Pyro (Python remote objects). It can almost certainly do what you want. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline -- http://mail.python.org/mailman/listinfo/python-list From egbert.bouwman at hccnet.nl Fri Sep 28 05:46:58 2007 From: egbert.bouwman at hccnet.nl (egbert) Date: Fri, 28 Sep 2007 11:46:58 +0200 Subject: Python 3.0 migration plans? In-Reply-To: References: Message-ID: <20070928094658.GB3589@hccnet.nl> On Thu, Sep 27, 2007 at 09:17:30PM -0400, Steve Holden wrote: > So what we need is a poll on what the questions should be. I *love* c.l.py. I will switch as soon as Debian has all the tools for an easy conversion available, and Python 3000 has reached the default release status. e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From joel.hedlund at gmail.com Tue Sep 25 18:12:33 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 26 Sep 2007 00:12:33 +0200 Subject: What is a good way of having several versions of a python module installed in parallell? In-Reply-To: References: <5ls95aF9pq3gU1@mid.uni-berlin.de> Message-ID: First of all, thanks for all the input - it's appreciated. > Otherwise, three words: > > test driven development Do you also do this for all the little stuff, the small hacks you just whip together to get a particular task done? My impression is that doing proper unittests adds a lot of time to development, and I'm thinking that this may be a low return investment for the small programs. I try to aim for reusability and generalizability also in my smaller hacks mainly as a safeguard. My reasoning here is that if I mess up somehow, sooner or later I'll notice, and then I have a chance of making realistic damage assessments. But even so, I must admit that I tend to do quite little testing for these small projects... Maybe I should be rethinking this? Cheers! /Joel From russell.no.spam at gmail.com Tue Sep 18 01:45:14 2007 From: russell.no.spam at gmail.com (Russell Wallace) Date: Tue, 18 Sep 2007 06:45:14 +0100 Subject: The meaning of a = b in object oriented languages In-Reply-To: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> Message-ID: Summercool wrote: > so most or all object oriented language do assignment by reference? > is there any object oriented language actually do assignment by > value? I kind of remember in C++, if you do > > Animal a, b; > > a = b will actually be assignment by value. > while in Java, Python, and Ruby, there are all assignment by > reference. ("set by reference") > > Is that the case: if a is an object, then b = a is only copying the > reference? Yes, your understanding is exactly correct; C++ will assign by value unless you explicitly use pointers, but the other languages will assign by reference (except for primitive types). -- "Always look on the bright side of life." To reply by email, replace no.spam with my last name. From nagle at animats.com Thu Sep 20 16:12:29 2007 From: nagle at animats.com (John Nagle) Date: Thu, 20 Sep 2007 13:12:29 -0700 Subject: M2Crypto 0.18 - new version, same old build bugs. Message-ID: Back in March, I posted this: > Hit that with OpenSSL. Red Hat took elliptical curve cryptography > out of Fedora 6 for patent reasons. With that missing, M2Crypto won't > build. It ought to; the implementor of M2Crypto thought of that, because > it's an optional feature. But M2Crypto uses SWIG. SWIG doesn't normally > process nested include files. OpenSSL had changed their configuration > approach to use nested include files. So SWIG didn't see the #define that > said to turn off elliptical curve crypto support. This resulted in > compile errors in the 24,000 lines of code that come out of SWIG. That was for M2Crypto 0.17. It's still broken in M2Crypto 0.18. And there's no RPM or Windows binary. Nobody actually uses this stuff, do they? John Nagle From Sebastien.Boisgerault at gmail.com Fri Sep 7 13:02:04 2007 From: Sebastien.Boisgerault at gmail.com (S bastien Boisg rault) Date: Fri, 07 Sep 2007 10:02:04 -0700 Subject: Speed of Python In-Reply-To: References: Message-ID: <1189184524.709954.242230@o80g2000hse.googlegroups.com> On Sep 7, 6:42 pm, "wang frank" wrote: Matlab (aka MATrix LABoratory) has been designed with numeric computations in mind (every object being natively a n-dim array). If you wish to develop that kind of applications in Python, consider using the numerical array structure provided by Numpy. Numpy being mostly written in C, that should speed up your application ... In this context, additional 3rd party libs such as Scipy, Matplotlib, PIL, etc. will also be useful. Cheers, SB > Hi, > > While comparing the speed of octave and matlab, I decided to do a similar > test for python and matlab. The result shows that python is slower than > matlab by a factor of 5. It is not bad since octave is about 30 time slower > than matlab. > > Here is the result in matlab: > Elapsed time is 0.015389 seconds. > > and in Python:>>> t=timeit.Timer("bench1.bench1(10)","import bench1") > >>> t.repeat(1,1) > > [0.071012377266015392] > > Here is the bench1.py: > import math > def bench1(n): > for i in range(n): > for j in range(1000): > m=j+1 > z=math.log(m) > z1=math.log(m+1) > z2=math.log(m+2) > z3=math.log(m+3) > z4=math.log(m+4) > z5=math.log(m+5) > z6=math.log(m+6) > z7=math.log(m+7) > z8=math.log(m+8) > z9=math.log(m+9) > return z9 > > Is my conclusion correct that Python is slower than matlab? Are there any > way to speed it up? It seems Python automatically created bench1.pyc. Does > Python automatically execute the bench1.pyc to speed it up? > > Thanks > > Frank > > _________________________________________________________________ > ???????? ?????????????????????????http://chizumaga.jp/ From spam.noam at gmail.com Mon Sep 17 19:39:36 2007 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: Mon, 17 Sep 2007 23:39:36 -0000 Subject: How can I know how much to read from a subprocess In-Reply-To: <1190070896.332844.23080@22g2000hsm.googlegroups.com> References: <1190070896.332844.23080@22g2000hsm.googlegroups.com> Message-ID: <1190072376.600475.254260@y42g2000hsy.googlegroups.com> Ok, I could have researched this before posting, but here's an explanation how to do it with twisted: http://unpythonic.blogspot.com/2007/08/spawning-subprocess-with-pygtk-using.html It seems that another solution is gobject.io_add_watch, but I don't see how it tells me how much I can read from the file - if I don't know that, I won't know the argument to give to the read() method in order to get all the data: http://www.pygtk.org/docs/pygobject/gobject-functions.html#function-gobject--io-add-watch Noam From ratchetgrid at googlemail.com Thu Sep 27 12:16:29 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Thu, 27 Sep 2007 17:16:29 +0100 Subject: Pb with an AttributeError In-Reply-To: <676224240709270915x537a6426h1512cbddccb5c68f@mail.gmail.com> References: <676224240709270915x537a6426h1512cbddccb5c68f@mail.gmail.com> Message-ID: <676224240709270916w5a82ffd3ycf095bd5605a0915@mail.gmail.com> Did I just help someone with their homework? Hope not :S On 27/09/2007, Nathan Harmston wrote: > Hi, > > I m not sure what your trying to do, but this is where your problem is: > > string1 is not a string it is actually a dict because of your eval. > When you call > string1["param"] inside the string.split() > > it is returning a dictionary and not a string.... > 'param': {'key': 'SP<136>=', 'value': ['SD:<0> ']} > > since {'key': 'SP<136>=', 'value': ['SD:<0> ']} is inside curly > brackets it is a dictionary. > > I still dont get what your trying to have as your final result, but > hope this helps. > > Thanks > > Nathan > > On 27/09/2007, Eric BOUVIER wrote: > > > > > > > > Hello, > > > > First, sorry for my english. > > > > I've just been assigned a project written in Python which contains bug(s). > > I've never programmed in Python, but I've read the code > > and understood basically what the different source codes do. > > > > I've traced the code and found where the problem is but I don't > > know how to solve the problem. > > > > Here it is : > > > > I've got a string issued from a CSV file : > > string1 = eval(line[4]) > > print " * string1 = (", string1 ,") \n" > > => * string1 = ( {'header': 'X-Score', 'param': {'key': 'SP<136>=', > > 'value': ['SD:<0> ']} ) > > > > Then, there is a split with the equal : > > TheParts = string.split(string1["param"], "=") > > print " * TheParts = (", TheParts ,") \n" > > > > But, running the program returns : > > > > Traceback (most recent call last): > > File "C:\test\helper.py", line 136, in Action_handler > > Score_eval(line, OutputFile_SP, This_Host) > > File "C:\test\helper.py", line 66, in Score_eval > > TheParts = string.split(string1["param"], "=") > > File "C:\ActiveState\Python25\lib\string.py", line 290, > > in split > > return s.split(sep, maxsplit) > > AttributeError: 'dict' object has no attribute 'split' !?! > > > > I've found that it works when I put directly the string in the split > > expression : > > > > TheParts = string.split(" {'key': 'ESP<136>=', 'value': ['SHA:<0> ']} ", > > "=") > > => * TheParts = ["{'key': 'ESP<136>", "', 'value': ['SHA:<0> ']}"] > > > > But the code isn't dynamic anymore ! > > I think it's a problem with the type, but the different syntax I've tried > > didn't work. > > Is somebody could help me ? > > > > Thank you > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From nutsbreaker1 at gmail.com Sat Sep 15 12:27:12 2007 From: nutsbreaker1 at gmail.com (nutsbreaker1 at gmail.com) Date: Sat, 15 Sep 2007 16:27:12 -0000 Subject: Need a guitar? Message-ID: <1189873632.248697.163620@19g2000hsx.googlegroups.com> Free guitars here!!!!!! http://freeguitars.blogspot.com/ From carsten at uniqsys.com Mon Sep 10 09:58:25 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 10 Sep 2007 09:58:25 -0400 Subject: Using a time duration to print out data where every 2 seconds is a pixel In-Reply-To: References: <1189427545.322679.260970@r29g2000hsg.googlegroups.com> Message-ID: <1189432705.3385.31.camel@dot.uniqsys.com> On Mon, 2007-09-10 at 15:48 +0200, A.T.Hofkamp wrote: > I have seen references to a module called datetime, but I have never used such > module so no idea what it is or where to get it. You get it by using a non-ancient version of Python. It's been part of the standard library since Python 2.3. -- Carsten Haese http://informixdb.sourceforge.net From willshak at 00hvc.rr.com Fri Sep 28 08:18:11 2007 From: willshak at 00hvc.rr.com (willshak) Date: Fri, 28 Sep 2007 08:18:11 -0400 Subject: Traveling Europe In-Reply-To: References: <1190907679.164542.149190@19g2000hsx.googlegroups.com> Message-ID: <13fps837vh5cpf9@news.supernews.com> on 9/27/2007 10:43 PM Eric Sosman said the following: > freeaircon at gmail.com wrote: >> World's most popular traveling destinations >> >> http://... > > "Nobody goes there any more; it's too crowded." -- LPB > Besides, "It gets late there early" -- LPB -- Bill In Hamptonburgh, NY To email, remove the double zeroes after @ From lasses_weil at klapptsowieso.net Tue Sep 11 06:06:17 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Tue, 11 Sep 2007 12:06:17 +0200 Subject: Checking if elements are empty In-Reply-To: References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> <46e2013a$0$7687$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <46e66899$0$4534$9b4e6d93@newsspool3.arcor-online.net> Steve Holden wrote: > Neil Cerutti wrote: > >>> y = "" > >>> if y[0] == "": > ... print "True" > ... else: > ... print "False" > ... > Traceback (most recent call last): > File "", line 1, in > IndexError: string index out of range > >>> > Uhm, weren't we talking about a list of strings? /W From quentel.pierre at wanadoo.fr Sun Sep 16 12:53:34 2007 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sun, 16 Sep 2007 09:53:34 -0700 Subject: Processing drag & drop on the desktop Message-ID: <1189961614.510561.194610@w3g2000hsg.googlegroups.com> Hi all, I would like to create an application on a Windows machine, such that when a document is dragged and dropped on the application icon on the desktop, the document is processed by the application For instance, if I drag & drop an Outlook message or a PPT presentation, the application would propose to tag the document with keywords taken from a database Is it possible to do this with a Python script, and how ? Regards, Pierre From http Sun Sep 16 12:12:56 2007 From: http (Paul Rubin) Date: 16 Sep 2007 09:12:56 -0700 Subject: Needless copying in iterations? References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> <13epv3fnb6bak15@corp.supernews.com> <5l4ghuF655kfU2@mid.uni-berlin.de> <13eqc2daojgho03@corp.supernews.com> Message-ID: <7xzlzmoagn.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > What do you mean by Haskell is a dynamic language? It is statically and > > strict typed and the compiler usually knows all the functions. No > > "surprises", no side effects, no duck typing. > > Haskell's IO monad (and possibly the do monad?) allows side effects. It > would be a pretty poor programming language that didn't allow input or > output! In a certain theoretical sense, input and output in the IO monad are not side effects. Side effects means you can somehow distinguish between calling f(x) twice with the same value of x, and calling it just once. In Haskell, the print function does an output operation (called an "action") but if I understand it right, it turns out you cannot call the print function twice with the same argument. Of course you can say main = do { print "hello"; print "hello" } and that prints "hello" twice, but the do statement is syntactic sugar that turns the above into approximately like (the exact mechanism is a bit hairier): x = (special token representing the state of the external world) y = print ("hello", x) # y is the new external world state z = print ("hello", y) # z is another new state so print receives a different arg each time. (Note that every Haskell function has exactly one argument, so f(x,y) means call f, giving it the tuple (x,y) as an argument). > See also http://homepages.cwi.nl/~ralf/OOHaskell/ > showing that Haskell can do object-oriented programming, complete with > mutable objects and side-effects. Although "duck typing" is listed as a > keyword, I couldn't see any reference to it in the paper. That describes an OO extension to Haskell, which I suppose is interesting, but it's not Haskell. You could also bolt a Python interpreter into Haskell and that would not be Haskell either. > Haskell uses type inference, and has a "maybe" type for those cases where > it can't tell what the type will be. Type inference just means the static type system doesn't rely on declarations. Like when you say 3+4 in C++ or Java, the compiler figures out that is an integer expression, but if you say x = 3 + 4 without an "int x" declaration, the compiler complains. Haskell goes a little further and lets you say x = 3 + 4 and the compiler says "ok, now I know that x is an integer". If you later try to concatenate x with a string: y = x ++ "hello" you get a compile time error message. In a dynamic language like Python you would not get the error message til runtime. That is the difference between a static and dynamic language. The Maybe monad is still a static type. You can think of it as a statically typed list with a maximum of one element, i.e. a Maybe Int can have values like [3] (denoted "Just 3") or like [] (the empty list, denoted Nothing). It cannot have a value like "foo" or [3.14159] or [[7]] or [2,3,4]. You get compile time error messages if you try to assign those values to it. Of course you can have a Maybe Float (like [3.14159]) or a Maybe (Maybe Int) (like [[7]]). > If you still don't accept that Haskell is a dynamic language, for > whatever definition of dynamic language you use, I'll withdraw the claim > for the sake of not getting bogged down in long arguments over something > that was really just a minor point. Haskell is certainly not a dynamic language in the usual sense of that term. From bj_666 at gmx.net Mon Sep 10 10:32:40 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2007 14:32:40 GMT Subject: How do I read and write to the same CSV file References: <1189434466.001109.313060@d55g2000hsg.googlegroups.com> Message-ID: <5kl2s8F3vfqqU9@mid.uni-berlin.de> On Mon, 10 Sep 2007 07:27:46 -0700, Chris wrote: > if date == 0: > date = os.getmtime() > # now this is where I want to write into the row of the same csv > file but only updating that one field > > How can I do this? You can't. Modifying text files with variable length lines is "impossible" or at least not worth the trouble because if the replacement line does not have the very same length, all lines after that changed line have to be moved, i.e. rewritten anyway. Write the rows to another file and modify the desired entry on the fly and rename the temporary file to the source file's name afterward. Ciao, Marc 'BlackJack' Rintsch From larry.bates at websafe.com Wed Sep 12 16:55:35 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 12 Sep 2007 15:55:35 -0500 Subject: I want py2exe not to create library.zip In-Reply-To: References: Message-ID: <3P6dnfdlGPbez3XbnZ2dnUVZ_oaonZ2d@comcast.com> Laszlo Nagy wrote: > > Hi, > > I want py2exe not to create library.zip. My reason is that the installed > program will be a self updating program, and it must be able to download > changes (newer python source files) from the server. So the files should > not be in library.zip. I tried the --bundle option but apparently it can > only be used to make the distribution __more__ bundled. > > Thanks, > > Laszlo > That is correct. People want less files to distribute not more. People complain on py2exe list that it doesn't create a single .EXE file. Don't try to update the program via patching "pieces". Wrap everything in a proper installer (I use and highly recommend Inno Setup). It can handle version control, there is a plug-in for over-the-wire updates, etc. Best way I know of to automate everything. -Larry From tjreedy at udel.edu Sat Sep 22 16:23:42 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Sep 2007 16:23:42 -0400 Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> Message-ID: "Carl Banks" wrote in message news:46f49740$0$32514$4c368faf at roadrunner.com... | | Is it worth it to make such a change? It would remove a lot of operators | (11 by my count), vastly simplifying syntax, Which, IMHO, is no small | thing. New numerical types would have fewer operations to support. Py3 adds an abstract base class module. Bit-integers (with the above operations) are a separate subclass of abstract int/rats (forget the detail), so new numerical types do not have to support those ops unless declared as deriving from the bit-int class. Some people consider having lots of operators available to overload in their classes to be a good thing. Operator notation is much nicer that function notation for binary functions.mapping pairs of objects of a class to an object of the class. tjr From jstroud at mbi.ucla.edu Thu Sep 13 18:30:50 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 13 Sep 2007 15:30:50 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> Message-ID: James Stroud wrote: > set_value_at -> set_value (not simply set) Actually, 'set' seems better than set_value. From steve at holdenweb.com Thu Sep 27 18:17:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 18:17:26 -0400 Subject: Importing Module To Use Variables In A Second Module In-Reply-To: References: Message-ID: rshepard at nospam.appl-ecosys.com wrote: > I'm stymied by what should be a simple Python task: accessing the value of > a variable assigned in one module from within a second module. I wonder if > someone here can help clarify my thinking. I've re-read Chapter 16 (Module > Basics) in Lutz and Ascher's "Learning Python" but it's not working for me. > > In one module (the "source"), variablePage.py, three wxPython widgets > display values that are assigned to variables: curVar, UoDlow, and UoDhigh. > I want to display then in equivalent widgets on a wxPython notebook tab in a > different module, the "importer." > > At the top of the importer module I have: > > from variablePage import curVar, UoDlow, UoDhigh > > and I try to display the values of those variables in widgets on this page. > But, python complains: > > from variablePage import curVar, UoDlow, UoDhigh > ImportError: cannot import name curVar > > I've also tried > > import variablePage as VP > > and referenced the variables as VP.curVar, VP.UoDlow, and VP.UoDhigh, but > python still doesn't like this: > > File "/data1/eikos/fuzSetPage.py", line 364, in loadParVar > first = VP.curVar > AttributeError: 'module' object has no attribute 'curVar' > > Both of these forms are used in the book (pages 260-261) in simple > examples. I also get errors if I try importing using the class name before > the variable name. > > A clue stick would be very helpful since I am not seeing just what I'm > doing incorrectly. > > Rich Self-evidently you are *not* creating the variables you think you are in the variablePage module. Have you tried an interactive test? Try this at the interpreter prompt: >>> import variablePage >>> dir(variablePage) and you will see exactly what names the module is defining in its namespace. You could also try >>> variablePage.__file__ to make sure that you are importing the module you think you are. Otherwise, do you have circular imports? In other words, does the variablePage module by any chance import the module that's trying to import *it*? That's also a fruitful source of errors. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From hall.jeff at gmail.com Sat Sep 29 11:47:24 2007 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Sat, 29 Sep 2007 15:47:24 -0000 Subject: Program inefficiency? In-Reply-To: <13fss68juscn33@corp.supernews.com> References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> <13fss68juscn33@corp.supernews.com> Message-ID: <1191080844.248426.316340@g4g2000hsf.googlegroups.com> I did try moveing the re.compile's up and out of the replacecylce() but it didn't impact the time in any meaningful way (2 seconds maybe)... I'm not sure what an shell+sed script is... I'm fairly new to Python and my only other coding experience is with VBA... This was my first Python program In case it helps... We started with only 6 loops of replacecycle() but had to keep adding progressively more as we found more and more links with lots of spaces in them... As we did that, the program's time grew progressively longer but the length grew multiplicatively with the added number of cycles... This is exactly what I would have expected and it leads me to believe that the problem does not lie in the replacecycle() def but in the masseditor() def... *shrug* From jeff at taupro.com Mon Sep 3 05:16:54 2007 From: jeff at taupro.com (Jeff Rush) Date: Mon, 03 Sep 2007 04:16:54 -0500 Subject: The Texas Python Unconference is Almost Here! Message-ID: <46DBD106.7090901@taupro.com> The first regional Python unconference is coming to Houston on September 15-16 (Sat-Sun). Being held at the Texas Learning & Computing Center on the University of Houston main campus, this is a FREE event for Pythoneers from all over the Texas region. http://pycamp.python.org/Texas/ And being an unconference, participation by those who attend is welcome and greatly sought. The topics to be presented are purely up to the attendees. Details about the facility and a sign-up registration list is available on the wiki. Please add your name if you think you might attend, so that we can have some estimate of who is coming. Also add to the wiki topics on which you are coming prepared to present, or that you would like to see. Often people can present on many topics but don't know what others are interested in. And a big thanks go out to Robin Friedrich and those in Houston for hosting us. Let's roll up our sleeves and help them out! Involvement is key to making an unconference successful. For those not familiar with unconferences, check out this description: http://en.wikipedia.org/wiki/Unconference See you all there... Jeff Rush Python Advocacy Coordinator P.S. Please repost this to other Texas Python organizations. From andre.roberge at gmail.com Fri Sep 7 15:15:04 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Fri, 07 Sep 2007 19:15:04 -0000 Subject: Is a Borg rebellion possible? (a metaclass question) In-Reply-To: References: <1189168282.665210.260840@19g2000hsx.googlegroups.com> <1189180478.257790.60160@g4g2000hsf.googlegroups.com> Message-ID: <1189192504.062833.140500@y42g2000hsy.googlegroups.com> On Sep 7, 4:00 pm, Carsten Haese wrote: > On Fri, 2007-09-07 at 15:54 +0000, Andr? wrote: > > Unfortunately, it fails. Here's what I tried, followed by the > > traceback > > class SplinterBorg(object): > > _shared_states = {} > > def __new__(cls, *a, **k): > > group = k.pop("group","BORG") > > obj = object.__new__(cls, *a, **k) > > obj.__dict__ = cls._shared_states.setdefault(group,{}) > > return obj > > > class MyClass(SplinterBorg): > > def __init__(self, name): > > self.name = name > >[...] > > Traceback (most recent call last): > > File "test.py", line 15, in > > b1 = MyClass('b', group="B") > > TypeError: __init__() got an unexpected keyword argument 'group' > > Indeed, if you have an __init__ method that shouldn't see the "group" > argument, you need a metaclass after all so you can yank the "group" > argument between __new__ and __init__. The following code seems to work, > but it's making my brain hurt: > > class SplinterBorgMeta(type): > def __call__(cls, *args, **kwargs): > inst = cls.__new__(cls, *args, **kwargs) > kwargs.pop("group",None) > inst.__init__(*args,**kwargs) > return inst > > class SplinterBorg(object): > __metaclass__ = SplinterBorgMeta > _shared_states = {} > def __new__(cls, *a, **k): > group = k.pop("group","BORG") > obj = object.__new__(cls, *a, **k) > obj.__dict__ = cls._shared_states.setdefault(group,{}) > return obj > > class MyClass(SplinterBorg): > def __init__(self, name): > self.name = name > > The alternatives, as Steve just pointed out, would be not to subclass > SplinterBorg or to provide an __init__ method that expects a "group" > argument. > > HTH, > Thanks for your reply. I will try to adapt it and see if it works in my case. Andr? > -- > Carsten Haesehttp://informixdb.sourceforge.net From frikimaster at gmail.com Tue Sep 11 08:01:37 2007 From: frikimaster at gmail.com (Antoni Villalonga) Date: Tue, 11 Sep 2007 14:01:37 +0200 Subject: urllib2: handle an error (302) In-Reply-To: References: Message-ID: <75eeb70e0709110501x2bfd926cxc3048fa273ac3a01@mail.gmail.com> 2007/9/11, Lawrence D'Oliveiro: > In message , Antoni > Villalonga wrote: > > > There are any way to handle a 302 error? > > I assume the answer you seek is here > . > -- > http://mail.python.org/mailman/listinfo/python-list > Yes I read it, but I don't stand how to use it. I'm looking for an example of error handlers. Thanks! -- "Boring two-person multiplayer may turn friends into enemies." Antoni Villalonga i Noceras #Bloc# ~> http://friki.CAT #Jabber# ~> friki at bulmalug.net From jfine at pytex.org Wed Sep 19 02:38:07 2007 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 19 Sep 2007 07:38:07 +0100 Subject: [ANN] Metatest 0.1.0 References: <87sl5by343.fsf@benfinney.id.au> <46F0633E.7020304@pytex.org> <87d4wfxw96.fsf@benfinney.id.au> Message-ID: <46F0C3CF.7090505@pytex.org> Ben Finney wrote: > [Jonathan, please don't send me copies of messages sent to the > discussion thread. I follow comp.lang.python via a non-mail interface, > and it's irritating to get unwanted copies of messages via email.] [Thank you for letting me know your preference. For myself, I often appreciate it when people send me a copy directly.] >>The line >> plus(2, '', _ex=TypeError) >>causes something to be recorded, > That's confusing, then, for two reasons: > > It looks like '_ex' is an argument to the 'plus' function, which > otherwise (probably by design) looks exactly like a call to the 'plus' > function the programmer is testing. Actually, 'plus' above is an instance of a class (which for now we will call PyUnknown) that has a __call__ method. We know this because we imported it from metaclass.py.mymod. It is, if you like, a /test surrogate/ or /instrumented wrapper/ for the function 'plus' in mymod. And as such it has different properties. For example, the '_ex' parameter has a special significance. > Since this is, instead, an > assertion *about* that function, it is misleading to see it as an > argument *to* the function. Although, by design, it looks like an argument to 'plus' in mymod, it is as I said an argument to 'plus' in metatest.py.mymod, which is something completely different, namely a PyUnknown object. We can think of test-first programming as 1. Stating the problem to be solved. 2. Solving that problem. In mathematics, we often use unknowns when stating problems. We can think of a PyUnknown as being analogous, in programming, to the unknowns we use in mathematics. However, if the difference confuses one (and it can in some situations), then instead do from metatest.py.mymod import plus as mt_plus and then the confusing line becomes mt_plus(2, '', _ex=TypeError) which I think you will find much clearer. > It uses the "leading-underscore" convention which means "this is not > part of the public interface, and you'd better know what you're doing > if you use this externally". This convention is exactly that, a convention. Conventions allow us to communicate efficiently, without spelling everything out. Implicit in metatest are some other conventions or the like. Oh, and this use of metatest does confirm to the convention, and extra knowledge is required to use leading underscore parameters. >>Finally, if you can think of a better way of saying, in Python, "The >>function call plus(2, '') raises a TypeError", please let me know, >>and I'll consider using it in the next version of Metatest. > > I would think an explicit function call that says what it's doing > would be better. The unittest module implements this as: > > self.failUnlessRaises(TypeError, plus, 2, '') > which has the benefit of being explicit about what it's doing. Well, you did not tell me what self is (althout I guessed it is an instance of a subclass of unittest.TestCase). Nor did you tell me that this statement is part of a class method. To my eye, your example puts the focus on failUnlessRaises and on TypeError. I think the metatest way puts an equal focus on calling plus(2, '') and the result of this call. I give a comparison of three ways of writing tests in my slides: http://metatest.sourceforge.net/doc/pyconuk2007/metatest.html#slide13 To summarise: both metatest and unittest require the user to know something. Once that something is known, the choices for the crucial test line are plus(2, '', _ex=TypeError) self.failUnlessRaises(TypeError, plus, 2, '') I hope you know find the first option less confusing. (It certainly is shorter.) -- Jonathan From bignose+hates-spam at benfinney.id.au Tue Sep 25 21:24:37 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 26 Sep 2007 11:24:37 +1000 Subject: Python XML API's that preserve XML comments? References: Message-ID: <871wcmmd62.fsf@benfinney.id.au> Dan Stromberg writes: > Are there any python XML parsing API's that preserve comments (I think you mean "python XML parsing libraries"; it's the library, not the API, that preserves comments or not.) I don't have an answer, but this may help to get more information. The XML 1.0 specification allows for, but does not require, retention of comments for access by the application: 2.5 Comments [Definition: .... an XML processor MAY, but need not, make it possible for an application to retrieve the text of comments. ...] -- \ "Demagogue: One who preaches doctrines he knows to be untrue to | `\ men he knows to be idiots." -- Henry L. Mencken | _o__) | Ben Finney From fredrik at pythonware.com Wed Sep 26 08:23:16 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 14:23:16 +0200 Subject: setuptools without unexpected downloads In-Reply-To: <1190808836.056298.232640@57g2000hsv.googlegroups.com> References: <87ejgmklep.fsf@benfinney.id.au><874phhlupi.fsf@benfinney.id.au> <5lumarFae888U1@mid.uni-berlin.de> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> <5luv0iFaai82U1@mid.uni-berlin.de> <1190808836.056298.232640@57g2000hsv.googlegroups.com> Message-ID: Paul Boddie wrote: > P.S. Of course, the package maintainer problem manifests itself most > prominently on Windows where you often see people asking for pre-built > packages or installers. for the record, I'd love to see a group of volunteers doing stuff like this for Windows. there are plenty of volunteers that cover all major Linux/*BSD distributions (tons of thanks to everyone involved in this!), but as far as I can remember, nobody has ever volunteered to do the same for Windows. From steve at holdenweb.com Fri Sep 14 11:16:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Sep 2007 11:16:03 -0400 Subject: newbee: Simple Backend Python Script Question In-Reply-To: <372de840709140727x65b58400jadccb24bbabbdf62@mail.gmail.com> References: <372de840709140727x65b58400jadccb24bbabbdf62@mail.gmail.com> Message-ID: joe shoemaker wrote: > I need to create python script that is threaded. So the main program > will run in infinite loop and just retrieving messages and putting them > in a queue. (Main thread) > > I need child threads from a pool to process the queue. When there is no > stuff in the queue, they go to the pool and become available but they > don't terminate. This has to be done continuously. > > Main program need to keep putting stuff in the queue, when there are no > messages, then it sleeps for short time and check back to see any messages. > > To do this, I guess you don't write joinAll(), so that the main threads > just don't wait for the child but goes to work. > > am I right? > Pretty much. The way I usually do this is to start a number of threads reading work items of some sort from a Queue.Queue. The thread will block automatically if there's nothing on the queue, resuming when something appears (and if I want orderly termination I use None as a dummy work unit, and the threads terminate when they receive a None, but any sentinel value would do). > Also, child threads (a function that is threaded) will make connecitons > to the database. I am planning to use threadpool, so that threads reuse > the connections. So do you close the database connection at the end of > the function? If not then the connection will be opened forever? > You don't want a thread pool, you want a connection pool, but there's little advantage to having one that is only shared between your threads. You really need a system-wide connection pool. Alternatively, you might find that your database module is thread-safe to the extent that different threads can use cursors created on the same connection without interference. If you want each thread to be able to process transactions that are invisible to the other threads before they are committed you should ensure that you have a sufficient isolation level, which might imply the need for a connection-per-thread architecture, in which case you might expect some benefit from connection pooling. regards Steve regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From horpner at yahoo.com Sun Sep 16 18:10:45 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sun, 16 Sep 2007 22:10:45 GMT Subject: Parsing problems: A journey from a text file to a directory tree References: <1189958074.670245.17910@n39g2000hsh.googlegroups.com> Message-ID: On 2007-09-16, Martin M. wrote: > Hi everybody, > > Some of my colleagues want me to write a script for easy folder and > subfolder creation on the Mac. > > The script is supposed to scan a text file containing directory trees > in the following format: > > [New client] >|-Invoices >|-Offers >|--Denied >|--Accepted >|-Delivery notes Would it make sense to store it like this? [('New client', [('Invoices', []), ('Offers', [('Denied', []), ('Accepted', [])]), ('Delivery notes', [])]] > First I thought of an array like this: > > dirtreedb = {'New client': {'Invoices': {}, 'Offers': {'Denied': {}, > 'Accpeted': {}}, 'Delivery notes': {}}} A dictionary approach is fine if it's OK for the directories to be unordered, which doesn't appear to be the case. > But this doesn't do the trick, as I also have to save the > hierarchy level of the current folder as well... The above does store the hierarchy, as the number of nesting levels. ditreedb['New Client']['Offers']['Denied'] -- Neil Cerutti From google at mrabarnett.plus.com Mon Sep 10 18:41:07 2007 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 10 Sep 2007 15:41:07 -0700 Subject: Silent SaveAs when using the Excel win32com module In-Reply-To: References: <1189439861.200686.245420@k79g2000hse.googlegroups.com> Message-ID: <1189464067.350512.285230@k79g2000hse.googlegroups.com> On Sep 10, 5:24 pm, "Hamilton, William " wrote: > > From: Chris > > > I'm trying to create an excel file which will act as a log, however I > > want to overwrite the file if it exists. > > > Looking at the SaveAs method I can't find anything that would allow > > it. I don't want the prompt to appear to ask whether to replace the > > file or not. I just want to replace it without thinking. > > > Thanks in advance. > > Check if the file exists and delete it before saving the new one. > It's more Pythonic to delete the file and catch the exception if it doesn't actually exist. From sergio.correia at gmail.com Mon Sep 3 03:57:57 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Mon, 3 Sep 2007 02:57:57 -0500 Subject: PYTHONPATH not working on Windows XP (?) In-Reply-To: <1188804742.738490.50470@19g2000hsx.googlegroups.com> References: <1188804742.738490.50470@19g2000hsx.googlegroups.com> Message-ID: Thanks! It worked straightforward, and it's easier than messing with the enviromental variables or the registry. BTW, I'm still wondering how did Autohotkey got included in sys.path (there are no other .pht files on my PC) Regards, Sergio On 9/3/07, olivier wrote: > Hi, > > > Any suggestions for adding my path to sys.path permanently? > > You can write a file in Lib/site-packages with a 'pth' extension (the > name itself doesn't matter) containing the path you want to add. > > Example: > MyCustomLib.pth: > C:/docs/utils > > And be careful with path separator on win32. It should be "/" or "\\", > never "\". > > Regards, > > Olivier > > > -- > http://mail.python.org/mailman/listinfo/python-list > From Michael.Coll-Barth at VerizonWireless.com Sat Sep 29 15:58:22 2007 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Sat, 29 Sep 2007 15:58:22 -0400 Subject: Program inefficiency? In-Reply-To: References: Message-ID: <20070929195825.813C81E4005@bag.python.org> > -----Original Message----- > From: stdazi > On Sep 29, 6:07 pm, Michael.Coll-Ba... at VerizonWireless.com wrote: > > > You did not mention the OS, but because you are using > > "pathname\editfile.txt", it sounds like you are using an MS OS. From > > past experience with various MS OSes, I found that as the number of > > files in a directory increases the slower your process runs for each > > file. > > how so? > I said "sounds like", which means I was guessing. In *nix ( the ones I know ), it would have been "pathname/editfile.txt". But, it was the file extension that caught my eye. I had a project a while back that required a mass conversion of jpeg files and ran into what sounded like a similar problem. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From ldo at geek-central.gen.new_zealand Sat Sep 1 07:24:54 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 23:24:54 +1200 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> Message-ID: In message <7xy7g1if24.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > TeX/LateX have been around forever and are well established standards, > as awful as they are. Why do we want ANOTHER markup language? We > need fewer, not more. Because time marches on, and the deficiencies of the old way of doing things become more obvious, not less. For all the wonderful layout capabilities of TEX, I've never seen a decent font done with METAFONT--not a single one. They all looked like rubbish compared to what was available with those early PostScript-based Apple LaserWriters. By the way, did you know there was life before TEX? Back in that era, the main open-source markup system in use was ... troff. Still not quite dead today, it lives on in the definition of Unix/Linux man pages. From zzbbaadd at aol.com Thu Sep 27 23:18:22 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 27 Sep 2007 20:18:22 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <87641v4j38.fsf@benfinney.id.au> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> Message-ID: <1190949502.875203.57690@w3g2000hsg.googlegroups.com> > > - Abstract Base Classes > > I like how someone here characterized decorators - those silly @ things. They remind me of Perl. Not adding keywords for abstract and static is like Perl not adding a keyword for class. But I know all such additions are vigorously defended by the most ardent users of each language. From afriere at yahoo.co.uk Tue Sep 18 21:11:21 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 18 Sep 2007 18:11:21 -0700 Subject: Sets in Python In-Reply-To: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> Message-ID: <1190164281.329970.321360@y27g2000pre.googlegroups.com> On Sep 19, 10:39 am, sapsi wrote: > My question is, > 1) Why can't lists be hashed? They are mutable. From fakeaddress at nowhere.org Sat Sep 22 17:17:38 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Sep 2007 21:17:38 GMT Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <1190484589.890198.266430@y42g2000hsy.googlegroups.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> <1190484589.890198.266430@y42g2000hsy.googlegroups.com> Message-ID: richyjsm at gmail.com wrote: > Bryan Olson wrote: >> One surprising result was that more of the Python >> programmers surveyed use bitwise operators than are aware >> of the exponentiation operator, which C does not offer. > > On that subject, I'd suggest that the pow() builtin (not the ** > operator - just the pow() function) should also be a candidate for > removal... A darn good candidate, I'd say. I'm biased because I once took quite a while to figure out that importing the math module's 'pow' was how I broke my code. The operator module offers pow(). Is there any good reason for pow() as a built-in? -- --Bryan From steve at holdenweb.com Fri Sep 28 08:16:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 08:16:05 -0400 Subject: Bug: spurious indentation error In-Reply-To: <33dffc910709280441p14f78175n8549bdb315416328@mail.gmail.com> References: <33dffc910709280441p14f78175n8549bdb315416328@mail.gmail.com> Message-ID: Mridula Ramesh wrote: > hi. > > is this the right place to report a bug? > > i had written this by mistake: > filemenu = Menu(menu) , bg="White") > > instead of > filemenu = Menu(menu, bg="Pink") > > and the compiler kept giving me an indentation error in a line much > further down which was perfectly okay. > > i am using python 2.5.1 with IDLE 1.2.1 on a windows XP machine. > anyone else struggling with the same thing, beware! :) > > -mridula. > This is probably a bug in your mind, not in the compiler ;-) Without more detail (i.e. the complete code or a sizable and relevant chunk of it, pkus the copied error message) it's impossible to say exactly what was happening. However I am pretty confident that the 2.5.21 compiler will immediately report an unopened closing parenthesis as a syntax error. >>> something = "abc".replace("c"), "d") File "", line 1 something = "abc".replace("c"), "d") ^ SyntaxError: invalid syntax >>> So, what was the problem again? Give us a little more detail, please. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From gagsl-py2 at yahoo.com.ar Wed Sep 26 01:52:33 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Sep 2007 02:52:33 -0300 Subject: the address of list.append and list.append.__doc__ References: <1190775258.351819.24930@22g2000hsm.googlegroups.com> <1190780557.879816.13800@d55g2000hsg.googlegroups.com> Message-ID: En Wed, 26 Sep 2007 01:22:37 -0300, HYRY escribi?: > I installed python 2.4.4 and tried id(list.append.__doc__) again, here > is the result, only id(list.append.__doc__) changes, this is strange, > and only happened in the command line. Because I am doing something > program that use this id in the command line. Can someone help me try > this on your PC, I want to know which is the problem: this version of > python, or my PC. "the problem"? Perhaps if you explain what you really want to do, someone can think the way to do that, most likely *not* using id() >>>> id(list.count.__doc__) > 11863968 >>>> id(list.count.__doc__) > 11863968 >>>> id(list.count.__doc__) > 11863968 >>>> id(list.count.__doc__) > 11863968 This behavior is an accident. The actual doc strings are stored as C null-terminated strings inside the C structures defining the list type. When you request list.append.__doc__, a Python string object has to be built pointing to the original C string. After the call to id(), nobody references that string object, and it is garbage collected. Next time you request the same thing, depending on the details on how the memory allocator works, it may or may not reuse the same memory address. Try with some print "hello" in between those id calls. -- Gabriel Genellina From bj_666 at gmx.net Sun Sep 16 06:58:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Sep 2007 10:58:07 GMT Subject: Needless copying in iterations? References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> <13epv3fnb6bak15@corp.supernews.com> Message-ID: <5l4ghuF655kfU2@mid.uni-berlin.de> On Sun, 16 Sep 2007 09:50:39 +0000, Steven D'Aprano wrote: > The point is rather moot, since CPython (and probably other Pythons) do > almost no optimizations. But just because Python is a dynamic language > doesn't mean there are no optimizations possible: Haskell is a dynamic > language, and there are optimizing compilers for it. Of course, it is > much simpler for Haskell, because of the type system it uses. What do you mean by Haskell is a dynamic language? It is statically and strict typed and the compiler usually knows all the functions. No "surprises", no side effects, no duck typing. Ciao, Marc 'BlackJack' Rintsch From tdelaney at avaya.com Wed Sep 26 05:40:24 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 26 Sep 2007 17:40:24 +0800 Subject: sorting a list numbers stored as strings In-Reply-To: Message-ID: ZeD wrote: > thebjorn wrote: > >>>>>> int("020") >>> 20 >>>>>> 020 >>> 16 >> >> You can get the latter behavior using eval: > > why using eval when int has the "base" optional parameter? > >>>> int("020") > 20 >>>> int("020", 8) > 16 >>>> int("09", 8) > Traceback (most recent call last): > File "", line 1, in > ValueError: invalid literal for int() with base 8: '09' The whole point of this was I misremembered what the base/radix optional parameter of int() defaulted to - I thought it was 0, then when I checked in Python 2.5 I thought it must have been 0 in an earlier version. Tim Delaney From dvkeeney at gmail.com Wed Sep 5 13:12:43 2007 From: dvkeeney at gmail.com (dkeeney) Date: Wed, 05 Sep 2007 17:12:43 -0000 Subject: PythonAlley.com In-Reply-To: References: Message-ID: <1189012363.397845.174960@y42g2000hsy.googlegroups.com> The Python community would benefit from a moderated web-forum along the lines of perlmonks.org. The Python community online now seems to have two major segments, the c.l.p newsgroup (here), and a large selection of blogs. C.l.p is unmoderated and often hostile. The bloggers self-moderate reasonably well (to my observation), but the blogs, individually and in aggregate, look 'read-only' to newbies, in that questions are not welcomed. A moderated forum that gives recognition to the experienced and tolerance to newbies would be a good thing. David On Sep 5, 10:27 am, "Shawn Milochik" wrote: > I bought the domain PythonAlley.com (and PerlAlley.com and > RubyAlley.com) not too long ago. I had the inspiration to make some > kind of community site thing, but never did get around to it. > > Does anyone have any ideas as to what a wonderful use for > PythonAlley.com would be? I'd really like to do something with at > least the Python site, since I love Python. Not too sure about the > others -- maybe I'm make them wikis and open them up to the community. > Maybe I should just sell them. > > Ideas? > > Thanks, > Shawn From geoffness8 at gmail.com Tue Sep 18 06:03:58 2007 From: geoffness8 at gmail.com (geoff_ness) Date: Tue, 18 Sep 2007 10:03:58 -0000 Subject: UnicodeEncodeError in Windows In-Reply-To: References: <1190025496.308969.51400@n39g2000hsh.googlegroups.com> Message-ID: <1190109838.071973.251910@19g2000hsx.googlegroups.com> On Sep 18, 7:36 am, "Gabriel Genellina" wrote: > En Mon, 17 Sep 2007 07:38:16 -0300, geoff_ness > escribi?: > > > > > def buildString(warrior): > > """Build a string from a warrior's stats > > > Returns string for output to warStat.""" > > return "!tr!!td!!id!"+str(warrior.ID)+"!/id!!/td!"+\ > > "!td!"+str(warrior.damage)+"!/td!!td!"+str(warrior.kills)+\ > > "!/td!!td!"+str(warrior.survived)+"!/td!!/tr!" > > > This code runs fine on my linux machine, but when I sent the code to a > > friend with python running on windows, he got the following error: > > > Traceback (most recent call last): > > File "C:\Documents and Settings\Administrator\Desktop > > \reparser_014(2)\iotp_alt2.py", line 169, in buildString > > "!/td!!td!"+str(warrior.survived)+"!/td!!/tr!" > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in > > position 0: ordinal not in range(128) > > > As I understand it the error is related to the ascii codec being > > unable to cope with the unicode string u'\ufeff'. > > The issue I have is that this error doesn't show up for me - ascii is > > the default encoding for me also. Any thoughts or assistance would be > > welcomed. > > Some of those `warrior` attributes is an Unicode object that contains > characters outside ASCII. str(x) tries to convert to string, using the > default encoding, and fails. This happens on Windows and Linux too, > depending on the data. > I've seen that you use codecs.open: you should write Unicode objects to > the file, not strings, and that would be fine. > Look for some recent posts about this same problem. > > -- > Gabriel Genellina Thanks Gabriel, I hadn't thought about the str() function that way - I had initially used it to coerce the attributes which are type int to type str so that I could write them to the output file. I've rewritten the buildString() function now so that the unicode objects don't get fed to str(), and apparently windows copes ok with that. I'm still puzzled as to why python at my end had no problem with it... From ndbecker2 at gmail.com Fri Sep 28 06:35:29 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 28 Sep 2007 06:35:29 -0400 Subject: getopt with negative numbers? References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <1190915197.390247.313590@57g2000hsv.googlegroups.com> <1190930134.780005.68510@22g2000hsm.googlegroups.com> <1190944143.521085.66910@g4g2000hsf.googlegroups.com> <871wcj4ib9.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Casey writes: > >> Well, it is a hack and certainly not as clean as having getopt or >> optparse handle this natively (which I believe they should). > > I believe they shouldn't because the established interface is that a > hyphen always introduced an option unless (for those programs that > support it) a '--' option is used, as discussed. I don't agree. First of all, what is 'established interface'? There are precedents from well-known C and C++ libraries, such as 'getopt', 'popt', and boost::program_options. IIRC, each of these will treat a negative number following an option that requires a number as a number. Besides this, the behavior I just described is really required. Otherwise, numeric options are basically broken. From tenax.raccoon at gmail.com Wed Sep 19 09:35:47 2007 From: tenax.raccoon at gmail.com (Jason) Date: Wed, 19 Sep 2007 13:35:47 -0000 Subject: Keeping a database connection with a Singleton? In-Reply-To: <1190208406.041953.115580@g4g2000hsf.googlegroups.com> References: <1190208406.041953.115580@g4g2000hsf.googlegroups.com> Message-ID: <1190208947.351094.197010@57g2000hsv.googlegroups.com> On Sep 19, 7:26 am, "exhuma.twn" wrote: > I remember reading about the Singleton pattern in python and how it's > an unpythonic pattern and all. At the time I did not need the > Singleton anyways, so I just glanced over the document. > > But, setting this aside: I have an application where I have a > connection to a database. At some point in the application I open up a > new window. The new windows resides in a different module. So I have a > directory structure like this: > > - mainapp.py > - newwindow.py > > So I import "newwindow" in "mainapp" so I can instantiate and display > it. Meanwhile, the main-app has an open connection to the database. > What's the cleanest way to hand this connection to the new window? I > can see several possibilities: > > 1) Simply pass the connection as paramtere to the constructor of new- > window. > 2) Use the "Singleton" deisign pattern to keep a reference to the > connection > 3) Open up a completely new connection to the database in the new > window. > > Now, option 1) is clearly the easiest to implement, however, I somehow > tend to use option 2 (the singleton) as it's more flexible. Option 3 > looks ugly to me. > > This is a stuation I run into many times. And I am always faced with > the same choice. And I never know which one to chose. And now that I > am getting more and more comfortable with the basics of python, I > would like to know if I am missing something more "pythonic". > > So, what would you recommend? You don't need a way to make every instance the same. You need a way where every instance shares the same state. Aka, the Borg pattern, courtesy of Alex Martelli. It's in the Python Cookbook at "http:// aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531". Good luck! --Jason From dfedoruk at gmail.com Fri Sep 14 04:33:57 2007 From: dfedoruk at gmail.com (Dmitri Fedoruk) Date: Fri, 14 Sep 2007 08:33:57 -0000 Subject: lxml + mod_python: cannot unmarshal code objects in restricted execution mode In-Reply-To: <1189724657.261461.181420@22g2000hsm.googlegroups.com> References: <1189688758.587404.139360@r29g2000hsg.googlegroups.com> <1189724657.261461.181420@22g2000hsm.googlegroups.com> Message-ID: <1189758837.599777.6890@o80g2000hse.googlegroups.com> On Sep 14, 3:04 am, Graham Dumpleton wrote: > Try forcing mod_python to run your code in the first interpreter > instance created by Python. > PythonInterpreter main_interpreter Thank you very much, that solved the problem! A more detailed discussion can also be found in the lxml-dev mailing list ( http://comments.gmane.org/gmane.comp.python.lxml.devel/2942 ) Dmitri From hat at se-162.se.wtb.tue.nl Wed Sep 26 08:24:56 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 26 Sep 2007 14:24:56 +0200 Subject: Asynchronous Messaging References: <1190807252.731074.141450@k79g2000hse.googlegroups.com> Message-ID: On 2007-09-26, wink wrote: > Hello, > > I'm getting my feet wet in Python and thought I'd try to see how well > Python works for asynchronous messaging. I've been using asynchronous Have a look at Twisted (www.twistedmatrix.com) Albert From rschroev_nospam_ml at fastmail.fm Wed Sep 12 10:17:24 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 12 Sep 2007 14:17:24 GMT Subject: An ordered dictionary for the Python library? In-Reply-To: <1189601205.503841.327170@o80g2000hse.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <13efnmi4n959a59@corp.supernews.com> <1189601205.503841.327170@o80g2000hse.googlegroups.com> Message-ID: Michele Simionato schreef: > On Sep 12, 2:42 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 12 Sep 2007 07:33:45 +0000, Mark Summerfield wrote: >> In fact, I'm not sure what people mean by ordered dicts. I assume they >> mean the keys are ordered, not the values. But ordered by what? Insertion >> order? Modification order? Alphabetical order? > > Insertion order. Mark referred to C++ and the sort function, so I assume he meant alphabetical order (or the equivalent for types other than strings). -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From hosalo at _NO_SPAM_gmail.com Tue Sep 25 10:41:23 2007 From: hosalo at _NO_SPAM_gmail.com (Heikki Salo) Date: Tue, 25 Sep 2007 14:41:23 GMT Subject: directpython question In-Reply-To: References: Message-ID: veki wrote: > Hello, > I've got IBM Thinkpad 30 laptop with configuration: > > IBM Thinkpad R30 > P3 Mobile Celeron 900mhz > 128mb sdram pc133 > 15gb hdd > cd-rom Teac cd-224e > 56K V.90/92 > 10/100 Ethernet > lpt port > ps2 port > 2 x usb port > vga-out > pcmcia > > ,then I have been install directx 9.0c,Python 2.5 and directpython for > python 2.5.On my two computers directpython works but on this > laptop it don't want work e.g: > > When I want execute this script on laptop: > > import d3dx > frame=d3dx.Frame(u'SOME FRAME') > frame.mainloop() > > I get this error: > > Traceback (most recent call last): > File "C:\Python25\Lib\site-packages\veki1.py", line 2, in > fr=d3dx.Frame(u'SOME FRAME') > File "C:\Python25\lib\site-packages\directpy\d3dx.py", line 639, in > __init__ > self._createDevice(area[2:4]) > File "C:\Python25\lib\site-packages\directpy\d3dx.py", line 659, in > _createDevice > raise RuntimeError("No valid mode found") > RuntimeError: No valid mode found > > Regards, > Vedran > > As Tim already noted, your laptop apparently uses Trident CyberBlade Ai1 graphics card, which is quite old and designed for DirectX 6-8. This is not a problem if the device driver is up to date, but the newest I found seems to be from 2003. This can be a problem if it does not correctly support DirectX 9.0c (released in 2004). You should see what the DirectX diagnostics tool says (dxdiag.exe - found in WINDIR\system32) and possibly update the driver. Then cross your fingers and see what happens. -- Heikki Salo From paul at boddie.org.uk Thu Sep 20 17:51:26 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 20 Sep 2007 14:51:26 -0700 Subject: M2Crypto 0.18 - new version, same old build bugs. In-Reply-To: References: Message-ID: <1190325086.825866.319760@k79g2000hse.googlegroups.com> On 20 Sep, 22:12, John Nagle wrote: > > That was for M2Crypto 0.17. > > It's still broken in M2Crypto 0.18. > > And there's no RPM or Windows binary. > > Nobody actually uses this stuff, do they? I can find Ubuntu packages for 0.16 and 0.17: http://packages.ubuntu.com/feisty/libs/python-m2crypto http://packages.ubuntu.com/gutsy/libs/python-m2crypto So, clearly some people are managing to build the library, even if it isn't the absolute latest version. You might want to take a look at the source packages and the patches the distribution people apply, although it doesn't look like they are actually doing much patching. The source packages suggest that they use SWIG 1.3.24 to build M2Crypto - is that what you're using? Paul From aahz at pythoncraft.com Tue Sep 18 10:57:12 2007 From: aahz at pythoncraft.com (Aahz) Date: 18 Sep 2007 07:57:12 -0700 Subject: Using pseudonyms (was Re: Python 3K or Python 2.9?) References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46ee2d9d$0$26213$426a74cc@news.free.fr> <46ef893c$0$21882$426a34cc@news.free.fr> Message-ID: In article <46ef893c$0$21882$426a34cc at news.free.fr>, Bruno Desthuilliers wrote: >Aahz a ?crit : >> In article <46ee2d9d$0$26213$426a74cc at news.free.fr>, >> Bruno Desthuilliers wrote: >>> >>> But what, given that I'm an AOL user still thinking it's kewl to hide >>> behind a pseudo, what else would you expect ? >> >> What exactly is a "pseudo", pray tell? > >Sorry : a pseudonym (a nickname). You apparently missed the thrust of my sarcasm. You can't tell what is or is not a pseudonym online. For all I know, "Bruno Desthulliers" is a pseudonym. While I recognize that there is some social advantage to linking consistent identifiers with people, I have I think understandable irritation with people who insist that names follow certain patterns. (For those joining only recently, my full legal name is "Aahz", which I changed from my former name precisely because of attitudes like Bruno's.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From gagsl-py2 at yahoo.com.ar Thu Sep 6 20:53:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Sep 2007 21:53:04 -0300 Subject: Using wild character References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> <1189058095.671230.262190@o80g2000hse.googlegroups.com> <5k9pjoF2mrncU1@mid.uni-berlin.de> <1189122511.231602.217710@w3g2000hsg.googlegroups.com> Message-ID: En Thu, 06 Sep 2007 20:48:31 -0300, Zentrader escribi?: > On Sep 6, 12:47 am, Marc 'BlackJack' Rintsch wrote: >> >> Maybe better the ``in`` operator for the '*string*' type. `str.find()` >> will go away in the future. > > string.find serves a useful purpose in that it returns the starting > location of the string found, or -1 if not found, so if you wanted to > slice "abdecf" on"c", string.find will tell you where that is. PEP3100 says it will be removed, but at the same time says [UNLIKELY]... partition serves almost the same purpose and its easier to use. -- Gabriel Genellina From kw at codebykevin.com Fri Sep 28 16:48:27 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 28 Sep 2007 16:48:27 -0400 Subject: List search Message-ID: I'm having a problem with searching a list. Here's my code: mylist = ['x11', 'x11-wm', 'x11-system'] for line in mylist: if 'x11' in line: print line This results in the following output: x11 x11-wm x11-system I'm looking to return the list item that just has 'x11'. How can I structure my search term so that this output is returned? From musiccomposition at gmail.com Thu Sep 27 22:34:45 2007 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 28 Sep 2007 02:34:45 -0000 Subject: developing an application In-Reply-To: <1190930761.625756.309830@50g2000hsm.googlegroups.com> References: <1190930761.625756.309830@50g2000hsm.googlegroups.com> Message-ID: <1190946885.375600.272440@g4g2000hsf.googlegroups.com> On Sep 27, 5:06 pm, yadin wrote: > hi! > i was buiding an application using python...a program > this was my first one...now that i got it working perfectly > how can i put the bunch of files into one package? > the user of the appliation will not know where to start? that is which > file to click on in oder to start the program? > thanks a lot also you can make MacOS apps with the standard MacOS Python distribution From bardov at gmail.com Wed Sep 19 08:17:16 2007 From: bardov at gmail.com (Dan Bar Dov) Date: Wed, 19 Sep 2007 14:17:16 +0200 Subject: re question Message-ID: I'm trying to construct a regular expression to match valid IP address, without leading zeroes (i.e 1.2.3.4, 254.10.0.0, but not 324.1.1.1, nor 010.10.10.1) This is what I come up with, and it does not work. r'(^[12]?\d{0,2}\.){3,3}[12]?\d{0,2}' What am I doing wrong? Any common knowledge IP matching RE? Thanks, Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Sat Sep 15 13:33:21 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 15 Sep 2007 19:33:21 +0200 Subject: subclass of integers In-Reply-To: <1189780201.692192.291010@k79g2000hse.googlegroups.com> References: <1189780201.692192.291010@k79g2000hse.googlegroups.com> Message-ID: <46ead728$0$12900$426a34cc@news.free.fr> Mark Morss a ?crit : > I would like to construct a class that includes both the integers and > None. I desire that if x and y are elements of this class, and both > are integers, then arithmetic operations between them, such as x+y, > return the same result as integer addition. However if either x or y > is None, these operations return None. > > It's simple enough to construct a subclass of integers that behave in > this way: > > class Nint(int): > def __add__(self,other): > if (other != None): > return self+other > else: > return None > def __radd__(self,other): > if (other != None): > return other+self > else: > return None > #...and so forth > > However I have not been able to figure out how to make it so that > None, as well as an integer, could be an element of my class. My > preliminary impression is that I have to override int.__new__; but I > am uncertain how to do that and have been unable to find anything on > the web explaining that. Indeed I haven't been able to find much > about __new__ at all. Overriding this method of built-in classes > seems to be quite unusual. > > I would very much appreciate anyone's help. You'll find documentation in the FineManual(tm): http://docs.python.org/ref/customization.html http://www.python.org/download/releases/2.2.3/descrintro/#__new__ and a possible (even if imperfect IMHO) example in my answer to Zentrader in the thread. Now would you be kind enough to satisfy my curiousity and explain your use case ?-) From ldo at geek-central.gen.new_zealand Fri Sep 21 07:46:09 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 21 Sep 2007 23:46:09 +1200 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> Message-ID: In message <87hclpjm3a.fsf at rudin.co.uk>, Paul Rudin wrote: > ... these days emacs comes with all sorts of > pointing-clicky-menu-y type things - you don't really have to learn > anything to get started. After two decades of putting up with vi just to ensure compatibility with every proprietary *nix system I might come across, let me just say ... USE EMACS! Oh, and . From dandolls at yahoo.co.in Sun Sep 23 13:18:01 2007 From: dandolls at yahoo.co.in (Amit Kumar Saha) Date: Sun, 23 Sep 2007 22:48:01 +0530 Subject: [Bulk] Re: Writing Object Data to Disk In-Reply-To: <18c1e6480709230934k61504fa1r528c2f4ade9722f0@mail.gmail.com> References: <1190443648.5838.6.camel@ubuntu-laptop> <18c1e6480709230934k61504fa1r528c2f4ade9722f0@mail.gmail.com> Message-ID: <1190567881.8165.1.camel@ubuntu-laptop> On Sun, 2007-09-23 at 18:34 +0200, David wrote: > > I would like to know if "Pickling" the class object is the only way of > > writing it to disk for persistent storage. Also, do we have a concept > > similar to "array of objects" in Python? The number of objects is only > > known at "run-time". > > Have a look at YAML. > > http://freshmeat.net/projects/syck/ > > Also it is possible to persist python data to and from XML. See > xml.marshal.generic.dumps Thanks David :-) I appreciate the XML related comment, but as of now I am ready-to-roll with Python specific pickling. XML will be used in a later version of my code! Regards, Amit -- Amit Kumar Saha me blogs@ http://amitksaha.blogspot.com URL:http://amitsaha.in.googlepages.com From stephanerufer at gmail.com Thu Sep 20 03:01:16 2007 From: stephanerufer at gmail.com (Rufman) Date: Thu, 20 Sep 2007 00:01:16 -0700 Subject: Python and RTF Message-ID: <1190271676.160077.99270@w3g2000hsg.googlegroups.com> Does anyone have a good rtf library for python, have exprience with pyRTF or a link to a good tutorial? thx Stephane From effigies at gmail.com Thu Sep 6 04:37:09 2007 From: effigies at gmail.com (Chris Johnson) Date: Thu, 06 Sep 2007 08:37:09 -0000 Subject: Autogenerate functions (array of lambdas) Message-ID: <1189067829.685339.50550@y42g2000hsy.googlegroups.com> What I want to do is build an array of lambda functions, like so: a = [lambda: i for i in range(10)] (This is just a demonstrative dummy array. I don't need better ways to achieve the above functionality.) print [f() for f in a] results in: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] rather than the hoped for: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Clearly, lambda is returning the object i, which is left at the last value of range(10). The following is my solution. t = lambda i: lambda: i a = [t(i) for i in range(10)] or the somewhat more terse: a = [(lambda i: lambda: i)(i) for i in range(10)] This gives the behavior which, intuitively, I expected from the original syntax. So my questions are: 1) Does this make sense as what should be done here? That is, would this be the behavior you'd want more often than not? As I said, intuitively, I would think the lambda would treat the iterator variable as a constant in this context. 2) Is there a better or preferred method than the one I've found? Thanks, Chris From deets at nospam.web.de Thu Sep 6 04:46:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 06 Sep 2007 10:46:15 +0200 Subject: Autogenerate functions (array of lambdas) In-Reply-To: <1189067829.685339.50550@y42g2000hsy.googlegroups.com> References: <1189067829.685339.50550@y42g2000hsy.googlegroups.com> Message-ID: <5k9t33F2pforU1@mid.uni-berlin.de> Chris Johnson schrieb: > What I want to do is build an array of lambda functions, like so: > > a = [lambda: i for i in range(10)] > > (This is just a demonstrative dummy array. I don't need better ways to > achieve the above functionality.) > > print [f() for f in a] > > results in: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] > rather than the hoped for: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > Clearly, lambda is returning the object i, which is left at the last > value of range(10). The following is my solution. > > t = lambda i: lambda: i > a = [t(i) for i in range(10)] > > or the somewhat more terse: > > a = [(lambda i: lambda: i)(i) for i in range(10)] > > This gives the behavior which, intuitively, I expected from the > original syntax. So my questions are: > 1) Does this make sense as what should be done here? That is, would > this be the behavior you'd want more often than not? As I said, > intuitively, I would think the lambda would treat the iterator > variable as a constant in this context. > 2) Is there a better or preferred method than the one I've found? The problem you encountered relates to the fact that the lambdas close around the names known when they were created - not the values bound to them. To overcome that, bind the value you pass to a new name, like this: a = [lambda i=i: i for i in range(10)] Diez From usenet+meow at aldan.algebra.com Thu Sep 13 23:07:32 2007 From: usenet+meow at aldan.algebra.com (Mikhail Teterin) Date: Thu, 13 Sep 2007 23:07:32 -0400 Subject: automatic parallelization References: <46E99488.20909@uni-oldenburg.de> Message-ID: <1338560.ksk72Tk4Kk@aldan.algebra.com> Cameron Laird wrote: > There are a LOT more possibilities one might pursue, depending > on the details of Mr. Teterin's intent. The reason I began wondering about this is that I like a particular image-gallery generating tool called `imageindex' (http://www.edwinh.org/imageindex/) Unfortunately, it processes all given pictures sequentionally ignoring my three other cores. The tool is written in Perl, but I would consider rewriting it in Tcl or Python, if the language made it easy to parallelize loops... > I'm fond of Linda http://www.unixreview.com/documents/s=10125/ur0704l/ >, Parallel > Python only one of several > initiatives which aspire to exploit multicores, and so on. Linda URL does not open... I'll look into Parallel Python, but it is an "execution server", which is a rather different approach from OpenMP's, which I'm more familiar with. Thanks! -mi From ldo at geek-central.gen.new_zealand Wed Sep 19 05:48:43 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 19 Sep 2007 21:48:43 +1200 Subject: Quick shallow-copy idiom Message-ID: y = type(x)(x) From kostaspaxos at yahoo.gr Tue Sep 18 05:20:03 2007 From: kostaspaxos at yahoo.gr (Konstantinos Pachopoulos) Date: Tue, 18 Sep 2007 12:20:03 +0300 Subject: raw string Message-ID: <46EF9843.1030507@yahoo.gr> Hi, i am trying to execute the following query on a DB: qe.execQuery(r"SELECT * FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM Commiter") However, whether i put the r in the front or not, i always get an error about the "\n". What's wrong? From n.anand.k at gmail.com Tue Sep 25 05:28:05 2007 From: n.anand.k at gmail.com (Anand) Date: Tue, 25 Sep 2007 02:28:05 -0700 Subject: Inserting an element into existing xml file Message-ID: <1190712485.761290.136570@50g2000hsm.googlegroups.com> Hi, I'm new to Python. we are using python2.4. I wanted to insert an element into an existing xml file. Can anyone help me with this? I've seen lxml and elementTree in python2.5 has some API's to insert into existing xml file. We cant use python 2.5 due to some limitations. So how can we do it in 2.4? Thanks in Advance, Anand From duncan.booth at invalid.invalid Wed Sep 12 08:39:03 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Sep 2007 12:39:03 GMT Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> Message-ID: Ivan Voras wrote: >> I'd say Mr Eckel fails to graps some of the great points about Python's > >> object model - the rant about the use of 'self' is a sure clue. > > What does "self" have to do with an object model? It's an > function/method argument that might as well be hidden in the compiler > without ever touching the role it has (if not, why?). I agree that it's > needless noise in a language. You could add some syntax to Python such that '.x' was equivalent to '.x' (either completely implicitly or with some surrounding block that lets you specify the assumed variable. That wouldn't break anything in the syntax but the general feeling of the Python community is that such a change would be undesirable as it is better to write the variable name out explicitly. As for omitting 'self' from method definitions, at first site you might think the compiler could just decide that any 'def' directly inside a class could silently insert 'self' as an additional argument. This doesn't work though because not everything defined in a class has to be an instance method: static methods don't have a self parameter at all, class methods traditionally use 'cls' instead of 'self' as the name of the first parameter and it is also possible to define a function inside a class block and use it as a function. e.g. class Weird: def factory(arg): """Returns a function based on its argument""" foo = factory("foo") bar = factory("bar") del factory When factory is called, it is a simple function not a method. If it had gained an extra parameter then either you would have to explicitly pass it an instance of a not yet defined class when calling it, or the compiler would have to somehow know that it had been defined with the extra parameter and add it. Basically it all boils down to having a consistent set of rules. Ruby has one set of rules, but Python has a different set. Python's rules mean you can interchange functions and methods more easily [at a cost of having to write self out explicitly/with the advantage that you can easily see references to self](delete as preferred). There is no difference between: class C: def method(self): pass and def foo(self): pass class C: pass C.method = foo both of these result in effectively the same class (although the second one has a different name for the method in tracebacks). That consistency really is important. Whenever I see a 'def' I know exactly what parameters the resulting function will take regardless of the context. Another area to consider is what happens when I do: foo = FooClass() foo.bar(x) # versus f = foo.bar f(x) Both of these work in exactly the same way in Python: the self parameter is bound to the method when you access 'foo.bar', not when you make the call. That isn't the case in some other scripting languages. e.g. in Javascript the first one would call bar with the magic 'this' parameter set to foo, but in the second case it calls bar with 'this' set to the global object. My point here is that in Python the magic is clearly defined and overridable (so we can have static or class methods that act differently). From stefan.arentz at gmail.com Fri Sep 7 10:21:09 2007 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 07 Sep 2007 16:21:09 +0200 Subject: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute References: <1189173455.525144.326300@y42g2000hsy.googlegroups.com> Message-ID: <87k5r2zhd6.fsf@kip.sateh.com> cjt22 at bath.ac.uk writes: > Hi there > > I am fairly new to Python and have not really used regular expressions > before (I think this might be needed for my query) and wondered if you > could help > > I have a step class and store in a list step instances > A step instance contains variables: name, startTime etc and startTime > is stored as a string %H:%M:%S > > What I would like to do is to be able to sort this list of objects > based on the startTime object so that the first item in the list is > the object with the earliest Start time and last item is the object > with the last Start time. > > I belive my key has to be = strpTime(step.sTime, "%H:%M:%S") > But don't know how to create the comparison funciton. > > Any help on how I can perform this whole operation would be much > appreciated. Code: class Step(object): def __init__(self, time): self.time = time def __repr__(self): return "" % self.time steps = [Step("03:23:23"), Step("12:59:12"), Step("02:32:17")] print steps steps.sort(key = lambda s: s.time) print steps Output: [, , ] [, , ] If the default sort order of a Step is always it's time then you can also define a __cmp__ method like this: class Step(object): def __cmp__(self, other): return cmp(self.time, other.time) And simply do a steps.sort() S. From imageguy1206 at gmail.com Fri Sep 7 07:51:56 2007 From: imageguy1206 at gmail.com (imageguy) Date: Fri, 07 Sep 2007 04:51:56 -0700 Subject: application version checking against database Message-ID: <1189165916.268515.10360@d55g2000hsg.googlegroups.com> We are trying to implement a system that checks the version of the application against a version number stored in the database. We don't want the app and the db don't become out of sync. We have tried setting a __version__ variable in the top most module, however, it seems that this is not accessible for the modules that are subsequently imported. There are a several locations in the app where we want to do the version check, but we would like to have one place to set the version number, namely the top level module. We have thought of creating a Version class and passing it around, but aren't really keen on that idea. Any suggestions/ideas would be helpful. NOTE: the app is developed in wxPython. g. From Obey.civ at gmail.com Fri Sep 14 23:42:42 2007 From: Obey.civ at gmail.com (Stephen) Date: Sat, 15 Sep 2007 03:42:42 -0000 Subject: List append In-Reply-To: <1189826727.204061.310380@d55g2000hsg.googlegroups.com> References: <1189826727.204061.310380@d55g2000hsg.googlegroups.com> Message-ID: <1189827762.011325.315840@r29g2000hsg.googlegroups.com> In your code, "array" is a class attribute, so it is shared among all instances. You need to use the __init__ method to define instance (data) attributes instead: def __init__(self): self.array = [] On Sep 14, 11:25 pm, mouseit wrote: > I'm trying to add an element to a list which is a property of an > object, stored in an array. When I append to one element, all of the > lists are appended! > > Example Code: > > class Test: > array = [] > > myTests = [Test() , Test() , Test()] > print len(myTests[1].array) > myTests[0].array.append( 5 ) > print len(myTests[1].array) > > prints: > 0 > 1 > > This is probably a really easy question (I'm very new to python), so > thanks in advance for your help! From gagsl-py2 at yahoo.com.ar Sun Sep 30 23:13:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 01 Oct 2007 00:13:11 -0300 Subject: Using fractions instead of floats References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> <1191206183.441075.167450@57g2000hsv.googlegroups.com> Message-ID: En Sun, 30 Sep 2007 23:36:23 -0300, George Sakkis escribi?: > On Sep 30, 9:35 pm, andresj wrote: >> I was doing some programming in Python, and the idea came to my mind: >> using fractions instead of floats when doing 2/5. >> (...) >> I would like to get some feedback on this idea. Has this been posted >> before? If so, was it rejected? and for what? > > Is internet down today ? > > http://pypi.python.org/pypi/clnum/1.2 > http://www.python.org/dev/peps/pep-0239/ And gmpy: http://www.aleax.it/gmpy.html -- Gabriel Genellina From seanttierney at gmail.com Sat Sep 22 10:57:37 2007 From: seanttierney at gmail.com (Sean Tierney) Date: Sat, 22 Sep 2007 07:57:37 -0700 Subject: Zope review In-Reply-To: <1190432460.360614.293400@n39g2000hsh.googlegroups.com> References: <1190331847.514475.284200@22g2000hsm.googlegroups.com> <1190403772.862325.113960@y42g2000hsy.googlegroups.com> <1190432460.360614.293400@n39g2000hsh.googlegroups.com> Message-ID: <54e1e4bc0709220757r5609f19brabadc43f34ae90d8@mail.gmail.com> >From Twisted's website "Twisted is a networking engine written in Python, supporting numerous protocols. It contains a web server, numerous chat clients, chat servers, mail servers, and more. Given that Zope is also a written in python, supports numerous protocols, contains a webserver, has several chat packages available, a comparison/contrast would be quite useful. I will try to amass some info and bring it back here by midweek. Thanks, Sean On 9/21/07, Istvan Albert wrote: > On Sep 21, 7:04 pm, "Sean Tierney" wrote: > > > someone could contrast Zope w/ another Python framework like Twisted. > > > I've been investing some time in learning Zope/Plone and would love to > > hear someone speak to alternatives. > > Twisted is a networking engine, Zope is a web application framework, > Plone is a content management system, there is nothing to compare, > these are different applications altogether, it is not like you'd > replace one with the other > > For applications that can be compared see Zope vs Django vs Pylons vs > web.py vs CherryPy. Google these and contrast away. > > i > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sean Tierney From istvan.albert at gmail.com Fri Sep 21 23:41:00 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Sat, 22 Sep 2007 03:41:00 -0000 Subject: Zope review In-Reply-To: References: <1190331847.514475.284200@22g2000hsm.googlegroups.com> <1190403772.862325.113960@y42g2000hsy.googlegroups.com> Message-ID: <1190432460.360614.293400@n39g2000hsh.googlegroups.com> On Sep 21, 7:04 pm, "Sean Tierney" wrote: > someone could contrast Zope w/ another Python framework like Twisted. > I've been investing some time in learning Zope/Plone and would love to > hear someone speak to alternatives. Twisted is a networking engine, Zope is a web application framework, Plone is a content management system, there is nothing to compare, these are different applications altogether, it is not like you'd replace one with the other For applications that can be compared see Zope vs Django vs Pylons vs web.py vs CherryPy. Google these and contrast away. i From georgerxz at gmail.com Sun Sep 16 04:52:45 2007 From: georgerxz at gmail.com (GeorgeRXZ) Date: Sun, 16 Sep 2007 01:52:45 -0700 Subject: Free Python Ebook Message-ID: <1189932765.100822.82720@r29g2000hsg.googlegroups.com> Please tell me from which website I will get the free Python Ebook. GEOrgE http://zsoftwares.googlepages.com/index.htm From hg at nospam.org Thu Sep 27 23:56:53 2007 From: hg at nospam.org (hg) Date: Fri, 28 Sep 2007 03:56:53 GMT Subject: Guitars for 0$ !!!!! References: <1190829152.350303.280950@o80g2000hse.googlegroups.com> Message-ID: <9Y_Ki.1136$4V6.1049@newssvr14.news.prodigy.net> nutsbreaker2 at gmail.com wrote: > http://free-guitars.blogspot.com/ And the chicks for free ! From Brad.Johnson at ballardtech.com Fri Sep 28 17:31:32 2007 From: Brad.Johnson at ballardtech.com (Brad Johnson) Date: Fri, 28 Sep 2007 21:31:32 +0000 (UTC) Subject: Reentrancy of Python interpreter Message-ID: I have embedded a single threaded instance of the Python interpreter in my application. I have a place where I execute a Python command that calls into C++ code which then in turn calls back into Python using the same interpreter. I get a fatal error which is "PyThreadStage_Get: no current thread." I guess I understand why I can't have two invocations of the same interpreter thread in one call stack, but how would I go about solving this? From pyth0nc0d3r at gmail.com Wed Sep 5 13:10:22 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Wed, 5 Sep 2007 11:10:22 -0600 Subject: Soemthing wrong w/ urllib module or something. In-Reply-To: References: <46DBC5CB.3040007@timgolden.me.uk> <46DC0BA6.50606@timgolden.me.uk> Message-ID: Anyone got an answer for this? On 9/3/07, Lamonte Harris wrote: > > Yeah I can browse it like normal. For some reason though my News System > that worked like a charm just stopped working also. Is there any > alternatives that I could try to use to POST to a PHP script? > > On 9/3/07, Tim Golden wrote: > > > > [Tim Golden] > > >> To do the obvious, can you open a socket connection > > >> to the domain you're using? > > >> > > >> > > >> from socket import socket > > >> socket ().connect (("DOMAINHERE", 80)) > > >> > > >> > > >> > > >> or does it give you the same error? > > > > [Lamonte Harris] > > > Yeah I basically got the same error. > > > > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "", line 1, in connect > > > socket.error: (10053, 'Software caused connection abort') > > > > OK, then *something's* blocking access to that host (at least) > > on port 80. Can you browse the web normally from this machine? > > In particular, can you browse to that site ("DOMAINHERE")? > > > > TJG > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.hankin at gmail.com Fri Sep 28 19:09:34 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 28 Sep 2007 16:09:34 -0700 Subject: Bug with lists of pairs of lists and append() In-Reply-To: References: Message-ID: <1191020974.172493.127040@w3g2000hsg.googlegroups.com> On Sep 28, 11:25 pm, Gabriel Zachmann wrote: > could some kind soul please explain to me why the following trivial code is > misbehaving? > > lst = [ 0, 1, 2 ] > s = [] > l = [ lst[0] ] > r = lst[1:] > while r: > x = (l,r) > print x > s.append( x ) > l.append( r.pop(0) ) > print s What TeroV said - you need to copy the lists into s otherwise they'll still mutate when you pop or append to them. Try putting an extra "print s" after the s.append(x) line, and you'll find that s changes between there and the final print statement outside the loop. Here's code that works: s, l, r = [], [0], [1, 2] while r: x = (list(l), list(r)) print x s.append(x) l.append(r.pop(0)) print s I'm using list(l) to copy the list, Tero uses l[:], but the idea is the same. But do you just want all proper partitions of lst? Then this is much simpler: lst = [0, 1, 2] s = [(lst[:i], lst[i:]) for i in range(1, len(lst))] -- Paul Hankin From mridula.ccpl at gmail.com Fri Sep 21 01:59:52 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Fri, 21 Sep 2007 11:29:52 +0530 Subject: global name is not defined - but this is actually a function's name Message-ID: <33dffc910709202259h699c04a3w111f0fa23966a59d@mail.gmail.com> hi. i'm a beginner and i'm trying to get the hang of classes and functions. my code looks like this: class showRecord(main): def __init__(self): global gmax #now to create the screen by placing all the widgets rt = Tk() showbuttons() #call the scroller to DoSomething scroll() def showbuttons(self): # NAVIGATION BAR------ NavBut1 = Button(rt, text="|<", width=6, height=2, bg="DarkSeaGreen", fg="Black") NavBut1.grid(row=10, column=20, padx=6, pady=6, columnspan=3) NavBut2 = Button(rt, text="<<", width=6, height=2, bg="DarkSeaGreen", fg="Black") NavBut2.grid(row=10, column=25, padx=6, pady=6, columnspan=3) #widget bindings NavBut2.bind('', lambda e:GoPrev(ctr)) my problem is at the 6th line: showbuttons() the error says "global name "showbuttons" is not defined.... but it's not a global variable. what am i doing wrong? also, should i say ... def showbuttons(self): or def showbuttons(self, showRecord): thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From robertoedwins at gmail.com Wed Sep 5 13:16:17 2007 From: robertoedwins at gmail.com (rieh25) Date: Wed, 5 Sep 2007 10:16:17 -0700 (PDT) Subject: Module for mod_python Message-ID: <12506829.post@talk.nabble.com> I've been thinking about a module (actually I have it partially implemented in Zope), that would do the following things: - Read the structure of a MySql database (fill a dictionary with it) In order to: - Quickly create detail/filter/update forms given a table name (without specifying the fields because they have already been detected) - Keep state of record selection. In order to implement Master-Detail form processing, with unlimited levels of parent-child table relations, which have also been detected already (foreign keys) - Management of interrelation between security and menus (a user can only access certain parts of the application) I think that Ruby on Rails does something similar, but still I thing it would be interesting to implement it in Python. What do you think? -- View this message in context: http://www.nabble.com/Module-for-mod_python-tf4386823.html#a12506829 Sent from the Python - python-list mailing list archive at Nabble.com. From michele.simionato at gmail.com Thu Sep 20 00:30:07 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 20 Sep 2007 04:30:07 -0000 Subject: Mixin classes and single/multiple inheritance In-Reply-To: <87y7f2uhpp.fsf@benfinney.id.au> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> <877immvye0.fsf_-_@benfinney.id.au> <1190257864.945639.199230@k79g2000hse.googlegroups.com> <87y7f2uhpp.fsf@benfinney.id.au> Message-ID: <1190262607.684957.49610@57g2000hsv.googlegroups.com> On Sep 20, 5:41 am, Ben Finney wrote: > Okay. How do we use the language we have to achieve what mixin classes > achieve in Ruby? Can you give an code example that you *would* > recommend for someone looking to do what mixin classes do? Since the language we have does have multiple inheritance, let's use it to implement mixins. My point was that even if Python had been implemented without multiple inheritance, it would have been simple to implement mixins, or by copying the methods, or by dispatching with __getattr__. So, multiple inheritance is giving us very little for the point of view of mixins; OTOH, multiple inheritance is giving us a lot of headaches for what concerns cooperative methods. Michele Simionato From http Tue Sep 4 01:39:52 2007 From: http (Paul Rubin) Date: 03 Sep 2007 22:39:52 -0700 Subject: So what exactly is a complex number? References: Message-ID: <7xk5r7dm53.fsf@ruckus.brouhaha.com> Steve Holden writes: > but the reals aren't. Clearly you *can* take the square root of all > real numbers, since a real number *is* also a complex number with a > zero imaginary component. They are mathematically equal and equivalent. Ehhh, I let it slide before but since the above has been said a few times I thought I better mention that it's mathematically a bit bogus. We could say there is an embedding of the real numbers in the complex numbers (i.e. the set of complex numbers with Im z = 0). But the usual mathematical definition of the reals (as a set in set theory) is a different set from the complex numbers, not a subset. Also, for example, the derivative of a complex valued function means something considerably stronger than the derivative of a real valued function. The real valued function f(x) = { exp(-1/x**2, if x != 0, { 0, if x = 0 for real x is infinitely differentiable at x=0 and all the derivatives are 0, which makes it sound like there's a Taylor series that converges to 0 everywhere in some neighborhood of x=0, which is obviously wrong since the function itself is nonzero when x!=0. The discrepancy is because viewed as a complex valued function f(z), f is not differentiable at z=0 even once. It's pretty normal for a real function f to have a first derivative at x, but no second derivative at x. That can't happen with complex functions. If f'(z) exists for some z, then f is analytic at z which means that all of f's derivatives exist at z and there is some neighborhood of z in which the Taylor series centered at z converges. From nagle at animats.com Sat Sep 29 19:20:46 2007 From: nagle at animats.com (John Nagle) Date: Sat, 29 Sep 2007 23:20:46 GMT Subject: What's the current status of socket timeouts? Message-ID: What actually works and what doesn't in socket timeouts in Python 2.5? What breaks with timeouts turned on? There are lots of patches and bug reports, but no coherent summary. John Nagle From tim.couper at scivisum.co.uk Tue Sep 11 08:08:25 2007 From: tim.couper at scivisum.co.uk (Tim Couper) Date: Tue, 11 Sep 2007 13:08:25 +0100 Subject: IOError - list of all Errno numbers and their meanings? Message-ID: <46E68539.1020404@scivisum.co.uk> As you know, when an IOError is raised, you get a helpful: [Errno N] Is there a list of all possible values of N which can be returned, and their meanings? -- Dr Tim Couper CTO, SciVisum Ltd www.scivisum.com From steve at REMOVE-THIS-cybersource.com.au Sun Sep 23 09:52:17 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 23 Sep 2007 13:52:17 -0000 Subject: newb: Question regarding custom exception References: <1190550748.698865.210740@22g2000hsm.googlegroups.com> Message-ID: <13fcrshn28pot7c@corp.supernews.com> On Sun, 23 Sep 2007 05:32:28 -0700, crybaby wrote: > Why you specify type and name of the exception in your custom > exceptions, > but not in built in exceptions > except IOError: > print "no file by the name ccy_rates*.txt" > > except MyError, e: > print e.msg You can say: except IOError, e: print e.msg And you can say: except MyError: print "whatever I want" It all depends on what you want to do. > Also, when you do: > > try: raise MyError(23) > > In "try: MyError(23) ", you are calling MyError class, but actually get > instantiated in except MyError, e: ? I don't understand what you are actually asking, but I will try my best. raise MyError(23) calls the class MyError and creates and instance, and that instance is then used as an argument to the raise statement. You can also do this: instance = MyError(23) raise instance You don't need the try block unless you want to catch the exception. The exception itself it actually raised by the "raise" statement, not the "except" statement. The "except" statement _catches_ the exception. Try typing these lines in the interactive interpreter: try: print "before the exception" raise Exception("an error occurred") print "this line is never executed" print "neither is this" except Exception, e: print "the exception is:" print e print e.message Hope this helps. -- Steven. From robertoedwins at gmail.com Wed Sep 5 19:32:50 2007 From: robertoedwins at gmail.com (rieh25) Date: Wed, 5 Sep 2007 16:32:50 -0700 (PDT) Subject: Module for mod_python In-Reply-To: <12506829.post@talk.nabble.com> References: <12506829.post@talk.nabble.com> Message-ID: <12513012.post@talk.nabble.com> Is it such a bad idea that it doesn't deserve a reply? rieh25 wrote: > > I've been thinking about a module (actually I have it partially > implemented in Zope), that would do the following things: > > - Read the structure of a MySql database (fill a dictionary with it) > > In order to: > > - Quickly create detail/filter/update forms given a table name (without > specifying the fields because they have already been detected) > - Keep state of record selection. In order to implement Master-Detail form > processing, with unlimited levels of parent-child table relations, which > have also been detected already (foreign keys) > - Management of interrelation between security and menus (a user can only > access certain parts of the application) > > I think that Ruby on Rails does something similar, but still I thing it > would be interesting to implement it in Python. What do you think? > -- View this message in context: http://www.nabble.com/Module-for-mod_python-tf4386823.html#a12513012 Sent from the Python - python-list mailing list archive at Nabble.com. From bj_666 at gmx.net Sat Sep 15 08:42:49 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Sep 2007 12:42:49 GMT Subject: how to join array of integers? References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> Message-ID: <5l22a9F5v20uU1@mid.uni-berlin.de> On Sat, 15 Sep 2007 12:36:02 +0000, Summercool wrote: > i think in Ruby, if you have an array (or list) of integers > > foo = [1, 2, 3] > > you can use foo.join(",") to join them into a string "1,2,3" > > in Python... is the method to use ",".join() ? but then it must take > a list of strings... not integers... > > any fast method? Convert them to strings before joining: In [145]: foo = [1, 2, 3] In [146]: ','.join(map(str, foo)) Out[146]: '1,2,3' Ciao, Marc 'BlackJack' Rintsch From knipknap at gmail.com Thu Sep 6 07:47:49 2007 From: knipknap at gmail.com (Samuel) Date: Thu, 06 Sep 2007 04:47:49 -0700 Subject: ImportError depending on the calling module Message-ID: <1189079269.279716.254560@50g2000hsm.googlegroups.com> Hi, Given the following directory structure: --------- |-- Obj.py |-- __init__.py |-- foo | |-- FooTest.py | `-- __init__.py `-- start1.py --------- With the following content: --------- $ cat Obj.py class Obj(object): pass $ cat __init__.py import Obj __all__ = ['Obj'] $ cat foo/FooTest.py from Obj import Obj class FooTest(object): pass $ cat foo/__init__.py from FooTest import FooTest __all__ = ['FooTest'] $ cat start1.py from foo import FooTest x = FooTest() print "Works!" sab at pcf2245:~/test$ --------- The test works: --------- $ python start1.py Works! $ --------- However, if the module is imported elsewhere, e.g. in the following directory structure: --------- test |-- Obj.py |-- __init__.py |-- foo | |-- FooTest.py | `-- __init__.py `-- start1.py test2 `-- start2.py --------- Where start2.py has the following content: --------- $ cd test2 $ cat start2.py import sys, os.path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import test import test.foo print 'Works!' --------- It does not work: --------- $ python start2.py Traceback (most recent call last): File "start2.py", line 4, in import test.foo File "/home/sab/test/foo/__init__.py", line 1, in from FooTest import FooTest File "/home/sab/test/foo/FooTest.py", line 1, in from Obj import Obj ImportError: No module named Obj --------- How would you import the foo module correctly? -Samuel From puredata at 11h11.com Tue Sep 25 14:44:14 2007 From: puredata at 11h11.com (patrick) Date: Tue, 25 Sep 2007 14:44:14 -0400 Subject: jack audio connection kit Message-ID: <46F956FE.3090803@11h11.com> hello everyone, is there a way to make python output audio in jack: http://jackaudio.org/ jack is the best audio solution for linux, mac and lately windows. i found 1 project called pyjack, but the author remove the software from his website. that would be neat! pat From miki.tebeka at gmail.com Sun Sep 9 01:57:59 2007 From: miki.tebeka at gmail.com (Miki) Date: Sun, 09 Sep 2007 05:57:59 -0000 Subject: Spell-checking Python source code In-Reply-To: References: <1189285495.185657.88010@o80g2000hse.googlegroups.com> Message-ID: <1189317479.924231.210490@y42g2000hsy.googlegroups.com> >> In an ideal world, my IDE would do this with a red wavy line. > > You didn't mention which IDE you use; however, if you use Emacs, there > is flyspell-prog-mode which does that for you (checks your spelling > "on the fly", but only within comments and strings). Same in Vim (:set spell) HTH, -- Miki http://pythonwise.blogspot.com From brenNOSPAMbarn at NObrenSPAMbarn.net Tue Sep 4 13:53:06 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Tue, 04 Sep 2007 17:53:06 GMT Subject: Python is overtaking Perl References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> <1188925214.716404.219920@22g2000hsm.googlegroups.com> Message-ID: George Sakkis wrote: > On Sep 4, 8:35 am, Jean-Paul Calderone wrote: >> On Tue, 04 Sep 2007 00:32:23 -0000, Ben >> wrote: >> >Here are the statistics from Google Trends: >> >> >http://benyang22a.blogspot.com/2007/09/perl-vs-python.html >> >> >From the graph, it seems more accurate to say that Perl is >> >undertaking Python. >> >> Jean-Paul > > And to make it even more accurate, "Perl is undertaking Python in > India", since that's where the difference in favor of Python comes > from. No, it's the other way around. The big difference in India is in favor of Perl. -- --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 bear at bears.org Thu Sep 20 16:48:16 2007 From: bear at bears.org (Gary Coulbourne) Date: Thu, 20 Sep 2007 16:48:16 -0400 Subject: An Editor that Skips to the End of a Def In-Reply-To: <87odfxjgjy.fsf@pobox.com> References: <87odfxjn16.fsf@rudin.co.uk> <87odfxjgjy.fsf@pobox.com> Message-ID: John J. Lee wrote: > Eclipse must be able to do this. Not by default... but I am certain there are plugins that provide python integration. (And jython integration) Peace, Gary From see.signature at no.spam Wed Sep 5 06:42:28 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 05 Sep 2007 12:42:28 +0200 Subject: Multi Heritage with slots References: <1188982916.071976.160170@g4g2000hsf.googlegroups.com> Message-ID: On Wed, 05 Sep 2007 11:01:56 +0200, Alexandre Badez wrote: > Hye, > > I'm developing a little app, and I want to make multi heritage. > My problem is that my both parent do have __slots__ define. > > So I've got something like: > > class foo(object): > __slots__ = ['a', 'b'] > pass > > class foo2(object): > __slots__ = ['c', 'd'] > pass > > class crash(foo, foo2): > pass > > If you write only that in a sample file or in python console (as I > did), python refuse to load the module and report something like: > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: Error when calling the metaclass bases > multiple bases have instance lay-out conflict > > Do you know why it append? And how could I make this work? See http://mail.python.org/pipermail/python-list/2006-December/418768.html Basically, the general advice you're likely to get here is: don't use __slots__, or at least don't use __slots__ with inheritance. BTW, what are you trying to do? Is it really a memory footprint optimization, which is the intended use case for __slots__, or are you just doing Java in Python? -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From gagsl-py2 at yahoo.com.ar Thu Sep 6 12:44:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Sep 2007 09:44:16 -0700 Subject: ImportError depending on the calling module In-Reply-To: <1189095236.413270.288090@50g2000hsm.googlegroups.com> References: <1189079269.279716.254560@50g2000hsm.googlegroups.com> <1189093482.137051.73770@r29g2000hsg.googlegroups.com> <1189095236.413270.288090@50g2000hsm.googlegroups.com> Message-ID: <1189097056.295186.62020@r29g2000hsg.googlegroups.com> On 6 sep, 13:13, Samuel wrote: > On Sep 6, 5:44 pm, Gabriel Genellina wrote: > > They should import the package as any other > > client code, without doing any import tricks nor playing with > > sys.path. > > Why does it matter whether I install it in sys.path or whether > sys.path is modified? What's the difference? Because it's more simple, less error prone, easier to test, more efficient... > What I am doing is I ship two modules in one tarball with my software. > The software is only unpacked and ran. It has to work without > installation. That's fine, and a good requirement. Place start2.py inside the container directory, and your package beneath it. Then you don't have to modify sys.path to find the package - "import packagename" just works. And it still works if the user installs the package (into site- packages, by example). start1.py start2.py packagename/ |-- Obj.py |-- __init__.py |-- foo/ |-- FooTest.py `-- __init__.py Packages are... well, packages, boxes. Don't try to import a module inside a package as it were a standalone module - relative imports won't work then. This was discussed some time ago -- Gabriel Genellina From steve at holdenweb.com Tue Sep 11 08:46:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 08:46:18 -0400 Subject: Checking if elements are empty In-Reply-To: <588D53831C701746A2DF46E365C018CE01D2CB39@LITEXETSP001.etrsouth.corp.entergy.com> References: <588D53831C701746A2DF46E365C018CE01D2CB39@LITEXETSP001.etrsouth.corp.entergy.com> Message-ID: Hamilton, William wrote: >> From: Steve Holden >> Neil Cerutti wrote: >>> On 2007-09-10, Chris Mellon wrote: >>>> On 9/10/07, Neil Cerutti wrote: >>>>> Agreed; but I prefer 'if y[0] == ""', absent more context and >>>>> better names. >>>> Probably should use u"" if you're going to take that route, as >>>> this will fail spuriously if y[0] contains a unicode string >>>> that can't be implicitly converted to ascii. Personally, I >>>> prefer the boolean check and I'll let operations fail elsewhere >>>> if there's a type mismatch. >>> I have a quibble not with the functionality of the boolean check, >>> but with its expressiveness. if y[0] == "" expresses more, i.e., >>> that I expect y[0] to contain a Python byte string. >>> >> I have a quibble with a test that will raise an exception when the >> anticipated condition is true. Your test is patently absurd, as you >> would have discovered had you bothered to try it: >> >> >>> y = "" >> >>> if y[0] == "": >> ... print "True" >> ... else: >> ... print "False" >> ... >> Traceback (most recent call last): >> File "", line 1, in >> IndexError: string index out of range >> >>> >> >> Further, when the string is *not* the null string the test will always >> return False, as you will be comparing two strings of unequal length. >> >> So, absent a solution that works, len(y) == 0 looks pretty good. > > > Going back to the OP, the problem is taking a string such as >>>> x = ' \t"ff' > then splitting that string like this >>>> y = x.split('\t') > > The question is, does the first element of the list y contain an empty > string or not? In this case, the logic in the following conditional is > perfectly valid. >>>> if y[0] == "": > ... print "True" > ... else > ... print "False" > > (len(y[0]) == 0) would also work, and is the solution you originally > gave the OP. > Aah, list of strings, right. Thanks. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From deets at nospam.web.de Sat Sep 15 10:56:31 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 15 Sep 2007 16:56:31 +0200 Subject: python 2.5 cElementTree entity troubles In-Reply-To: <46EBEEFF.80106@web.de> References: <5l22jsF5taqoU1@mid.uni-berlin.de> <46EBEEFF.80106@web.de> Message-ID: <5l2a5kF60ti9U1@mid.uni-berlin.de> Stefan Behnel schrieb: > Diez B. Roggisch wrote: >> Any suggestions on how to teach the built-in ET-parser entities? > > As you already do it in your code. > > http://effbot.org/elementtree/elementtree-xmlparser.htm#tag-ET.XMLParser.entity > > But I guess your version of cET is just too old. Unfortunately, it's the python 2.5-build-in one.. :( Diez From mal at egenix.com Fri Sep 21 09:20:00 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 21 Sep 2007 14:20:00 +0100 Subject: looking for ocbc example In-Reply-To: References: Message-ID: <46F3C500.7070901@egenix.com> Carl K wrote: > I am sure this is what I want: > http://www.python.org/topics/database/docs.html > "The documentation for the PythonWin ODBC module." > > but it is 404. > > google isn't being nice. > > Anyone know where I can find some simple examples? > > I have used odbc in other environments, so just need to know what modules, and > the lines to connect and execute a sql command. Here's a very simple example for mxODBC: # mxODBC is available from http://www.egenix.com/products/python/mxODBC/: # On Windows: from mx.ODBC import Windows as Database # On Mac OS X: from mx.ODBC import iODBC as Database # On Linux/BSD/etc.: from mx.ODBC import unixODBC as Database # or from mx.ODBC import iODBC as Database # Open a connection to the database connection = Database.DriverConnect('DSN=;' 'UID=;' 'PWD=;' 'KEYWORD=') # replace the values accordingly, add new keyword-value pairs as # necessary for your data source; data sources are configured # in the ODBC manager # Create a cursor; this is used to execute commands cursor = connection.cursor() # Create a table cursor.execute('CREATE TABLE mxodbcexample1 ' ' (id integer, name varchar(10), data varchar(254))') # this command does not create a result set, so there's nothing # to fetch from the database; however in order to make the # change permanent, we need to commit the change connection.commit() # Prepare some data rows to add to the table, ie. a list of tuples rows = [] for i in range(42): name = 'name-%i' % i data = 'value-%i' % i rows.append((i, name, data)) # Add the data in one go; the values from the tuples get assigned # to the ?-mark parameter markers in the SQL statement based on # their position and the SQL statement is executed once for # each tuple in the list of rows cursor.executemany('INSERT INTO mxodbcexample1 VALUES (?,?,?)', rows) # If you apply changes to the database, be sure to commit or # rollback your changes; a call to .commit() or .rollback() # will implicitly start a new transaction connection.commit() # Now fetch some data rows from_id = 40 to_id = 42 cursor.execute('SELECT * FROM mxodbcexample1' ' WHERE (id >= ?) and (id < ?)', (from_id, to_id)) # Fetch the results for i, row in enumerate(cursor.fetchall()): print 'Row %i: %r' % (i, row) # Remove the table again cursor.execute('DROP TABLE mxodbcexample1') connection.commit() # Close the connection connection.close() With MS Access this gives: Row 0: (40, 'name-40', 'value-40') Row 1: (41, 'name-41', 'value-41') -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From f.guerrieri at gmail.com Wed Sep 5 13:43:16 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Wed, 5 Sep 2007 19:43:16 +0200 Subject: PythonAlley.com In-Reply-To: <1189012363.397845.174960@y42g2000hsy.googlegroups.com> References: <1189012363.397845.174960@y42g2000hsy.googlegroups.com> Message-ID: <79b79e730709051043j4ab048ebsde172278835c8a06@mail.gmail.com> On 9/5/07, dkeeney wrote: > > > The Python community would benefit from a moderated web-forum along > the lines of > perlmonks.org. > > The Python community online now seems to have two major segments, the > c.l.p newsgroup (here), > and a large selection of blogs. C.l.p is unmoderated and often > hostile. The bloggers > Actually c.l.py is one of the least hostile place (and more helpful for the newcomers, like myself) I ever met on the net. I will concede that I've only been online since twelve years so in the good ol' times surely there were many more place better than this one. francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From see.signature at no.spam Tue Sep 4 05:31:06 2007 From: see.signature at no.spam (Eric Brunel) Date: Tue, 04 Sep 2007 11:31:06 +0200 Subject: Tkinter References: <1188882720.020666.67490@k79g2000hse.googlegroups.com> Message-ID: On Tue, 04 Sep 2007 07:12:00 +0200, vijayca wrote: > i tried to use python gui module Tkinter in solaris,aix,hpux..... > while importing the module it shows an error... > > import Tkinter > error says that your python may not be configured for Tk()... > how to get out of this... Did you compile the Python interpreter yourself, or did it come in a sort of package? In the first case, you have to install tcl/tk yourself if it's not already there, then tweak the build options for Python to make it use the tcl/tk installation you've done. How to tweak these options depends on the Python version you use, so please tell us what it is. In the second case, Tkinter may be provided as a separate package, that you also need to install. And BTW, Wildemar's comment still holds: please copy/paste the exact traceback you get if it doesn't work. I'm only guessing here... HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From deets at nospam.web.de Tue Sep 18 07:07:36 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Sep 2007 13:07:36 +0200 Subject: Looking for web software in Python. References: Message-ID: <5l9proF75mf3U1@mid.uni-berlin.de> Kevin Ar18 wrote: > > Are any of the following pieces of web software available in Python (under > a non-copyleft license like BSD or MIT or Python license)? > > > Mailing list - with web accessable archive and list maintenance. > Source control > Wiki System For the last two, look at TRAC. But I'm not sure about the license - check that out for yourself. Diiez From steven.bethard at gmail.com Wed Sep 12 14:46:06 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Sep 2007 12:46:06 -0600 Subject: pwdmodule.c In-Reply-To: <1189622437.459458.129390@57g2000hsv.googlegroups.com> References: <1189622437.459458.129390@57g2000hsv.googlegroups.com> Message-ID: hvendelbo.dev at googlemail.com wrote: > I am trying to compile Python with cmake, but perhaps there are a few > dependencies that have not been corrected for Windows compilation. I don't know the specific answers to your questions, but I wanted to point out, in case you didn't already know, that Alexander Neundorf successfully compiled Python with CMake and posted the necessary files: http://mail.python.org/pipermail/python-dev/2007-July/073912.html STeVe From modiinfo at gmail.com Mon Sep 10 08:25:46 2007 From: modiinfo at gmail.com (Harshad Modi) Date: Mon, 10 Sep 2007 12:25:46 -0000 Subject: encoding latin1 to utf-8 Message-ID: <1189427146.723304.270600@22g2000hsm.googlegroups.com> hello , I make one function for encoding latin1 to utf-8. but i think it is not work proper. plz guide me. it is not get proper result . such that i got "Belgi???" using this method, (Belgium) : import codecs import sys # Encoding / decoding functions def encode(filename): file = codecs.open(filename, encoding="latin-1") data = file.read() file = codecs.open(filename,"wb", encoding="utf-8") file.write(data) file_name=sys.argv[1] encode(file_name) From gagsl-py2 at yahoo.com.ar Fri Sep 14 02:59:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Sep 2007 03:59:31 -0300 Subject: Spaces from string specifier References: <03a601c7f68b$ccdf1ed0$669d5c70$@com> Message-ID: En Fri, 14 Sep 2007 01:57:43 -0300, Gavin Tomlins escribi?: > I'm trying to work out when using a format specifier I get spaces in the > resulting string. Eg. Looking at the outputted string you can see that > there are spaces after T5LAT, F4LAT etc. as I result from trying to keep > the > code aligned - You should *not* build the SQL text yourself; use a parametrised query instead. It's not only easier to write; it's safer, less error prone, and maybe faster. See this previous post - Spaces are not significant in SQL, but you may have your own reasons to format the SQL text in a certain way. In addition to the ideas already menctioned on that thread (avoid \, use parenthesis, and auto-concatenate adjacent strings), you may use a triple-quoted string + function dedent from textwrap module: py> fmtSqlP300Amp = textwrap.dedent('''\ ... UPDATE Patient SET ... O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s", ... P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s", ... TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s" ... WHERE Pat_Id = "%s"''') py> print fmtSqlP300Amp UPDATE Patient SET O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s", P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s", TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s" WHERE Pat_Id = "%s" I hope any of these ideas will fit your own needs. -- Gabriel Genellina From sjmachin at lexicon.net Tue Sep 18 18:31:05 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Sep 2007 15:31:05 -0700 Subject: Parsing problems: A journey from a text file to a directory tree In-Reply-To: References: <1189958074.670245.17910@n39g2000hsh.googlegroups.com> Message-ID: <1190154665.944722.137750@q3g2000prf.googlegroups.com> On Sep 19, 4:51 am, "Michael J. Fromberger" wrote: > . > . # This expression matches "header" lines, defining a new section. > . new_re = re.compile(r'\[([\w ]+)\]\s*$') Directory names can contain more different characters than those which match [\w ] ... and which ones depends on the OS; might as well just allow anything, and leave it to the OS to complain. Also consider using line.rstrip() (usually a handy precaution on ANY input text file) instead of having \s*$ at the end of your regex. > . > . while new_level < len(state): > . state.pop() Hmmm ... consider rewriting that as the slightly less obfuscatory while len(state) > new_level: state.pop() If you really want to make the reader slow down and think, try this: del state[new_level:] A warning message if there are too many "-" characters might be a good idea: [foo] |-bar |-zot |---plugh > . > . state[-1][key] = {} > . state.append(state[-1][key]) > . And if the input line matches neither regex? > . return out > > To call this, pass a file-like object to parse_folders(), e.g.: > > test1 = ''' > [New client]. Won't work with the dot on the end. > Michael J. Fromberger | Lecturer, Dept. of Computer Science From grante at visi.com Sat Sep 1 20:12:52 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Sep 2007 00:12:52 -0000 Subject: Looking for Delaunay triangulation module... References: <13dge9m2339ka68@corp.supernews.com> <13dhqbm42tr1i7b@corp.supernews.com> <1188686186.415022.293900@19g2000hsx.googlegroups.com> Message-ID: <13dk004g643p346@corp.supernews.com> On 2007-09-01, drobinow at gmail.com wrote: >>>> So for lack of a delaunay module, I'm stuck trying to port my >>>> application to Win32. >> >>> Why not run it under Cygwin? :) >> >> I'm hoping there is an easier way than trying to build a >> half-dozen large Python extensions (and their supporting >> libraries) under Cygwin. > > Well, that's what Cygwin is for -- to make it easy to do that. I know that's its intent. In my experience it doesn't succeed very well. I've spent years supporting a set of development tools under both Cygwin and Linux. The Cygwin versions are a continuous pain for everybody involved. > What's not working? I have never tried to run my application under Cygwin. AFAICT, many of the Python packages I use aren't available as packages for Cygwin, and I don't really want to spend the time trying to build and maintain them. My experiences building things from source in Cygwin haven't been good in the past, and I have zero experience bundling up Cygwin-hosted applications for delivery. I have used an application suite under Windows that comprised Cygwin apps and a bundled Cygwin installation, and it was a total distaster. Perhaps that was just a singularly bad example, but it sure made it seem like using Cygwin as a platform for delivering Windows applications was a bad idea. > I'm also not clear what your problem is with Delny with qhull > under Windows. I wasn't able to find a copy of Delny and qhull library for Windows. I did find postings asking where one could be found. Those postings went unanswered. > What errors have you gotten? > > All the tests pass for me. -- Grant Edwards grante Yow! Alright, at you!! Imitate a WOUNDED visi.com SEAL pleading for a PARKING SPACE!! From obazzzz2007 at gmail.com Tue Sep 18 17:55:35 2007 From: obazzzz2007 at gmail.com (blade) Date: Tue, 18 Sep 2007 14:55:35 -0700 Subject: buy any tthing from the web free without creditcards.. true .. simple .. legal Message-ID: <1190152535.926647.253810@y42g2000hsy.googlegroups.com> first : click on this link and make a new account http://www.AWSurveys.com/HomeMain.cfm?RefID=alshab write some very short reviews on soms very few sites -= earn your money keep earning money till the amount u need for a certain thing u want to buy creat a new free account on paypal.com transfer your money from the first site to paypal.com use your money From robert.kern at gmail.com Tue Sep 4 00:24:42 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Sep 2007 23:24:42 -0500 Subject: Applying transformation matrix to 3D vertex coordinates In-Reply-To: <5rjod3lih4mnupjcm2184k5no15eodlc8r@4ax.com> References: <5rjod3lih4mnupjcm2184k5no15eodlc8r@4ax.com> Message-ID: PhilC wrote: > ''' > ################################################ > Task:- > to apply a translation array to an array > of 3D vertex coordinates to produce the > resulting location of each vertices. > > Translation array and vertex coordinates taken from > a Truespace COB file. > > The text in the COB file looks like this:- > > Transform > -2.11786 -0.817596 0.946387 0.864939 > 0.405189 1.25484 2.11894 0.434915 > -1.16679 1.9198 -0.981965 1.13894 > 0 0 0 1 > World Vertices 8 > -0.200000 -0.029486 -0.236313 > 0.200000 0.029486 -0.163687 > -0.200000 0.370514 -0.282911 > -0.200000 0.370514 0.117089 > -0.200000 -0.029486 0.163687 > 0.200000 0.029486 0.236313 > 0.200000 0.429486 -0.210286 > 0.200000 0.429486 0.189714 > > ############################################### > ''' > # script start > > import Numeric > > transArray = Numeric.array(( > (-2.11786, -0.817596, 0.946387, 0.864939), > (0.405189, 1.25484, 2.11894, 0.434915), > (-1.16679, 1.9198, -0.981965, 1.1389), > (0, 0, 0, 1) > )) > > # a "1" added to the end of each set of vertix coordinates > vertArray = Numeric.array(( > (-0.200000, -0.029486, -0.236313, 1), > (0.200000, 0.029486, -0.163687, 1), > (-0.200000, 0.370514, -0.282911, 1), > (-0.200000, 0.370514, 0.117089, 1), > (-0.200000, -0.029486, 0.163687, 1), > (0.200000, 0.029486, 0.236313, 1), > (0.200000, 0.429486, -0.210286, 1), > (0.200000, 0.429486, 0.189714, 1) > )) > > print transArray > print "" > print vertArray > print "" > > transArray = Numeric.reshape(transArray,(4,4)) > vertArray = Numeric.reshape(vertArray,(4,8)) > > print Numeric.matrixmultiply(transArray,vertArray) > > # script end > ''' > ################################################################## > Result:- > > [[ 0.5708016 0.10309048 0.70481144 -1.12413 0.1022124 > 0.03400637 0.63866924 -1.12413 ] > [-0.6688108 0.57729922 -0.19537307 4.213884 0.3408408 > 0.72615216 0.66384632 4.213884 ] > [ 0.273571 1.26381257 -0.66763452 0.909945 -0.585931 > 1.13709619 0.39979 0.909945 ] > [ 0.2 0.429486 -0.210286 1. 0.2 > 0.429486 0.189714 1. ]] > > Am I going in the right direction? No. The reshape didn't do what you want it to. The elements will have the same order; it won't transpose the array. To do that, use the transpose() function. > What do I do with the result? :) When you have it correct, the last row will be all 1s. Ignore 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 bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 3 10:26:30 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 03 Sep 2007 16:26:30 +0200 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <46DB04DD.80801@v.loewis.de> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> Message-ID: <46dc1995$0$30627$426a34cc@news.free.fr> Martin v. L?wis a ?crit : >>> (2) it is a interpretation language >> Not quite. It's compiled to byte-code - just like Java (would you call >> Java an 'interpreted language' ?) > > Python is not implemented like Java. In Java (at least in HotSpot), > the byte code is further compiled to machine code before execution; This is a VM-specific feature. > in Python, the byte code is interpreted. Idem. > Whether this makes Python an interpreter or a compiler, > I don't know. This is an old troll^Mdiscussion !-) Now IANAL, but AFAIK, the byte-code compilation stage can make a great difference performances-wide, and for a same language, a byte-compiled implementation is likely to be faster than a pure-interpreted one, at least because of the saving on parsing time (please someone correct me if I'm wrong) ... From no-spam at not-existing.invalid Tue Sep 11 11:19:36 2007 From: no-spam at not-existing.invalid (robert) Date: Tue, 11 Sep 2007 17:19:36 +0200 Subject: ValueError: insecure string pickle ? Message-ID: cPickle.loads raised "ValueError: insecure string pickle". The error is from a log file and I cannot reproduce it (quickly). What can be the cause for that error? Robert From http Mon Sep 3 01:56:48 2007 From: http (Paul Rubin) Date: 02 Sep 2007 22:56:48 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> <13dmctogeh19410@corp.supernews.com> Message-ID: <7x4picthpb.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: A big > question mark in my mind is Lisp, which according to aficionados is > just as dynamic as Python, but has native compilers that generate > code running as fast as highly optimized C. I'm not qualified to > judge whether the lessons learnt from Lisp can be applied to Python, > but in any case Lisp is an old, old language -- only Fortran is > older. The amount of development effort and money put into Lisp > dwarfs that put into Python by possibly a hundred or more. Writing a simple Lisp compiler is not all that difficult. There's a chapter in SICP about how to do it, so it's sometimes part of introductory courses. To get C-like performance you end up having to rely on user-supplied type declarations and/or type inference, but even without that you can still do ok. I'd say Lisp is a less dynamic language than Python. Lisp doesn't have duck typing and doesn't represent class instance variables as dictionary elements that have to be looked up at runtime all the time. This maybe even applies to locals, e.g. in Python if you say x = 3 print "hello" y = x + 4 you're possibly not guaranteed that y=7, because you might have bound sys.stdout to something with a .write method that reaches up the call stack and messes with the caller's local variables, and if the langref manual says this is supposed to work, then the compiler has to do it like CPython. Maybe Python 4.0 will fix some of this stuff. From kelvie at ieee.org Sun Sep 23 16:16:51 2007 From: kelvie at ieee.org (Kelvie Wong) Date: Sun, 23 Sep 2007 13:16:51 -0700 Subject: building a GUI In-Reply-To: <5lnp2rF90pqqU1@mid.uni-berlin.de> References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> <5lnp2rF90pqqU1@mid.uni-berlin.de> Message-ID: <94ccbe710709231316ld901bdfo6d9e57974df3d101@mail.gmail.com> On 9/23/07, Diez B. Roggisch wrote: > > stef mientki schrieb: > > Thomas Dybdahl Ahle wrote: > >> Den Sun, 23 Sep 2007 17:28:38 +0200 skrev stef mientki: > >> > >>> yadin wrote: > >>> > >>> > >>>> if i were up to make a GUI chich are the advantages of choosing > python > >>>> over matlab or java? > >>>> > >>>> > >>> The best is Delphi, > >>> second is VB, > >>> > >> > >> That sounds mostly like a personal preference :) > >> > >> > > Well I prefer Python ( because of it's OS-independancy and it's open > > source), > > but Python is really (still) much worse for GUI designs. > > Just compare some parameters like: > > - ease of use > > - speed of development > > - support of features > > - availability of libraries > > - documentation > > Sounds like PyQt for me. Best GUI-designer I know, tremendous speed in > development, giant sized lib that does all kinds of stuff & is > brilliantly designed + professional grade docus. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > I'll have to agree completely here, Qt is just so great to work with. It makes my day job (I have to do it in C++) much more bearable. Phil Thompson (who maintains PyQt) is also very responsive and updates frequently even if you haven't bought a commercial licence for it. I also have to agree that the Qt Designer is the best I've ever had to work with, and I can't think of an instance where Qt Assistant wasn't open on one desktop or another. -- Kelvie -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Thu Sep 27 12:42:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Sep 2007 16:42:55 GMT Subject: ValueError: too many values to unpack,>>> References: Message-ID: <5m24sfFatlbuU1@mid.uni-berlin.de> On Thu, 27 Sep 2007 12:36:58 -0400, Shawn Minisall wrote: > With the multiple value lines, python says this "ValueError: too many > values to unpack" > > I've googled it and it says that happens when you have too few or too > many strings that don't match with the variables in number your trying > to assign them too. Below are the lines in reading in: > > line 3 - 19.18 29.15 78.75 212.10 > line 4 - 100 20 410.29 > > And this is the code I'm using: > > #read withdrawls from file on line3 > line = infile.readline() > > #split withdrawls up > withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") > > #read deposits from file on line4 > line = infile.readline() > #split deposits up > deposit1, deposit2, deposit3 = string.split(line, "\t") > > I have 4 strings to match line 3 and 3 to match the 3 on line 4...any > thoughts? First thought is to find out which of the two lines triggers the exception. This information is part of the full traceback. Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Mon Sep 17 17:14:41 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 17 Sep 2007 21:14:41 -0000 Subject: Extracting xml from html In-Reply-To: <1190062919.998077.112810@19g2000hsx.googlegroups.com> References: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> <1190062919.998077.112810@19g2000hsx.googlegroups.com> Message-ID: <1190063681.632965.249020@y42g2000hsy.googlegroups.com> On Sep 17, 4:01 pm, Paul Boddie wrote: > On 17 Sep, 22:31, kyoso... at gmail.com wrote: > > > > > What's the best way to get at the XML? Do I need to somehow parse it > > using the HTMLParser and then parse that with minidom or what? > > Probably easiest is to use an XML processing toolkit or library which > supports HTML parsing. Since the libxml2 library (written in C) makes > a fairly good job of HTML parsing, I would suggest either libxml2dom > (for a DOM-like API) or lxml (for an ElementTree-like API) as suitable > Python wrappers of libxml2. Of course, HTMLParser or SGMLParser should > work, but the programming style is a bit more convoluted unless you're > used to XML processing using a SAX-like API. > > Paul > > P.S. I'm biased towards libxml2dom, being the developer, but I use it > routinely and it generally does the job for me. I have lxml installed and I appear to also have libxml2dom installed. I know lxml has decent docs, but I don't see much for yours. Is this the only place to go: http://www.boddie.org.uk/python/libxml2dom.html ? Mike From bignose+hates-spam at benfinney.id.au Tue Sep 25 23:12:47 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 26 Sep 2007 13:12:47 +1000 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: <87myvaktlc.fsf@benfinney.id.au> Lawrence D'Oliveiro writes: > That's another issue, that of ROI. Having learnt the vi/vim > keystrokes, what does that enable you to do? Use vi/vim, and that's > it. There are a great many programs whose interactive keybindings come from vi. Perhaps you've heard of 'less', 'screen', 'mutt', or dozens of other frequently-used programs, all of which use 'vi key bindings by default. > Whereas I've found other situations where subsets of Emacs > keystrokes are recognized, such as anything that uses GNU readline Which can also be configured one-time by the user to use 'vi' keybindings everywhere, so the 'vi' fanatic is able to keep using the key bindings they know. I think this argument is silly ? both Emacs and vi(m) have enormous following, are both extremely capable editors, and both are clearly the inspiration for many other programs' key bindings. It's ludicrous to say of either program that "once you learn its key bindings you only know how to use that program". -- \ "Welchen Teil von 'Gestalt' verstehen Sie nicht? [What part of | `\ 'gestalt' don't you understand?]" -- Karsten M. Self | _o__) | Ben Finney From ldo at geek-central.gen.new_zealand Mon Sep 10 20:36:17 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Sep 2007 12:36:17 +1200 Subject: zlib References: Message-ID: In message , Milos Prudek wrote: > Although I have Python 2.5 with zlib in my Linux disto, I need to install > my own Python (as most Zope developers do). Why? > Zope requires zlib. Python 2.4.4 does not contain zlib. So why does your own Python version have to be 2.4.4? From bdesth.quelquechose at free.quelquepart.fr Thu Sep 13 15:29:53 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 13 Sep 2007 21:29:53 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <5ktfjqF5ctrvU2@mid.individual.net> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <5ksoaoF5am8cU1@mid.individual.net> <1189701793.466307.93210@g4g2000hsf.googlegroups.com> <5ktfjqF5ctrvU2@mid.individual.net> Message-ID: <46e98fd8$0$27757$426a34cc@news.free.fr> Bjoern Schliessmann a ?crit : > TheFlyingDutchman wrote: > >>Here's a FAQ item where they refer to it as I think Python should >>have done it - a special predefined variable: > > > Maybe. Personally, I like it the way it is in Python. > > Why don't you make a preprocessor which accepts method declarations > without "self" and fixes them? The problem being that there's no such thing as a "method declaration" in Python - only functions being attributes of a class... (ok, I know, you meant "functions declared within a class statement"). From arnodel at googlemail.com Thu Sep 6 01:51:34 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 05 Sep 2007 22:51:34 -0700 Subject: Text processing and file creation In-Reply-To: References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> <1189027883.834083.291430@19g2000hsx.googlegroups.com> Message-ID: <1189057894.218881.227020@d55g2000hsg.googlegroups.com> On Sep 6, 12:46 am, Steve Holden wrote: > Arnaud Delobelle wrote: [...] > > print "all done!" # All done > > print "Now there are 4000 files in this directory..." > > > Python 3.0 - ready (I've used open() instead of file()) > > bzzzzzzzzzzt! > > Python 3.0a1 (py3k:57844, Aug 31 2007, 16:54:27) ... > Type "help", "copyright", "credits" or "license" for more information. > >>> print "all done!" # All done > File "", line 1 > print "all done!" # All done > ^ > SyntaxError: invalid syntax > >>> Damn! That'll teach me to make such bold claims. At least I'm unlikely to forget again now... -- Arnaud From wolf_tracks at invalid.com Tue Sep 18 22:39:05 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 19 Sep 2007 02:39:05 GMT Subject: Tutorial or Example (or Tutorial) of Using Canvas to Produce a Plot In-Reply-To: References: <13evohih7rkd030@corp.supernews.com> <13f0b2qlvj5ige6@corp.supernews.com> <9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com> Message-ID: Ah, I missed your link to Chap 11. That looks very helpful. W. Watson wrote: > Thanks. I've arranged for an inter-library loan(ILL), and probably will > not get his book for several days yet. I've had the book before, but was > really unable to get the time to pursue it (the ILL). I have his web > site bookmarked. I do not yet plan to buy his book, web or hardbound > yet. Maybe I can re-examine his site for examples, and find one that is > appropriate. > > > Richard Townsend wrote: >> On Tue, 18 Sep 2007 13:18:36 -0700, "W. Watson" >> wrote: >> >>> Tk is it. I'm really not interested in the others at this point. >>> >> >> John Grayson's book 'Python and Tkinter Programming' has a chapter on >> plotting Graphs and Charts. You can even download that chapter as a >> PDF file: >> >> http://www.manning-source.com/books/grayson/grayson_ch11.pdf >> >> See http://www.manning.com/grayson/ for more info about the book. >> > -- Wayne Watson (Nevada City, CA) Web Page: From bh at izb.knu.ac.kr Sun Sep 30 06:22:07 2007 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Sun, 30 Sep 2007 19:22:07 +0900 Subject: Can you please give me some advice? Message-ID: <1191147727.1699.15.camel@viola.izb.knu.ac.kr> Hi there, What is different between Ruby and Python? I am wondering what language is really mine for work. Somebody tell me Ruby is clean or Python is really easy! Anyway I will really make decision today what I have to study from now on. What I make the decision is more difficult than to know why I have to learn English. Yeah I do not like to learn English because it is just very painful.. Can you please give me some advice? Byung-Hee From python-url at phaseit.net Mon Sep 24 07:46:50 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 24 Sep 2007 11:46:50 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 24) Message-ID: QOTW: "This thread shows again that Python's best feature is comp.lang.python." - Joerg Schuster "I find it best to treasure the saints, tolerate the irritable and ignore the whiners." - RedGrittyBrick Python as a functional language: of limited usage due to stack limitations: http://groups.google.com/group/comp.lang.python/browse_thread/thread/2b476f8d3a290f1b/ Generator functions, generator expressions... what is a generator, after all? http://groups.google.com/group/comp.lang.python/browse_thread/thread/7a4f8d011e6badcf/ A proposal for removing bitwise operators (most people said "no, because..."): http://groups.google.com/group/comp.lang.python/browse_thread/thread/4a16e4cba57b1c4d/ How widely is Python used at Google? http://groups.google.com/group/comp.lang.python/browse_thread/thread/af75a3e91a03ec18/ An example of optimizing a Python program: http://groups.google.com/group/comp.lang.python/browse_thread/thread/fa33727aa3a6751f/ About sets, dicts, hash and mutable containers: http://groups.google.com/group/comp.lang.python/browse_thread/thread/bc8377a8a5d89a3f/ super() documentation and actual behavior are confusing: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9b38dc19c6beeb8b/ Functions, the def statement, lambda calculus, and why those things are the way they are: http://groups.google.com/group/comp.lang.python/browse_thread/thread/661eb7a7e80d310a/ ======================================================================== 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 Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. 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 enthusiats": 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/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ 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/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch 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://aspn.activestate.com/ASPN/Cookbook/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 are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php 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/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. 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 *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python 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 bdesth.quelquechose at free.quelquepart.fr Sat Sep 15 13:28:11 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 15 Sep 2007 19:28:11 +0200 Subject: subclass of integers In-Reply-To: <1189782046.121148.65220@22g2000hsm.googlegroups.com> References: <1189780201.692192.291010@k79g2000hse.googlegroups.com> <1189782046.121148.65220@22g2000hsm.googlegroups.com> Message-ID: <46ead5f3$0$14839$426a74cc@news.free.fr> Zentrader a ?crit : > This would accept ints, floats, and decimal types. It doesn't... > import decimal Useless > class Nint(int): > def __add__(self, x, y): The prototype for __add__ is __add__(self, other) > try: > return x+y > except: > return None > > if __name__=='__main__': > N=Nint() > print N.__add__( 1, 2 ) > print N.__add__( 1, None ) > print N.__add__(decimal.Decimal("2"), decimal.Decimal("3")) > print N.__add__(decimal.Decimal("2"), 3) > i = Nint(42) i + 33 Traceback (most recent call last): File "", line 1, in ? TypeError: __add__() takes exactly 3 arguments (2 given) The following works better (at least for integers - which is what the OP saked for), but it's still not the solution: import types class Nint(int): def __new__(cls, value=0): # doesn't work with Nint(None)... return int.__new__(cls, value) def __add__(self, other): if isinstance(other, int): return int.__add__(self, other) elif isinstance(other, types.NoneType): return None else: err = "unsupported operand type(s) for +: '%s' and '%s'" \ % (type(self), type(other)) raise TypeError(err) i = Nint(42) => 42 i + None => None i + "allo" Traceback (most recent call last): File "", line 1, in ? File "/usr/tmp/python-8683q3Z", line 19, in __add__ TypeError: unsupported operand type(s) for +: '' and '' Fo some reasons I'm not sure about and didn't have time to investigate (some guru around ?), trying to catch a TypeError in __add__ failed - raising a TypeError ! But anyway, this isn't the correct solution since we don't want Nint.__add__ to return None when other is neither an int nor None. Anyway, this still doesn't solves the OP's problem since it doesn't satisfy isinstance(Nint(None), NoneType). I tried making Nint a subclass of both int and NoneType, but it doesn't work for obvious reasons (None is a singleton). The only funny thing here is the error message when trying to call NoneType.__new__: >>> NoneType.__new__(NoneType) Traceback (most recent call last): File "", line 1, in ? TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__() >>> The best I could come with is: from types import NoneType class Nint(int, NoneType): def __new__(cls, value=None): # by default, will return Nint(0) even if value is None return int.__new__(cls, value) def __add__(self, other): if isinstance(other, int): return int.__add__(self, other) elif isinstance(other, NoneType): return None else: err = "unsupported operand type(s) for +: '%s' and '%s'" \ % (type(self), type(other)) raise TypeError(err) # other __functions__ to implement, left as an exercise to the OP __all__ = [Nint] Maybe some guru around will find something better, but I have some doubts... From __peter__ at web.de Fri Sep 14 03:40:47 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Sep 2007 09:40:47 +0200 Subject: "once" assigment in Python References: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> Message-ID: Lorenzo Di Gregorio wrote: > I've been using Python for some DES simulations because we don't need > full C speed and it's so much faster for writing models. During > coding I find it handy to assign a variable *unless it has been > already assigned*: I've found that this is often referred to as "once" > assigment. > > The best I could come up with in Python is: > > try: > variable > except NameError: > variable = method() > > I wonder if sombody has a solution (trick, whatever ...) which looks > more compact in coding. Something like: > > once(variable, method) > > doesn't work, but it would be perfect. Of course I can preprocess the > Python code but an all-Python solution would be more handy. > > Any suggestions? You can use properties to implement lazy evaluation. Or you can rely on a naming convention: >>> class Once(object): ... def __getattr__(self, name): ... if name.startswith("_calc_"): ... raise AttributeError("No method to calculate attribute %r" % name[6:]) ... value = getattr(self, "_calc_" + name)() ... setattr(self, name, value) ... return value ... >>> class A(Once): ... def _calc_foo(self): ... print "calculating foo" ... return 42 ... >>> a = A() >>> a.foo calculating foo 42 >>> a.foo 42 >>> a.bar Traceback (most recent call last): File "", line 1, in File "", line 5, in __getattr__ File "", line 4, in __getattr__ AttributeError: No method to calculate attribute 'bar' >>> a._calc_bar = lambda: "bar-value" >>> a.bar 'bar-value' Peter From deets at nospam.web.de Wed Sep 26 07:44:19 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Sep 2007 13:44:19 +0200 Subject: setuptools without unexpected downloads References: <87ejgmklep.fsf@benfinney.id.au><5luhb0Faal8aU1@mid.uni-berlin.de> <874phhlupi.fsf@benfinney.id.au> <5lumarFae888U1@mid.uni-berlin.de> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> Message-ID: <5luv0iFaai82U1@mid.uni-berlin.de> > I think most of the evolution has been in the surrounding tools, > although stuff like the new Debian Python policy could be complicating > factors. But I don't think the dependency stuff has changed that much > over the years. It might be, yet one thing is for sure: there have been various times in debian in the last few year where for the sake of their own migration paths to e.g. newere GCC-versions and the like a lot of seemingly "crude" packages appeared, that catered to these needs. So it's not only about the package form, one also has to take the actual distribution and even version into consideration... seems daunting to me! > My response here was mostly addressing the "global site-packages" > issue since that's usually a big reason for people abandoning the > system package/dependency management. If you can't find a new-enough > system package, you have to either choose a local "from source" > installation (which I would regard as a temporary measure for reasons > given elsewhere with respect to maintenance), or to choose to > repackage the upstream code and then install it through the system > package manager, which I claim can be achieved in a non-global > fashion. Do I understand that correctly that essentially you're saying: if you want your software released for a certain distro, package it up for it the way it's supposed to be? I can understand that and said so myself - but then, the whole setuptools-debate has come to an end. Diez From david at asdf.asdf Mon Sep 10 03:42:16 2007 From: david at asdf.asdf (bambam) Date: Mon, 10 Sep 2007 17:42:16 +1000 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> <13e99756io95p66@corp.supernews.com> Message-ID: <13e9taoa44icgb4@corp.supernews.com> I have a number of news readers here, but all of them work better with top-posting, and in none of them is top posting a problem. What software are you using? Steve. "Lawrence D'Oliveiro" wrote in message news:fc2c86$i1l$4 at lust.ihug.co.nz... > In message <13e99756io95p66 at corp.supernews.com>, bambam wrote: > >> Thank you, > > Don't top-post. From ricaraoz at gmail.com Fri Sep 7 14:25:09 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 07 Sep 2007 15:25:09 -0300 Subject: why should I learn python In-Reply-To: <200709061602.52121.brown@esteem.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> <200709061602.52121.brown@esteem.com> Message-ID: <46E19785.5030801@bigfoot.com> Tom Brown wrote: > On Thursday 06 September 2007 15:44, Torsten Bronger wrote: >> Hall?chen! >> >> Tom Brown writes: >>> [...] Python has been by far the easiest to develop in. Some >>> people might say it is not "real programming" because it is so >>> easy. >> I can't believe this. Have you really heard such a statement? > > Yes. I was told this by a C programmer. Something about doing it all yourself > and not using provided packages. I countered with something about reinventing > the wheel. :) > You should have asked if he used the OS or did he control the devices (HD, screen) himself. From duncan.booth at invalid.invalid Mon Sep 10 07:20:52 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Sep 2007 11:20:52 GMT Subject: less obvious "super" References: <1189417830.645749.226120@d55g2000hsg.googlegroups.com> Message-ID: Nagarajan wrote: > Here is what I need to achieve.. > > class A : > def __init__( self ): > self.x = 0 Don't use old style classes. If you are planning to use 'super' then you must use new-style classes, so use 'object' as a base class here. > > class B ( A ): > def __init__( self, something ): > # Use "super" construct here so that I can "inherit" x of A > self.y = something > > How should I use "super" so that I could access the variable "x" of A > in B? > If you aren't worried about diamond shaped multiple inheritance hierarchies then just use: class B ( A ): def __init__( self, something ): A.__init__(self) self.y = something If you are then: class B ( A ): def __init__( self, something ): super(B, self).__init__() self.y = something When you use super you usually just want the current class and current instance as parameters. Putting that together: >>> class A(object): def __init__( self ): self.x = 0 >>> class B ( A ): def __init__( self, something ): super(B, self).__init__() self.y = something >>> obj = B(3) >>> obj.x 0 >>> obj.y 3 >>> From wolf_tracks at invalid.com Tue Sep 18 16:18:36 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Tue, 18 Sep 2007 13:18:36 -0700 Subject: Tutorial or Example (or Tutorial) of Using Canvas to Produce a Plot In-Reply-To: <13f0b2qlvj5ige6@corp.supernews.com> References: <13evohih7rkd030@corp.supernews.com> <13f0b2qlvj5ige6@corp.supernews.com> Message-ID: Tk is it. I'm really not interested in the others at this point. Grant Edwards wrote: > On 2007-09-18, W. Watson wrote: > >> What would be appropriate? What are the choices? I'm pretty new to Python, >> but am familiar with the XWindow widget set. > > There's no such thing as "the XWindow widget set". There are > at least 8-10 different X Windows widget sets. The ones that I > can name off the top of my head: > > Tk > Athena > Motif > FLTK > GTK > Qt > XRT > WxWidgets (actually sort of meta-widget-set) > > http://en.wikipedia.org/wiki/Widget_toolkit > > http://en.wikipedia.org/wiki/List_of_widget_toolkits#On_Unix.2C_under_the_X_Window_System > -- Wayne Watson (Nevada City, CA) Web Page: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Sep 11 16:47:36 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 11 Sep 2007 22:47:36 +0200 Subject: Compiler Python References: <000001c7f4a2$307fa720$917ef560$@com> Message-ID: <5kod78F3udmuU1@mid.individual.net> anton a wrote: > Someone knows since as I can obtain the information detailed about > the compiler of Python? (Table of tokens, lists of productions of > the syntactic one , semantic restrictions...) I'm not really about the syntax of your question, but I'd try looking at the source code. Regards, Bj?rn -- BOFH excuse #228: That function is not currently supported, but Bill Gates assures us it will be featured in the next upgrade. From knipknap at gmail.com Thu Sep 6 13:41:42 2007 From: knipknap at gmail.com (Samuel) Date: Thu, 06 Sep 2007 17:41:42 -0000 Subject: ImportError depending on the calling module In-Reply-To: <1189097056.295186.62020@r29g2000hsg.googlegroups.com> References: <1189079269.279716.254560@50g2000hsm.googlegroups.com> <1189093482.137051.73770@r29g2000hsg.googlegroups.com> <1189095236.413270.288090@50g2000hsm.googlegroups.com> <1189097056.295186.62020@r29g2000hsg.googlegroups.com> Message-ID: <1189100502.390665.216830@o80g2000hse.googlegroups.com> On Sep 6, 6:44 pm, Gabriel Genellina wrote: > On 6 sep, 13:13, Samuel wrote: > > > On Sep 6, 5:44 pm, Gabriel Genellina wrote: > > > They should import the package as any other > > > client code, without doing any import tricks nor playing with > > > sys.path. > > > Why does it matter whether I install it in sys.path or whether > > sys.path is modified? What's the difference? > > Because it's more simple, less error prone, easier to test, more > efficient... > > > What I am doing is I ship two modules in one tarball with my software. > > The software is only unpacked and ran. It has to work without > > installation. > > That's fine, and a good requirement. Place start2.py inside the > container directory, and your package beneath it. Then you don't have > to modify sys.path to find the package - "import packagename" just > works. And it still works if the user installs the package (into site- > packages, by example). > > start1.py > start2.py > packagename/ > |-- Obj.py > |-- __init__.py > |-- foo/ > |-- FooTest.py > `-- __init__.py > > Packages are... well, packages, boxes. Don't try to import a module > inside a package as it were a standalone module But the start2.py script *is* part of the library. It should be in the package. However, I just found that Python 2.5 introduces relative imports. This sounds like an attempt to remedy the situation. -Samuel From grante at visi.com Wed Sep 12 19:41:20 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 12 Sep 2007 23:41:20 -0000 Subject: I want py2exe not to create library.zip References: <_tmdna-0DrGsxXXbnZ2dnUVZ8sjinZ2d@pipex.net> Message-ID: <13egu90sgb71dd5@corp.supernews.com> On 2007-09-12, Rob Williscroft wrote: > On Wed, 12 Sep 2007 22:09:30 +0200, Laszlo Nagy wrote: > >> Hi, >> >> I want py2exe not to create library.zip. My reason is that the installed >> program will be a self updating program, and it must be able to download >> changes (newer python source files) from the server. So the files should >> not be in library.zip. I tried the --bundle option but apparently it can >> only be used to make the distribution __more__ bundled. > > In your setup.py, after the call to setup(), use zipfile.ZipFile > to extract the "library.zip" into a directory called "library" then > delete the .zip. Don't do that. Use the "skip_archive" option to tell it not to create the zip file. -- Grant Edwards grante Yow! Here I am in 53 at B.C. and all I want is a visi.com dill pickle!! From jwkenne at attglobal.net Thu Sep 20 20:47:57 2007 From: jwkenne at attglobal.net (John W. Kennedy) Date: Thu, 20 Sep 2007 20:47:57 -0400 Subject: The meaning of a = b in object oriented languages In-Reply-To: References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> Message-ID: <%wEIi.176$mS7.36@newsfe12.lga> Russell Wallace wrote: > Summercool wrote: >> so most or all object oriented language do assignment by reference? >> is there any object oriented language actually do assignment by >> value? I kind of remember in C++, if you do >> >> Animal a, b; >> >> a = b will actually be assignment by value. >> while in Java, Python, and Ruby, there are all assignment by >> reference. ("set by reference") >> >> Is that the case: if a is an object, then b = a is only copying the >> reference? > > Yes, your understanding is exactly correct; C++ will assign by value > unless you explicitly use pointers, but the other languages will assign > by reference (except for primitive types). Ada also assigns by value absent explicit use of access variables (similar to pointers or references). The question, in fact, is meaningless. Java has a certain defined behavior. C++ has a certain defined behavior. Smalltalk has a certain defined behavior. LISP has a certain defined behavior. Ada has a certain defined behavior. Object-oriented languages as a class do not. -- John W. Kennedy "The poor have sometimes objected to being governed badly; the rich have always objected to being governed at all." -- G. K. Chesterton. "The Man Who Was Thursday" From garyjefferson123 at gmail.com Wed Sep 12 14:17:51 2007 From: garyjefferson123 at gmail.com (garyjefferson123 at gmail.com) Date: Wed, 12 Sep 2007 18:17:51 -0000 Subject: customizing a logging logger In-Reply-To: <1189615607.631091.214240@o80g2000hse.googlegroups.com> References: <1187412814.493872.325190@j4g2000prf.googlegroups.com> <1189527296.426004.17600@19g2000hsx.googlegroups.com> <1189615607.631091.214240@o80g2000hse.googlegroups.com> Message-ID: <1189621071.960166.30490@22g2000hsm.googlegroups.com> On Sep 12, 10:46 am, Vinay Sajip wrote: > On 11 Sep, 17:14, garyjefferson... at gmail.com wrote: > > > What is the best way to do this, so that I don't have to manually put > > the self.ctx in the log string in hundreds of different places? > > Another way is to generate your log messages via a factory method > which prepends the context: you can do this via a mixin, too. > > def log_message(self, msg): > return "%s: %s" % (self.ctx, msg) > > Note also that in recent versions, an optional "extra" parameter can > be used, to pass info into the LogRecord. > > Seehttp://mail.python.org/pipermail/patches/2007-January/021535.html > which may be of some help - it's a similar use case. > > Best regards, > > Vinay Sajip The email thread you pointed to was very informative, especially since I was about to go down the road of creating one logger per context (eek!). Whichever method I choose, I am particularly concerned with the following aspect: I like to use the "logger.debug("msg %s %s", s1, s2)" format, as I understand that when the logging for this log level is turned off, we don't have to do the potentially expensive string building that a '%' operator would imply. It seems like using something other than a literal string in the message is the way to go, since I assume that its __repr__() won't get called unless the logger is actually going to log a message for it. Is that right? Are any of the other methods likely to provide as-good or better performance? thanks, Gary From basilisk96 at gmail.com Thu Sep 6 21:57:21 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Fri, 07 Sep 2007 01:57:21 -0000 Subject: interesting puzzle......try this you will be rewarded... In-Reply-To: References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> <46e04138$0$16377$88260bb3@free.teranews.com> Message-ID: <1189130241.529344.52950@57g2000hsv.googlegroups.com> I got to 14 :) It's rather silly. I remember seeing a more elaborate puzzle that involved coding, cryptography knowledge, etc. to get through it. But what was the link, I forget now... From deets at nospam.web.de Wed Sep 5 06:22:04 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Sep 2007 12:22:04 +0200 Subject: creating really big lists References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> <87ejhd2zzt.fsf@rudin.co.uk> Message-ID: <5k7eacF2g23sU2@mid.uni-berlin.de> Paul Rudin wrote: > Dr Mephesto writes: > >> Hi! >> >> I would like to create a pretty big list of lists; a list 3,000,000 >> long, each entry containing 5 empty lists. My application will append >> data each of the 5 sublists, so they will be of varying lengths (so no >> arrays!). >> >> Does anyone know the most efficient way to do this? I have tried: >> >> list = [[[],[],[],[],[]] for _ in xrange(3000000)] >> >> but its not soooo fast. Is there a way to do this without looping? > > You can do: > > [[[],[],[],[],[]]] * 3000000 > > although I don't know if it performs any better than what you already > have. You are aware that this is hugely different, because the nested lists are references, not new instances? Thus the outcome is most probably (given the gazillion of times people stumbled over this) not the desired one... Diez From Scott.Daniels at Acm.Org Fri Sep 21 22:17:36 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 21 Sep 2007 19:17:36 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190415741.380795.259050@y42g2000hsy.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> Message-ID: <13f8unjjeqs5p97@corp.supernews.com> Cristian wrote: > On Sep 21, 3:44 pm, Ron Adam wrote: > >> I think key may be to discuss names and name binding with your friend. Here's an idea: import math def sin_integral(start, finish, dx): total = 0.0 y0 = math.sin(start) for n in range(1, 1 + int((finish - start) / float(dx))): y1 = math.sin(start + n * dx) total += (y0 + y1) y0 = y1 return total / 2. * dx def cos_integral(start, finish, dx): total = 0.0 y0 = math.sin(start) for n in range(1, 1 + int((finish - start) / float(dx))): y1 = math.cos(start + n * dx) total += (y0 + y1) y0 = y1 return total / 2. * dx generalize and separate the integration technique from the function it integrates. From mail at microcorp.co.za Sat Sep 1 03:09:29 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 1 Sep 2007 09:09:29 +0200 Subject: Let's Unite Against Jews and Mongrels! References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com><1188300284.507909.126770@57g2000hsv.googlegroups.com><46D40BFE.2020301@comcast.net><023fd3dhtmb5j0hl2uvdc4f25d5s6vogkp@4ax.com> <46d81508$0$4536$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <01f201c7ec71$4af861c0$03000080@hendrik> "Wildemar Wildenburger" wrote: > Barry OGrady wrote: > > He has some wrong ideas. The blacks are victims of the jews as well. > > > > And Jews are the victims of "Christians". And Christians are the victims > of "Muslims". > > Anybody not a victim of anyone else, please raise your hand! Everybody seems to have missed the really funny part of the original post - He wrote something like "our skin is our uniform", and he was going to use this to differentiate himself from Jews and Blacks. He must have been referring to his foreskin... - Hendrik From christophertidy at hotmail.com Mon Sep 3 04:48:19 2007 From: christophertidy at hotmail.com (christophertidy at hotmail.com) Date: Mon, 03 Sep 2007 08:48:19 -0000 Subject: TypeError: 'module object is not callable' Message-ID: <1188809299.316203.85930@22g2000hsm.googlegroups.com> Hi I am new to Python and have recieved this error message when trying to instantiate an object from a class from another file within the same directory and wondered what I have done wrong. I have a Step.py class: class Step(object) def __init__(self, sName): "Initialise a new Step instance" self.sName = sName self.depSteps = [] self.remDepSteps = [] self.isCompleted = 0 Then I have created a new file within the same directory called main.py: import Step a = Step("magn") The following however generates the error Traceback (most recent call last): File "main.py", line 3, in ? a = Step("magn") TypeError: 'module' object is not callable If anyone could help point me in the right direction, how to fix this problem it would be much appreciated. Chris From lew at lewscanon.com Tue Sep 18 18:02:59 2007 From: lew at lewscanon.com (Lew) Date: Tue, 18 Sep 2007 18:02:59 -0400 Subject: The meaning of a = b in object oriented languages In-Reply-To: <1190098656.030658.66380@57g2000hsv.googlegroups.com> References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> <1190098656.030658.66380@57g2000hsv.googlegroups.com> Message-ID: <_4OdnQm5joyO1m3bnZ2dnUVZ_tuonZ2d@comcast.com> Summercool wrote: > when a writing or a book reads "a is a Hash object; a is an Array > object; or a is an Animal object" it is just a short form to say that > "a is a reference to that object." > > b = a means "whatever a is referencing to, now b is referencing it > too". > > so that's why a[1] = "foobar" will change what b will display, but > a = "foobar" will not change what b will display. You can't do both in Java. Is a an array or a String? If a is a String and b is an array, then neither `a = b' nor `b = a' will compile in Java. Java is a strongly-typed, compiled language which means it does more static type checking and thus would reject treating a as both an array and a String. In that environment the programmer must choose one or the other. Otherwise what you say is exactly correct. > (because a[1] = "foobar" says "what is a referencing? go there and change its > content that has the index 1" and when b goes there to see it, it is > also changed.) Speaking just of Java, it's useful to distinguish a variable from an object (instance). As you point out, the variable represents a reference to the instance. The variable has a compile-time type in Java, which may be different from the run-time type of the object, albeit compatible. C++ is similar in this respect. Python and Ruby are more, shall we say, flexible in their type systems. Both jet liners and hang gliders have their uses, both are flight, and neither is really suitable for the other's purpose. -- Lew From lolu999 at gmail.com Mon Sep 10 19:39:41 2007 From: lolu999 at gmail.com (a.m.) Date: Mon, 10 Sep 2007 16:39:41 -0700 Subject: question on python syntax Message-ID: <1189467581.200075.236120@g4g2000hsf.googlegroups.com> If I type this in shell $ ./yourfile.py 12:34 PM & What does '$', '.', '/' and '& means in this succession? Note: 12:34 PM is a argument to the yourfile.py. From gagsl-py2 at yahoo.com.ar Fri Sep 28 22:52:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Sep 2007 23:52:24 -0300 Subject: Can I overload the compare (cmp()) function for a Lists ([]) index function? References: <1191000652.430036.288400@y42g2000hsy.googlegroups.com> <1191001014.951696.285800@50g2000hsm.googlegroups.com> Message-ID: En Fri, 28 Sep 2007 14:36:54 -0300, xkenneth escribi?: > On Sep 28, 12:30 pm, xkenneth wrote: >> Looking to do something similair. I'm working with alot of timestamps >> and if they're within a couple seconds I need them to be indexed and >> removed from a list. >> Is there any possible way to index with a custom cmp() function? The comparison is made by the list elements themselves (using their __eq__ or __cmp__), not by the index method nor the list object. So you should modify __cmp__ for all your timestamps (datetime.datetime, I presume?), but that's not very convenient. A workaround is to wrap the object you are searching into a new, different class - since the list items won't know how to compare to it, Python will try reversing the operands. datetime objects are a bit special in this behavior: they refuse to compare to anything else unless the other object has a `timetuple` attribute (see note (4)) import datetime class datetime_tol(object): timetuple=None # unused, just to trigger the reverse comparison to datetime objects default_tolerance = datetime.timedelta(0, 10) def __init__(self, dt, tolerance=None): if tolerance is None: tolerance = self.default_tolerance self.dt = dt self.tolerance = tolerance def __cmp__(self, other): tolerance = self.tolerance if isinstance(other, datetime_tol): tolerance = min(tolerance, other.tolerance) other = other.dt if not isinstance(other, datetime.datetime): return cmp(self.dt, other) delta = self.dt-other return -1 if delta<-tolerance else 1 if delta>tolerance else 0 def index_tol(dtlist, dt, tolerance=None): return dtlist.index(datetime_tol(dt, tolerance)) d1 = datetime.datetime(2007, 7, 18, 9, 20, 0) d2 = datetime.datetime(2007, 7, 18, 9, 30, 25) d3 = datetime.datetime(2007, 7, 18, 9, 30, 30) d4 = datetime.datetime(2007, 7, 18, 9, 30, 35) d5 = datetime.datetime(2007, 7, 18, 9, 40, 0) L = [d1,d2,d3,d4,d5] assert d3 in L assert L.index(d3)==2 assert L.index(datetime_tol(d3))==1 # using 10sec tolerance assert index_tol(L, d3)==1 assert index_tol(L, datetime.datetime(2007, 7, 18, 9, 43, 20), datetime.timedelta(0, 5*60))==4 # 5 minutes tolerance -- Gabriel Genellina From bbxx789_05ss at yahoo.com Fri Sep 21 03:50:21 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 21 Sep 2007 00:50:21 -0700 Subject: subprocess: returncode v. poll() In-Reply-To: References: <1190315820.532320.26570@22g2000hsm.googlegroups.com> <1190316312.929039.85670@o80g2000hse.googlegroups.com> <1190316490.165848.248300@w3g2000hsg.googlegroups.com> Message-ID: <1190361021.103869.210240@r29g2000hsg.googlegroups.com> On Sep 20, 3:24 pm, David wrote: > On 9/20/07, 7stud wrote: > > > > > On Sep 20, 1:25 pm, 7stud wrote: > > > On Sep 20, 1:17 pm, 7stud wrote: > > > > > Hi, > > > > > What is the difference between: > > > > > 1) getting the returncode directly from the subprocess object > > > > 2) calling poll() on the subprocess object? > > > > > Here is an example: > > > > > import subprocess > > > > > p = subprocess.Popen("ls", stdout=subprocess.PIPE) > > > > print p.returncode > > > > print p.poll() > > > > print > > > > > print p.stdout.read()[:5] > > > > print > > > > > print p.returncode > > > > print p.poll() > > > > print p.returncode > > > > > --output:-- > > > > None > > > > None > > > > > 10tes > > > > > None > > > > 0 > > > > 0 > > > > Hmm....after a little more testing, I don't think returncode > > > dynamically updates: > > > > import subprocess > > > import time > > > > p = subprocess.Popen("ls", stdout=subprocess.PIPE) > > > > print p.returncode > > > time.sleep(5) > > > print p.returncode > > > time.sleep(2) > > > print p.returncode > > > > print p.stdout.read()[:5] > > > print p.returncode > > > > --output:-- > > > None > > > None > > > None > > > 10tes > > > None > > > ...but then when is p.returncode set? And what good is it? > > AFAICT p.returncode is only set by Popen methods. It doesn't > automatically get set by the OS internals that manage the actual > process. > > One place where it is useful is when using Popen's communicate() > method, which returns (stdout,stderr), but not the return code. Also > it lets you call poll() but not have to save poll()'s return value. I didn't understand your post when I first read it, but after looking at my output again, and rereading your post, I get it now. In case someone else doesn't understand it: returncode is not set by the child process--ever. return code starts off with a default value of None, and it remains None until you call a method in the subprocess module, like poll() or wait(). Those methods set and then return returncode. As a result, if you want to know what the status of the child process is, you have to call either poll() or wait(). From python at rcn.com Tue Sep 4 21:39:50 2007 From: python at rcn.com (Raymond Hettinger) Date: Tue, 04 Sep 2007 18:39:50 -0700 Subject: Does shuffle() produce uniform result ? In-Reply-To: References: Message-ID: <1188956390.192897.10640@g4g2000hsf.googlegroups.com> On Aug 24, 12:38 am, tooru honda wrote: > 1. Does shuffle() produce uniform result ? If you're worried about this microscopic bias (on the order of 2**-53), then shuffle more than once. That will distribute the bias more evenly: def super_shuffle(sequence): for i in range(10): shuffle(sequence) Raymond Hettinger From hat at se-162.se.wtb.tue.nl Wed Sep 19 08:37:47 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 19 Sep 2007 14:37:47 +0200 Subject: cannot create my own dict Message-ID: Hello all, This morning I tried to create my own read-only dictionary, and failed miserably. I don't understand why, can somebody enlighten me? Below is a brute-force experiment that cannot deal with "x in obj", plz read the explanation below the code: -------------------------------- class myowndict(object): def __init__(self, mydict): self.mydict = mydict # Below is produced with # print '\n'.join([' self.%s = self.mydict.%s' % (v,v) # for v in dir(dict)]) # commented-out functions done by hand # #self.__class__ = self.mydict.__class__ self.__cmp__ = self.mydict.__cmp__ self.__contains__ = self.mydict.__contains__ self.__delattr__ = self.mydict.__delattr__ self.__delitem__ = self.mydict.__delitem__ #self.__doc__ = self.mydict.__doc__ self.__eq__ = self.mydict.__eq__ self.__ge__ = self.mydict.__ge__ self.__getattribute__ = self.mydict.__getattribute__ self.__getitem__ = self.mydict.__getitem__ self.__gt__ = self.mydict.__gt__ self.__hash__ = self.mydict.__hash__ #self.__init__ = self.mydict.__init__ self.__iter__ = self.mydict.__iter__ self.__le__ = self.mydict.__le__ self.__len__ = self.mydict.__len__ self.__lt__ = self.mydict.__lt__ self.__ne__ = self.mydict.__ne__ #self.__new__ = self.mydict.__new__ self.__reduce__ = self.mydict.__reduce__ self.__reduce_ex__ = self.mydict.__reduce_ex__ self.__repr__ = self.mydict.__repr__ self.__setattr__ = self.mydict.__setattr__ self.__setitem__ = self.mydict.__setitem__ self.__str__ = self.mydict.__str__ self.clear = self.mydict.clear self.copy = self.mydict.copy self.fromkeys = self.mydict.fromkeys self.get = self.mydict.get self.has_key = self.mydict.has_key self.items = self.mydict.items self.iteritems = self.mydict.iteritems self.iterkeys = self.mydict.iterkeys self.itervalues = self.mydict.itervalues self.keys = self.mydict.keys self.pop = self.mydict.pop self.popitem = self.mydict.popitem self.setdefault = self.mydict.setdefault self.update = self.mydict.update self.values = self.mydict.values # end of __init__ if __name__ == '__main__': fd = myowndict({1:10}) print 1 in fd # FAILS! (with "TypeError: iterable argument required") -------------------------------- I wanted to make my own dictionary. However, a simple element test failed (after implementing various __*__ functions), and I cannot figure out why. The above code is a brute force attempt, where I forward all methods (except __class__, __doc__, __init__, and __new__) to my local 'mydict' object. IT STILL FAILS. So if copying all methods of a native dictionary is not enough, what should I do to make my class work as a dictionary WITHOUT deriving from dict (which will obviously work). Sincerely, Albert From Praveen.Shilavantar at in.tesco.com Thu Sep 20 06:35:19 2007 From: Praveen.Shilavantar at in.tesco.com (Shilavantar, Praveen) Date: Thu, 20 Sep 2007 16:05:19 +0530 Subject: AIX - Python - db2.py Message-ID: <6702B04331BCF8408F9FE92AFC5349B7E442@INBLRCLUMS0201.in.tesco.org> Hi, I am getting the following error while installing PyDB2 package on AIX machine. So can anybody give me the requirements list and a procedure to install PyDb2 package on AIX. xn75 at ti057:/home/xn75/PyDB2-1.1.0> python setup.py install Your DB2 root is: WARNING: it seems that you did not install 'Application Development Kit'. Compilation may fail. running install running build running build_py not copying DB2.py (output up-to-date) running build_ext building '_db2' extension cc_r -O -Iinclude -I/usr/local/include/python2.1 -c _db2_module.c -o build/temp.aix-5.3-2.1/_db2_module.o "_db2_module.c", line 24.10: 1506-296 (S) #include file not found. "_db2_module.c", line 25.10: 1506-296 (S) #include file not found. "_db2_module.c", line 47.9: 1506-046 (S) Syntax error. "_db2_module.c", line 52.11: 1506-045 (S) Undeclared identifier SQL_BIGINT. "_db2_module.c", line 52.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 53.11: 1506-045 (S) Undeclared identifier SQL_BINARY. "_db2_module.c", line 53.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 54.11: 1506-045 (S) Undeclared identifier SQL_BLOB. "_db2_module.c", line 54.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 55.11: 1506-045 (S) Undeclared identifier SQL_BLOB_LOCATOR. "_db2_module.c", line 55.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 56.11: 1506-045 (S) Undeclared identifier SQL_CHAR. "_db2_module.c", line 56.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 57.11: 1506-045 (S) Undeclared identifier SQL_CLOB. "_db2_module.c", line 57.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 58.11: 1506-045 (S) Undeclared identifier SQL_CLOB_LOCATOR. "_db2_module.c", line 58.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 59.11: 1506-045 (S) Undeclared identifier SQL_TYPE_DATE. "_db2_module.c", line 59.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 60.11: 1506-045 (S) Undeclared identifier SQL_DBCLOB. "_db2_module.c", line 60.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 61.11: 1506-045 (S) Undeclared identifier SQL_DBCLOB_LOCATOR. "_db2_module.c", line 61.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 62.11: 1506-045 (S) Undeclared identifier SQL_DECIMAL. "_db2_module.c", line 62.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 63.11: 1506-045 (S) Undeclared identifier SQL_DOUBLE. "_db2_module.c", line 63.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 64.11: 1506-045 (S) Undeclared identifier SQL_FLOAT. "_db2_module.c", line 64.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 65.11: 1506-045 (S) Undeclared identifier SQL_GRAPHIC. "_db2_module.c", line 65.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 66.11: 1506-045 (S) Undeclared identifier SQL_INTEGER. "_db2_module.c", line 66.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 67.11: 1506-045 (S) Undeclared identifier SQL_LONGVARCHAR. "_db2_module.c", line 67.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 68.11: 1506-045 (S) Undeclared identifier SQL_LONGVARBINARY. "_db2_module.c", line 68.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 69.11: 1506-045 (S) Undeclared identifier SQL_LONGVARGRAPHIC. "_db2_module.c", line 69.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 70.11: 1506-045 (S) Undeclared identifier SQL_NUMERIC. "_db2_module.c", line 70.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 71.11: 1506-045 (S) Undeclared identifier SQL_REAL. "_db2_module.c", line 71.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 72.11: 1506-045 (S) Undeclared identifier SQL_SMALLINT. "_db2_module.c", line 72.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 73.11: 1506-045 (S) Undeclared identifier SQL_TYPE_TIME. "_db2_module.c", line 73.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 74.11: 1506-045 (S) Undeclared identifier SQL_TYPE_TIMESTAMP. "_db2_module.c", line 74.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 75.11: 1506-045 (S) Undeclared identifier SQL_VARCHAR. "_db2_module.c", line 75.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 76.11: 1506-045 (S) Undeclared identifier SQL_VARBINARY. "_db2_module.c", line 76.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 77.11: 1506-045 (S) Undeclared identifier SQL_VARGRAPHIC. "_db2_module.c", line 77.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 78.11: 1506-045 (S) Undeclared identifier SQL_DATALINK. "_db2_module.c", line 78.33: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 79.14: 1506-026 (S) Number of initializers cannot be greater than the number of aggregate members. "_db2_module.c", line 82.7: 1506-282 (S) The type of the parameters must be specified in a prototype. "_db2_module.c", line 90.11: 1506-045 (S) Undeclared identifier SQL_SUCCESS. "_db2_module.c", line 91.11: 1506-045 (S) Undeclared identifier SQL_SUCCESS_WITH_INFO. "_db2_module.c", line 92.11: 1506-045 (S) Undeclared identifier SQL_ERROR. "_db2_module.c", line 93.11: 1506-045 (S) Undeclared identifier SQL_INVALID_HANDLE. "_db2_module.c", line 94.11: 1506-045 (S) Undeclared identifier SQL_NO_DATA_FOUND. "_db2_module.c", line 95.11: 1506-045 (S) Undeclared identifier SQL_STILL_EXECUTING. "_db2_module.c", line 96.11: 1506-045 (S) Undeclared identifier SQL_NEED_DATA. "_db2_module.c", line 100.27: 1506-275 (S) Unexpected text SQLRETURN encountered. "_db2_module.c", line 150.9: 1506-046 (S) Syntax error. "_db2_module.c", line 154.33: 1506-045 (S) Undeclared identifier SQL_MAX_DSN_LENGTH. "_db2_module.c", line 154.33: 1506-195 (S) Integral constant expression with a value greater than zero is required. "_db2_module.c", line 177.19: 1506-282 (S) The type of the parameters must be specified in a prototype. "_db2_module.c", line 178.12: 1506-282 (S) The type of the parameters must be specified in a prototype. "_db2_module.c", line 179.12: 1506-282 (S) The type of the parameters must be specified in a prototype. "_db2_module.c", line 212.9: 1506-046 (S) Syntax error. "_db2_module.c", line 221.9: 1506-046 (S) Syntax error. "_db2_module.c", line 237.9: 1506-046 (S) Syntax error. "_db2_module.c", line 256.9: 1506-046 (S) Syntax error. "_db2_module.c", line 305.39: 1506-046 (S) Syntax error. "_db2_module.c", line 327.25: 1506-275 (S) Unexpected text rc encountered. "_db2_module.c", line 329.14: 1506-045 (S) Undeclared identifier rc. "_db2_module.c", line 343.25: 1506-275 (S) Unexpected text rc encountered. "_db2_module.c", line 345.14: 1506-045 (S) Undeclared identifier rc. "_db2_module.c", line 398.35: 1506-022 (S) "hstmt" is not a member of "struct {...}". "_db2_module.c", line 398.42: 1506-045 (S) Undeclared identifier SQL_HANDLE_STMT. "_db2_module.c", line 434.35: 1506-022 (S) "hstmt" is not a member of "struct {...}". "_db2_module.c", line 434.42: 1506-045 (S) Undeclared identifier SQL_HANDLE_STMT. "_db2_module.c", line 455.35: 1506-022 (S) "hdbc" is not a member of "struct {...}". "_db2_module.c", line 455.41: 1506-045 (S) Undeclared identifier SQL_HANDLE_DBC. "_db2_module.c", line 480.27: 1506-275 (S) Unexpected text handle encountered. "_db2_module.c", line 480.47: 1506-275 (S) Unexpected text handleType encountered. "_db2_module.c", line 482.25: 1506-277 (S) Syntax error: possible missing ';' or ','? "_db2_module.c", line 482.9: 1506-045 (S) Undeclared identifier SQLCHAR. "_db2_module.c", line 494.9: 1506-045 (S) Undeclared identifier SQLINTEGER. "_db2_module.c", line 495.9: 1506-045 (S) Undeclared identifier SQLRETURN. "_db2_module.c", line 502.30: 1506-276 (S) Syntax error: possible missing ')'? "_db2_module.c", line 500.17: 1506-045 (S) Undeclared identifier handleType. "_db2_module.c", line 501.17: 1506-045 (S) Undeclared identifier handle. "_db2_module.c", line 499.9: 1506-045 (S) Undeclared identifier rc. "_db2_module.c", line 507.18: 1506-045 (S) Undeclared identifier msgTextOutLen. "_db2_module.c", line 513.52: 1506-045 (S) Undeclared identifier sqlState. "_db2_module.c", line 515.46: 1506-045 (S) Undeclared identifier nativeErr. "_db2_module.c", line 517.52: 1506-045 (S) Undeclared identifier msgText. error: command 'cc_r' failed with exit status 1 xn75 at ti057:/home/xn75/PyDB2-1.1.0> Regards, - Praveen V S ---- Disclaimer ---- This is a confidential email. Tesco may monitor and record all emails. The views expressed in this email are those of the sender and not Tesco. Tesco Stores Limited Company Number: 519500 Registered in England Registered Office: Tesco House, Delamare Road, Cheshunt, Hertfordshire EN8 9SL VAT Registration Number: GB 220 4302 31 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ratchetgrid at googlemail.com Thu Sep 27 12:15:42 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Thu, 27 Sep 2007 17:15:42 +0100 Subject: Pb with an AttributeError In-Reply-To: References: Message-ID: <676224240709270915x537a6426h1512cbddccb5c68f@mail.gmail.com> Hi, I m not sure what your trying to do, but this is where your problem is: string1 is not a string it is actually a dict because of your eval. When you call string1["param"] inside the string.split() it is returning a dictionary and not a string.... 'param': {'key': 'SP<136>=', 'value': ['SD:<0> ']} since {'key': 'SP<136>=', 'value': ['SD:<0> ']} is inside curly brackets it is a dictionary. I still dont get what your trying to have as your final result, but hope this helps. Thanks Nathan On 27/09/2007, Eric BOUVIER wrote: > > > > Hello, > > First, sorry for my english. > > I've just been assigned a project written in Python which contains bug(s). > I've never programmed in Python, but I've read the code > and understood basically what the different source codes do. > > I've traced the code and found where the problem is but I don't > know how to solve the problem. > > Here it is : > > I've got a string issued from a CSV file : > string1 = eval(line[4]) > print " * string1 = (", string1 ,") \n" > => * string1 = ( {'header': 'X-Score', 'param': {'key': 'SP<136>=', > 'value': ['SD:<0> ']} ) > > Then, there is a split with the equal : > TheParts = string.split(string1["param"], "=") > print " * TheParts = (", TheParts ,") \n" > > But, running the program returns : > > Traceback (most recent call last): > File "C:\test\helper.py", line 136, in Action_handler > Score_eval(line, OutputFile_SP, This_Host) > File "C:\test\helper.py", line 66, in Score_eval > TheParts = string.split(string1["param"], "=") > File "C:\ActiveState\Python25\lib\string.py", line 290, > in split > return s.split(sep, maxsplit) > AttributeError: 'dict' object has no attribute 'split' !?! > > I've found that it works when I put directly the string in the split > expression : > > TheParts = string.split(" {'key': 'ESP<136>=', 'value': ['SHA:<0> ']} ", > "=") > => * TheParts = ["{'key': 'ESP<136>", "', 'value': ['SHA:<0> ']}"] > > But the code isn't dynamic anymore ! > I think it's a problem with the type, but the different syntax I've tried > didn't work. > Is somebody could help me ? > > Thank you > -- > http://mail.python.org/mailman/listinfo/python-list > From ldo at geek-central.gen.new_zealand Wed Sep 19 05:45:11 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 19 Sep 2007 21:45:11 +1200 Subject: How can I know how much to read from a subprocess References: <1190070896.332844.23080@22g2000hsm.googlegroups.com> Message-ID: In message <1190070896.332844.23080 at 22g2000hsm.googlegroups.com>, spam.noam at gmail.com wrote: > ... how can I know if the process wrote something to its > output, and how much it wrote? Others have mentioned using one-byte reads. To tell if something is available for reading, use select . From semanticist at gmail.com Tue Sep 25 11:48:23 2007 From: semanticist at gmail.com (Miles) Date: Tue, 25 Sep 2007 11:48:23 -0400 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: <1190733242.746403.264650@o80g2000hse.googlegroups.com> References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> <1190733242.746403.264650@o80g2000hse.googlegroups.com> Message-ID: On 9/25/07, Paul McGuire wrote: > On Sep 24, 11:23 pm, Gabriel Genellina wrote: > > py> print re.sub(r"<(\w+)([^>]*)>", r"<\1\2 />", source) > > And let's hope the OP doesn't have to parse anything truly nasty like: > > esolang:language> Or something mildly nasty, like -Miles From robin at reportlab.com Fri Sep 28 07:20:39 2007 From: robin at reportlab.com (Robin Becker) Date: Fri, 28 Sep 2007 12:20:39 +0100 Subject: recipient validation with smtplib Message-ID: <46FCE387.9070601@chamonix.reportlab.co.uk> Is there a way to use smtplib to get recipient validation. I can use smtplib quite happily to send emails using the locahost's sendmail, but sendmail is just fire and forget, so some bad addresses eg idiot at www.dingo.zzz don't cause any error in the sending application. I know some smtp setups do enforce recipient validation, but it doesn't seem terribly easy to do this with sendmail. I wondered if there were some way to do this in python? -- Robin Becker From uymqlp502 at sneakemail.com Sat Sep 1 01:40:20 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Fri, 31 Aug 2007 22:40:20 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <1188523589.736146.263510@l22g2000prc.googlegroups.com> <1i3o9kr.2gmni61g62moaN%aleax@mac.com> <7xwsvcc9yz.fsf@ruckus.brouhaha.com> <1i3p8lm.19738kn1q0gkouN%aleax@mac.com> <1188587846.687895.69240@q5g2000prf.googlegroups.com> <38rmq4-cq.ln1@strongwill.g2ctech> Message-ID: <1188625220.930546.217860@g4g2000hsf.googlegroups.com> On Aug 31, 6:45 pm, Steve Holden > We probably need to distinguish between "mission-critical", where a > program has to work reliably for an organization to meet its goals, and > "safety-critical" where people die or get hurt if the program misbehaves. The term "mission critical" itself can have a wide range of connotations. If a software failure would force a military pilot to abort his mission and hobble back home with a partially disabled aircraft, that's what I think of as "mission critical" software. If Google needs reliable software on its servers to maintain its revenue stream, that's another kind of "mission critical" software, but the criticality is certainly less immediate in that case. In the first case, the software glitch definitely causes mission failure. In the Google case, the software problems *may* ultimately cause mission failure, but probably only if nothing is done for quite some time to rectify the situation. If that is the case, then the software itself is not the critical factor unless it cannot be corrected and made to function properly in a reasonable amount of time. From george.sakkis at gmail.com Sun Sep 30 12:48:10 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 30 Sep 2007 16:48:10 -0000 Subject: Can you please give me some advice? In-Reply-To: References: Message-ID: <1191170890.744290.27840@19g2000hsx.googlegroups.com> On Sep 30, 6:22 am, Byung-Hee HWANG wrote: > Hi there, > > What is different between Ruby and Python? I am wondering what language > is really mine for work. Somebody tell me Ruby is clean or Python is > really easy! Anyway I will really make decision today what I have to > study from now on. What I make the decision is more difficult than to > know why I have to learn English. Yeah I do not like to learn English > because it is just very painful.. > > Can you please give me some advice? > > Byung-Hee "Dive into Python" has been translated in Chinese: http://www.woodpecker.org.cn/diveintopython/ Hope it helps, George From zzbbaadd at aol.com Fri Sep 28 13:26:34 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 10:26:34 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <5m4qc2Fbbk19U1@mid.uni-berlin.de> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> <1190997769.002795.59450@57g2000hsv.googlegroups.com> <5m4qc2Fbbk19U1@mid.uni-berlin.de> Message-ID: <1191000394.828693.285210@k79g2000hse.googlegroups.com> On Sep 28, 10:01 am, Marc 'BlackJack' Rintsch wrote: > On Fri, 28 Sep 2007 09:42:49 -0700, TheFlyingDutchman wrote: > > Which of the common languages have higher order functions and what is > > the syntax? > > C, C++, Pascal, Perl, PHP, Ruby have them. And of course the functional > languages, most notably Lisp and Scheme as you asked for common languages. > > Don't know if C#'s delegates qualify. > > Ciao, > Marc 'BlackJack' Rintsch What is the syntax of a higher order function in C, C++ and Pascal? From JS.Sokrates at googlemail.com Sun Sep 2 17:57:18 2007 From: JS.Sokrates at googlemail.com (Jonas Schneider) Date: Sun, 02 Sep 2007 14:57:18 -0700 Subject: Weird gcc errors while installing "MySQL-python" module Message-ID: <1188770238.595895.288760@r29g2000hsg.googlegroups.com> Hi guys, I?m experiencing weird error messages while installing MySQL-python with easy_install... I have no idea where the errors come from. Read the whole output at http://pastebin.com/m3859cf40 It?s really a lot... Someone got ideas? Greets Jonas From paul.nospam at rudin.co.uk Mon Sep 17 12:49:58 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 17 Sep 2007 17:49:58 +0100 Subject: How to assign a function to another function References: Message-ID: <87d4whnsnd.fsf@rudin.co.uk> Stefano Esposito writes: > Hi all > > what i'm trying to do is this: > >>>>def foo (): > ... return None > ... >>>>def bar (): > ... print "called bar" > ... >>>>def assigner (): > ... foo = bar > ... >>>>assigner() >>>>foo() > called bar >>>> > > This piece of code is not working and even trying with... > ... How can I achieve my goal? By adding the line: global foo at the beginning of the body of assigner. The assignment to foo in the body of assigner makes a local (to the function) variable called foo and assigns bar to it. From koutoo at hotmail.com Thu Sep 20 10:34:36 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Thu, 20 Sep 2007 07:34:36 -0700 Subject: Lookup values from one table to another based on a value Message-ID: <1190298876.689060.44540@d55g2000hsg.googlegroups.com> If I wanted to accomplish looking up values from one table based on a value from another table or file, how would I go about doing this in Python? Would I build a dictionary or an array? exp: Table1: Site = 103 Lane = 2 Dir = ? # Get this from Table2 Table2: Site, Lane, Direction, 103, 1, 1 103, 2, 1 103, 3, 5 103, 4, 5 Normally in Access I would just use a Dlookup and be done with it, or use a Recordset in VB. Thanks guys. Kou From cjt22 at bath.ac.uk Tue Sep 4 06:52:03 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Tue, 04 Sep 2007 03:52:03 -0700 Subject: TypeError: 'module object is not callable' In-Reply-To: References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> Message-ID: <1188903123.701882.205780@o80g2000hse.googlegroups.com> On Sep 4, 11:24 am, "Amit Khemka" wrote: > On 9/4/07, Chris.T... at jet.uk wrote: > > > Thanks guys. Changing to how Python does things has a lot of geting > > used to! > > Do any of you have any ideas on the best way to do the following > > problem: > > > Each loop I perform, I get a new list of Strings. > > I then want to print these lists as columns adjacent to each other > > starting with the first > > created list in the first column and last created list in the final > > column. > > > If you need any more information, just let me know! > > Cheers > > If I understand correctly what you may want is: > > >>> l = ['1', '2', '3', '4'] > > you can do: > > >>> print "\t".join(l) # lookup join method in stringmodule, > > assuming "\t" as the delimiter > > or, > > >>> for i in l: > > .... print i, '\t' , # note the trailing "," > > If this isnotwhat you want, post an example. > > Btw, Please post new issues in a separate thread. > > Cheers, > -- > ---- > Amit Khemka > website:www.onyomo.com > wap-site:www.owap.in I think that is very similar to what I want to do. Say I had lists a = ["1" , "2", "3"] b = ["4", "5", "6"] c = ["7", "8", "9"] Stored in another list d = [a,b,c] I want the printed output from d to be of the form: 1 4 7 2 5 8 3 6 9 >From what I am aware, there is no table module to do this. The '\t' operator looks like it can allow this, I am playing with it at the moment, although going for my lunch break now! From gagsl-py2 at yahoo.com.ar Wed Sep 26 00:00:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Sep 2007 01:00:10 -0300 Subject: Missing documentation for ElementTree? References: <496954360709251539y2511a1cbnd25c6d3a0d368d2a@mail.gmail.com> Message-ID: En Tue, 25 Sep 2007 19:39:33 -0300, Robert Dailey escribi?: > for the _ElementInterface class, there is no documentation for most of > the > members of this class such as .tail and .text. There's a brief > description > of these things on the front page of the ElementTree docs but nothing > helpful. I have no idea what Tail is vs Text and I wanted to figure this > out > myself, however I don't think I can now. Anyone know if I'm just missing > something in the documentation or if it really isn't in there? Start here: http://www.effbot.org/zone/element-index.htm -- Gabriel Genellina From zowtar at gmail.com Wed Sep 5 13:21:01 2007 From: zowtar at gmail.com (zowtar) Date: Wed, 05 Sep 2007 10:21:01 -0700 Subject: python-spidermonkey Message-ID: <1189012861.893842.87710@k79g2000hse.googlegroups.com> Guys, I am using slackware... js-spidermonkey 1.5 compiled - OK, Pyrex installed, but python-spidermonkey don't build... Screenshot: http://img406.imageshack.us/img406/562/testebp5.png what is the problem? zowtar From lasses_weil at klapptsowieso.net Thu Sep 13 15:22:41 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 13 Sep 2007 21:22:41 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <5ktfb5F5ctrvU1@mid.individual.net> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> <5ktfb5F5ctrvU1@mid.individual.net> Message-ID: <46e98e01$0$30383$9b4e6d93@newsspool4.arcor-online.net> Bjoern Schliessmann wrote: >> No, but the point being made is that it would be better IN >> THIS CASE. > > It wouldn't. IMHO, rewriting the code to two or three lines would be > better. > Well I think Charles' Point about making the equations look like the ones in the paper(s) is a pretty good one. That is a special case in that the code becomes clearer when it conformes to the standards of the domain it is referring to; it is not meant to be understood by itself but rather in conjunction with documents that motivate it. Or in short: Breaking it into n>1 lines would make it more readable but would break the connection with the form given in the papers. (Yes, of course you can refer to the eq. in a comment but believe me: if you're used to seeing a certain (form of) equation, your mind will trip over any variation. That is best avoided.) ... my 2 sents, anyway ... /W From laurent.pointal at limsi.fr Tue Sep 18 03:58:22 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 18 Sep 2007 09:58:22 +0200 Subject: The meaning of a = b in object oriented languages In-Reply-To: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> Message-ID: Summercool a ?crit : > > > The meaning of a = b in object oriented languages. > ==================================================== Oups, reading the subject I thought it was a Xah Lee post. ;-) From Dominic at PLEASEASK.co.uk Thu Sep 6 07:15:05 2007 From: Dominic at PLEASEASK.co.uk (special_dragonfly) Date: Thu, 6 Sep 2007 12:15:05 +0100 Subject: SQLite and coercing to Unicode - please help. References: <46dfcbea$0$89178$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: <46dfdd18$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> That helped immensely Steve thank you. You're right, this is my first really big project ever really, not just in Python. Just to clarify, my UPDATE statement instead of looking like this: longstring="UPDATE SecB SET currencyCode='"+Values[1]+"',issuerName='"+Values[2] "',instrName='"+Values[3]+\ "',instrShortName='"+Values[4]+"',instrType='"+Values[5]+"',secCode='"+Values[6]+\ "',SEDOL='"+Values[7]+"',Date='"+Values[8]+"',SuspendedState='"+Values[9]+\ "',bidPrice='"+Values[10]+"',offerPrice='"+Values[11]+"',midPrice='"+Values[12]+\ "',standardMarketSize='"+Values[13]+"',openOrClosed='"+Values[14]+\ "' WHERE secBoardId='"+Values[0]+"'" cursor.execute(longstring) should instead look more like this: cursor.execute('UPDATE SecB SET (?,?,?,?,?,?,?,?,?,?,?,?,?,?)',tuple(Values[1:])) ? The Elements list was from a time when it looked less pretty than it does now, where I iterated through it and didn't catch errors at all. Thank you again for your help and when it's finished and working I'll repost it online somewhere for ideas on how to optimise it slightly more! Dominic "Steve Holden" wrote in message news:mailman.143.1189076279.2658.python-list at python.org... > special_dragonfly wrote: >> Hello! >> First, the problem: the program below falls over with the following >> error: >> TypeError: coercing to Unicode: need string or buffer, NoneType found. >> and gives the following line: >> "' WHERE secBoardId='"+Values[0]+"'" >> My first thought was that Values[0] was containing nothing at all, that >> would allow a NoneType to be found, but it has data in that position of >> the list - you'll see below. >> So I thought that Values[0] was 'losing' its type somewhere, so I checked >> it just by having the program print out type(Values[0]), it says it's a >> string - also seen below. >> So given it's not a NoneType and it's a string, I don't understand why >> I'm getting the error. I tried forcing it to a particular type (I think >> that's the right word), so I put lines like: >> Values[0]=unicode(Values[0]) or >> WHERE ... ='"str(Values[0]+"'" >> but neither worked. >> I've put my code below, I'm sorry it's so long, I've commented the line >> where it's falling over. >> If it's useful, I am using Python 2.5.1, ElementTree 1.2.6 and pySQLite >> 2.3.5 >> If this is a silly mistake ( one where RTFM is a valid response, can you >> point me at the place where I can get the answer please?), otherwise any >> help is greatly appreciated as I'm out of ideas. :( >> Dominic >> > OK, the first problem is that you appear to be obsessing about Values[0] > when there doesn't appear to be any evidence that value in particular is > causing the problem. The line number being reported is simply that of the > last line in a single long statement, and the issue could be anywhere in > that statement. Sorry, you just have to know (or guess) that, it's not a > particularly admirable feature of Python. > > In point of fact it is the None values that are causing the problem: > > $ /usr/bin/python > Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) > [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> "a string"+None > Traceback (most recent call last): > File "", line 1, in > TypeError: cannot concatenate 'str' and 'NoneType' objects > >>> u"a string"+None > Traceback (most recent call last): > File "", line 1, in > TypeError: coercing to Unicode: need string or buffer, NoneType found > >>> > > The XML values you are retrieving will be Unicode strings, but you are > mixing them with plain string values, hence the (somewhat unhelpful) error > message.. > > Secondly, you are trying to construct a SQL UPDATE statement yourself, > instead of parameterising it like you did your INSERT statement. This is > also usually asking for trouble, and is vulnerable to SQL injection errors > (use Google if you don't know what they are). > > Thirdly, I'm not quite sure why you are using a list for the values, and > another one for the Elements, when it would seems to make more sense to > use a named variable for the former and just use the necessary string > literals for the latter. What's the advantage of using > > try: > branch=dom.getiterator(Elements[1]) > Values.append(branch[0].text) # currencyID > except: > Values.append(" "*3) > > when you could just as easily say > > try: > branch = dom.getiterator("currencyID") > currencyID = branch[0].text > except (..., ..., ...): # see below > currencyID = " " > > The usual shorthand for > > > (Values[0],Values[1],Values[2],Values[3],Values[4],Values[5],\ > Values[6],Values[7],Values[8],Values[9],Values[10],Values[11],\ > Values[12],Values[13],Values[14]) > > would, by the way, be > > tuple(Values) > > Note also that your INSERT statement assumes a specific ordering to the > columns, which is asking for trouble when the database goes into > production, as a DBA might re-order the fields during a reorganization or > restructuring of the data, and then your code will break. > > Finally, and almost completely irrelevant to the issue at hand, all those > "except" clauses will catch *absolutely any error* that may occur in your > code, which is almost always a bad idea, since this behavior will mask > certain errors that you really want to know about. The XML analysis code > is frankly pretty horrible, but we can address that issue once you start > to get some results. > > Sorry to bash what could well be your first significant program in Python, > but my main interest is in setting you off down the right path. It will > save time and grief in the end. Hope this has helped. > > regards > Steve > >> >> The output: >> At top of function: GBP/PLUS-ofn-GB00B12T7004 >> Values list contains: ['GBP/PLUS-ofn-GB00B12T7004', u'GBP', >> u'GB00B12T7004 ', u'All Star Minerals plc ', 'ASMO', >> 'DE', 'PLUS', u'B12T700', u' ', u'A', None, None, None, >> '000000000000000000', '0', '0'] >> >> Type of Values[0] is: >> >> The code: >> def dealwithSecBRep(text_buffer): >> # text_buffer contains a sequential string of xml >> >> Elements=['secBoardId','currencyId','issuerId','secName','secShortName','secClassId',\ >> >> 'sectorId','isin','issueDate','inheritedState','bidPrice','offerPrice','midPrice',\ >> 'standardMarketSize','openPrice','closePrice'] >> Values=[] >> dom=get_a_document(text_buffer) # this function returns an xml >> document. >> branch=dom.getiterator(Elements[0]) >> Values.append(GetUniqueId(branch[0])) # Combo of secCode and >> secBoardId >> print "At top of function:",Values[0] >> sql=cursor.execute('SELECT*FROM SecB WHERE >> secBoardId='+"'"+Values[0]+"'").fetchall() >> SQL2=sql >> flag=0 >> if len(sql)>0: >> #Prior database exists >> try: >> branch=dom.getiterator(Elements[1]) >> Values.append(branch[0].text) # currencyID >> except: >> value=GetFromDB('currencyCode',text_buffer) >> Values.append(value) >> try: >> branch=dom.getiterator(Elements[2]) >> Values.append(branch[0].text) # issuerName >> except: >> value=GetFromDB('issuerName',text_buffer) >> Values.append(value) > [other horrible code elided ...] > >> try: >> branch=dom.getiterator(Elements[15]) >> >> value=string.ljust(string.rjust(branch[0][0].text,10,"0"),18,"0") >> Values.append(branch[0].text) # Stock Close >> except: >> Values.append("0") # Stock Open >> flag=1 >> if flag==0: >> print "Values list contains:",Values,"\n" >> print "Type of Values[0] is:",type(Values[0]),"\n" >> longstring="UPDATE SecB SET >> currencyCode='"+Values[1]+"',issuerName='"+Values[2]+"',instrName='"+Values[3]+\ >> >> "',instrShortName='"+Values[4]+"',instrType='"+Values[5]+"',secCode='"+Values[6]+\ >> >> "',SEDOL='"+Values[7]+"',Date='"+Values[8]+"',SuspendedState='"+Values[9]+\ >> >> "',bidPrice='"+Values[10]+"',offerPrice='"+Values[11]+"',midPrice='"+Values[12]+\ >> >> "',standardMarketSize='"+Values[13]+"',openOrClosed='"+Values[14]+\ >> "' WHERE secBoardId='"+Values[0]+"'" # This is the >> line it falls over on. >> cursor.execute(longstring) >> connection.commit() >> currentStatus=SQL2[0][13] #current Stock Status >> if currentStatus==1: # Open >> if Values[14]!='0': # xml says open >> oldStart("",text_buffer) #5SE >> elif Values[15]!='0': # xml says closed >> oldStart("",text_buffer) >> elif Values[14]==0 and Values[15]==0: # neither openPrice nor >> closePrice exist in xml >> oldStart("",text_buffer) # just 5ER and 5IS >> else: # currently Closed >> if Values[14]!='0': #xml says open >> oldStart("",text_buffer) # 5PR >> else: #xml says closed >> oldStart("",text_buffer) # 5ER,5IS >> else: >> cursor.execute('INSERT INTO SecB VALUES >> (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',\ >> >> (Values[0],Values[1],Values[2],Values[3],Values[4],Values[5],\ >> >> Values[6],Values[7],Values[8],Values[9],Values[10],Values[11],\ >> Values[12],Values[13],Values[14])) >> connection.commit() >> if Values[14]!='0': # xml says open >> test=dom.getiterator('openPrice') >> oldStart("",text_buffer) # 5ER, 5IS >> oldStart("",text_buffer) # 5PR >> else: # xml says closed, or neither options exist. >> oldStart("",text_buffer) # 5ER, 5IS >> >> > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- > From lasses_weil at klapptsowieso.net Thu Sep 13 17:50:20 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 13 Sep 2007 23:50:20 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> <5ktfb5F5ctrvU1@mid.individual.net> <46e98e01$0$30383$9b4e6d93@newsspool4.arcor-online.net> <46e9921e$0$26251$426a74cc@news.free.fr> <46e995d1$0$16120$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <46e9b09c$0$7685$9b4e6d93@newsspool2.arcor-online.net> stef mientki wrote: > Wildemar Wildenburger wrote: >> Bruno Desthuilliers wrote: >> >>> OTHO, simple math-illeterate programmers like me will have hard time >>> maintaining such a code. >>> >> Certainly, but again: Such main people are not the intended audience. >> The code is for people that know how to read these equations. I think >> a general rule of (any form of) writing is to write with your audience >> in mind. I always do that and happily, that audience is usually naked. >> >> >> > Wouldn't Mathematica, Maple or MathCad be a far better choice ? > Well, those cost money ... Hey, why am *I* arguing here at all? This isn't my thread! Well, I guess the scientist in me felt tickled. /W From joemystery123 at gmail.com Thu Sep 20 19:52:16 2007 From: joemystery123 at gmail.com (crybaby) Date: Thu, 20 Sep 2007 16:52:16 -0700 Subject: Python Regex Question In-Reply-To: <46f2c7e8$0$21956$88260bb3@free.teranews.com> References: <1190316811.760038.145850@50g2000hsm.googlegroups.com> <46f2c7e8$0$21956$88260bb3@free.teranews.com> Message-ID: <1190332336.357719.28060@19g2000hsx.googlegroups.com> On Sep 20, 4:12 pm, Tobiah wrote: > joemystery... at gmail.com wrote: > > I need to extract the number on each > > i.e 49.950 from the following: > > >  49.950  > > > The actual number between:  49.950  can be any number of > > digits before decimal and after decimal. > > >  ######.####  > > > How can I just extract the real/integer number using regex? > > '[0-9]*\.[0-9]*' > > -- > Posted via a free Usenet account fromhttp://www.teranews.com I am trying to use BeautifulSoup: soup = BeautifulSoup(page) td_tags = soup.findAll('td') i=0 for td in td_tags: i = i+1 print "td: ", td # re.search('[0-9]*\.[0-9]*', td) price = re.compile('[0-9]*\.[0-9]*').search(td) I am getting an error: price= re.compile('[0-9]*\.[0-9]*').search(td) TypeError: expected string or buffer Does beautiful soup returns array of objects? If so, how do I pass "td" instance as string to re.search? What is the different between re.search vs re.compile().search? From nick at craig-wood.com Wed Sep 26 05:30:17 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 26 Sep 2007 04:30:17 -0500 Subject: Google and Python References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> <7xejgr68pm.fsf@ruckus.brouhaha.com> <7xps07w5g3.fsf@ruckus.brouhaha.com> Message-ID: Hendrik van Rooyen wrote: > "Paul Rubin" wrote: > > > "Hendrik van Rooyen" writes: > > > What is the advantage of passing the open file rather than just the > > > fully qualified file name and having the other process open the > > > file itself? > > > > The idea is that the application is a web server. The socket listener > > accepts connections and hands them off to other processes. That is, > > the file descriptors are handles on network connections that were > > opened by the remote client, not disk files that can be opened > > locally. > > Ok got it - so instead of starting a thread, as is current practice, you fork > a process (possibly on another machine) and "hand over" the client. It is trivial to pass a socket to a new thread or a forked child - you don't need this mechanism for that. It doesn't work on different machines though - it has to be on the same machine. It is for passing a socket to an already running process. For example you could implement fast cgi like this. Fast cgi is a process which runs continuously which avoids startup times and can track more state more easily. Instead of the client talking to the web server and the web server taking to the fast cgi process which is what normally happens, the web server could first writes some headers on the socket then pass the socket on to the fast cgi process directly, cutting out a whole lot of copying of the data. > Can't you do this by passing the client's IP addy and the negotiated socket > on the clients machine? No, because the state of the open TCP connection is kept in the kernel not in the user process. > Or is this where the heavy lifting comes in? - "spoofing" the original local IP > addy on the new server? - seems you would have to route to a local machine > based not on IP addy only, but on (IP,socket) tuples. - This might work if > you have only one entry point to the local LAN, but would be harder to do > if there are two points of entry, and packets could hit from > outside on either.. It is all done in the kernel. The kernel has the state of the TCP connection - it is just accessed from a different process. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jcd at sdf.lonestar.org Sun Sep 16 11:57:55 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Sun, 16 Sep 2007 11:57:55 -0400 Subject: SVG to raster conversion. Message-ID: <46ED5283.3030004@sdf.lonestar.org> Does anybody know a good solution (preferably in python) for rasterizing SVG or other vector graphics. I'm thinking something like vector_image = SVGFile(path_to_image) raster_image = vector_image.rasterize(format, (width, height), dpi) raster_image.write(out_file) Thanks for any pointers you might have. From khemkaamit at gmail.com Tue Sep 4 06:24:44 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 4 Sep 2007 15:54:44 +0530 Subject: TypeError: 'module object is not callable' In-Reply-To: <1188900397.459760.259580@k79g2000hse.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> Message-ID: <1360b7230709040324t638e9666gc9211132f1d5fae0@mail.gmail.com> On 9/4/07, Chris.Tidy at jet.uk wrote: > Thanks guys. Changing to how Python does things has a lot of geting > used to! > Do any of you have any ideas on the best way to do the following > problem: > > Each loop I perform, I get a new list of Strings. > I then want to print these lists as columns adjacent to each other > starting with the first > created list in the first column and last created list in the final > column. > > If you need any more information, just let me know! > Cheers If I understand correctly what you may want is: >>> l = ['1', '2', '3', '4'] you can do: >>> print "\t".join(l) # lookup join method in string module, assuming "\t" as the delimiter or, >>> for i in l: .... print i, '\t' , # note the trailing "," If this is not what you want, post an example. Btw, Please post new issues in a separate thread. Cheers, -- ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in From carsten at uniqsys.com Mon Sep 24 08:09:21 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Sep 2007 08:09:21 -0400 Subject: sorting a list numbers stored as strings In-Reply-To: References: Message-ID: <1190635761.5618.2.camel@dot.uniqsys.com> On Mon, 2007-09-24 at 19:58 +0800, Delaney, Timothy (Tim) wrote: > I'm sure that in some version of Python it would have given a > ValueError (due to the default radix being 0) but it appears to have > changed to a default radix of 10 somewhere along the way. Not even Python 1.5.2 seems to have a problem with leading zeroes: Python 1.5.2 (#1, Nov 6 1999, 14:53:40) [C] on sco_sv3 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> int("08") 8 -- Carsten Haese http://informixdb.sourceforge.net From arkanes at gmail.com Wed Sep 12 11:49:01 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 12 Sep 2007 10:49:01 -0500 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189605250.186948.303130@50g2000hsm.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <13efnmi4n959a59@corp.supernews.com> <1189601205.503841.327170@o80g2000hse.googlegroups.com> <1189605250.186948.303130@50g2000hsm.googlegroups.com> Message-ID: <4866bea60709120849hc0beacfu681ec6b4eff3e235@mail.gmail.com> On 9/12/07, Mark Summerfield wrote: > On 12 Sep, 13:46, Michele Simionato > wrote: > > On Sep 12, 2:42 pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > > On Wed, 12 Sep 2007 07:33:45 +0000, Mark Summerfield wrote: > > > In fact, I'm not sure what people mean by ordered dicts. I assume they > > > mean the keys are ordered, not the values. But ordered by what? Insertion > > > order? Modification order? Alphabetical order? > > > > Insertion order. > > > > M.S. > > > Actually I meant by key order, so insertion order doesn't matter at > all. If you need a dictionary-like data structure that respects > insertion order you could use a list of (key, value) tuples. > These sort of disagreements about what such a beast should "obviously" do are a good part of the reason why one doesn't exist in the standard library. A sorted dict is so trivial that it's not really seen as necessary, since all you have to do is sort the keys(). An ordered dict is generally better satisfied with a list, as you've seen. There's implementations of all these for people who want something wrapped up in the cookbook. >But what happens when I need to do this a *lot* and when the number of >items is hundreds or a few thousands? keys = sorted(d.keys()) for k in key: ... You've got two choices: either you insert more than you iterate, in which case sorting at the point of iteration is the most efficient option, or you iterate more than you insert, in which case sorting after you insert is easy. There's no way that an ordered dict implementation could satisfy both constraints. Can you honestly think of a use case where the performance of your sorting is a bottleneck *and* it's a suitably general case that a standard lib class should optimize for that specific case? Even in this short thread we've seen 3 different ideas of what the dict should do. From http Tue Sep 11 23:42:05 2007 From: http (Paul Rubin) Date: 11 Sep 2007 20:42:05 -0700 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> Message-ID: <7x7imwpn1u.fsf@ruckus.brouhaha.com> TheFlyingDutchman writes: > Python user and advocate Bruce Eckel is disappointed with the > additions (or lack of additions) in Python 3: > > http://www.artima.com/weblogs/viewpost.jsp?thread=214112 That article is pretty weak. From rrr at ronadam.com Fri Sep 21 18:44:39 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 21 Sep 2007 17:44:39 -0500 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190412475.772358.109810@n39g2000hsh.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> Message-ID: <46F44957.6060700@ronadam.com> Cristian wrote: > My hope is to subtly reinforce the notion that functions are data > and can be passed around. The current function declaration doesn't > help with this. Creating a function and assigning it to a name is > exactly what Python does, why not have it come out in the syntax? It's > not necessary, yes, but I think it would be helpful for teaching > purposes. I think key may be to discuss names and name binding with your friend. How a name is not the object it self, like a variable is in other languages. For example show him how an object can have more than one name. And discus how names can be bound to nearly anything, including classes and functions. > Again, it's not necessary as much as it's more intuitive and obvious > what's going on. This helps a beginner sort out the process from the > syntax without taking it on faith. They can see the class declaration > and see "I'm defining just another attribute to this class only this > time it happens to be method". > > There is nothing functionally lacking in Python. I'm just curious if > there's anything Python can do syntax-wise to help a person better > grasp programming ideas and Python's inner workings. You could also discus factory functions with him. Once he gets that a function can return another function, then it won't be so much of a leap for a function to take a function as an argument. Of course he'll figure out all this sooner or later anyway. You can't be an engineer without a fair amount of brain cells committed to processing abstract concepts. Cheers, Ron From brown at esteem.com Thu Sep 6 19:02:51 2007 From: brown at esteem.com (Tom Brown) Date: Thu, 6 Sep 2007 16:02:51 -0700 Subject: why should I learn python In-Reply-To: <87zlzzs9by.fsf@wilson.homeunix.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> Message-ID: <200709061602.52121.brown@esteem.com> On Thursday 06 September 2007 15:44, Torsten Bronger wrote: > Hall?chen! > > Tom Brown writes: > > [...] Python has been by far the easiest to develop in. Some > > people might say it is not "real programming" because it is so > > easy. > > I can't believe this. Have you really heard such a statement? Yes. I was told this by a C programmer. Something about doing it all yourself and not using provided packages. I countered with something about reinventing the wheel. :) From jcd at sdf.lonestar.org Mon Sep 10 20:24:35 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 10 Sep 2007 20:24:35 -0400 Subject: question on python syntax In-Reply-To: <46E5D8F8.1060501@townisp.com> References: <1189467581.200075.236120@g4g2000hsf.googlegroups.com> <46E5D8F8.1060501@townisp.com> Message-ID: <46E5E043.6000604@sdf.lonestar.org> Andrew Robert wrote: > a.m. wrote: >> If I type this in shell >> >> $ ./yourfile.py 12:34 PM & >> >> What does '$', '.', '/' and '& means in this succession? Note: >> 12:34 PM is a argument to the yourfile.py. >> > > This not python syntax but Unix shell. > > $ = shell prompt ./ = look for the program > in my current working directory yourfile.py = the program name > 12:34 = argument 1 PM = argument 2 & > = run in background And just to be perfectly clear, you don't type the $. It's already there for you, in some form; your prompt may not be a $. Cheers, Cliff -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Wed Sep 12 16:52:54 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Sep 2007 13:52:54 -0700 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1i4bnbp.1l8sr3mjdojghN%aleax@mac.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> <1i4bnbp.1l8sr3mjdojghN%aleax@mac.com> Message-ID: <1189630374.506503.190690@r34g2000hsd.googlegroups.com> On Sep 12, 1:05 pm, al... at mac.com (Alex Martelli) wrote: > Making, say, 'a' hiddenly mean 'x.a', within a function, requires a > decorator that suitably rewrites the function's bytecode... (after > which, it WOULD still be terrible and horrible and not to be used, just > as you say, but it might at least _work_;-). Main problem is, the > decorator needs to know the set of names to be "faked out" in this > terrible and horrible way at the time the 'def' statement executes: it > can't wait until runtime (to dynamically determine what's in var(self)) > before it rewrites the bytecode (well, I guess you _could_ arrange a > complicated system to do that, but it _would_ be ridiculously slow). How about this? The decorator could generate a bytecode wrapper that would have the following behavior, where __setlocal__ and __execute_function__ are special forms that are not possible in Python. (The loops would necessarily be unwrapped in the actual bytecode.) for sym in sys._getframe(0).f_code.co_varnames: if sym == "self": continue try: __setlocal__(sym,getattr(self,sym)) except AttributeError: pass try: __execute_function__() finally: for sym,val in locals.iteritems(): if sym == "self": continue if sym in self: setattr(self,sym,val) This wouldn't be that much slower than just assigning local variables to locals by hand, and it would allow assignments in the straightforward way as well. There'd be some gotchas, so extra care is required, but it seems like for the OP's particular use case of a complex math calculation script, it would be a decent solution. I understand where the OP is coming from. I've done flight simulations in Java where there are lot of complex calculations using symbols. This is a typical formula (drag force calculation) that I would NOT want to have to use self.xxx for: FX_wind = -0.5 * rho * Vsq * Sref * (C_D_0 + C_D_alphasq*alpha*alpha + C_D_esq*e*e) Even if I'd habitually used "this." in Java, I'd probably skip it in functions like htis. Carl Banks From michele.simionato at gmail.com Wed Sep 12 10:04:03 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 12 Sep 2007 14:04:03 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189605250.186948.303130@50g2000hsm.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <13efnmi4n959a59@corp.supernews.com> <1189601205.503841.327170@o80g2000hse.googlegroups.com> <1189605250.186948.303130@50g2000hsm.googlegroups.com> Message-ID: <1189605843.866907.117370@w3g2000hsg.googlegroups.com> On Sep 12, 3:54 pm, Mark Summerfield wrote: > On 12 Sep, 13:46, Michele Simionato > > Actually I meant by key order, so insertion order doesn't matter at > all. If you need a dictionary-like data structure that respects > insertion order you could use a list of (key, value) tuples. > > Another respondent asked about use cases. > > I have found time and again that I needed (key, value) pairs where the > key is some string that provides a representation for human readers > and the value is some internal key (e.g., database ID) that the system > uses internally. In these cases I often need to present the user with > a list of items from which to choose and want to present them in > sorted order. Naturally, I could use an ordinary dict and then do > this: > > for string in sorted(d.keys()): > process(string) > > But what happens when I need to do this a *lot* and when the number of > items is hundreds or a few thousands? I'm having to sort again and > again, since it is often the case that the items in the list changes > during the runtime of the application. So my solution in C++ is to use > an ordered dictionary (a map in C++ jargon), which in Python means I > can simply write: > > for string in od.keys(): > process(string) > For your use case I would wrap a list [(key, value)] with a dict-like object and I would use the bisect module in the standard library to keep the inner list ordered. M.S. From iclark at mail.ewu.edu Thu Sep 6 14:30:14 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Thu, 06 Sep 2007 11:30:14 -0700 Subject: Getting original working directory In-Reply-To: <12.1809-14479-787046656-1189102077@seznam.cz> References: <1189092734.750184.317490@y42g2000hsy.googlegroups.com> <12.1809-14479-787046656-1189102077@seznam.cz> Message-ID: rave247 rave247 wrote: > "......the *original* directory location *after* os.chdir() is performed......" os.getcwd() is not helping much as it returns the location that was set up in os.chdir() call > > Thanks Your question is akin to having a name X that is bound to some value, setting it to 2 and then wanting to know what the original value is. It just ain't gonna happen. Simply follow the advice given by Gary and use os.getcwd() *before* the call to os.chdir(). Ian From jstucklex at attglobal.net Sun Sep 30 15:49:35 2007 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Sun, 30 Sep 2007 15:49:35 -0400 Subject: which language allows you to change an argument's value? In-Reply-To: References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> <1191170989.227928.252880@g4g2000hsf.googlegroups.com> Message-ID: Erik Wikstr?m wrote: > On 2007-09-30 18:49, Summercool wrote: >> On Sep 30, 4:18 am, 7stud -- wrote: >>> SpringFlowers AutumnMoon wrote: >>>> we have no way >>>> of knowing what we pass in could get changed. >>> Sure you do. You look at the function's signature. In order to use >>> someone else's library, you have to know the function's signature. And >>> the signature explicitly tells you whether the value you pass in could >>> be changed. >> do you mean in C++? I tried to find signature in two C++ books and it >> is not there. Google has a few results but it looks something like >> prototype. Is signature the same as the function prototype in the .h >> file? > > A signature is what is required to identify a function and includes > return type, name of function and the types of the parameters, while it > looks just like a prototype it is not. A prototype is something you > write to satisfy your compiler while a signature identifies a function. > Below are some examples of signatures, only the last can modify the > values of its parameter. > No, the function's signature does not include the return type. > void foo(int, float) > std::string bar(const std::string&, int, int) > void baz(std::string&) > Actually, these are prototypes. The signature is what's passed onto the linker - perhaps something like "?foo@@YAXHM at Z". It's also generally compiler dependent for C++ mangled names. Also, I should clarify - the C++ function signature includes parameter information. The C function signature is only dependent on the function name and is almost always the name preceded by an underscore). You can see the function signatures in a map file if you leave the names mangled. . >> If so, don't we usually just include <___.h> and forget about >> the rest. Documentation is fine although in some situation, the >> descriptions is 2 lines, and notes and warnings are 4, 5 times that, >> and the users' discussing it, holding different opinion is again 2, 3 >> times of that length. > > Unless you read the documentation how do you know which files to > include? And what documentation are you reading which does not clearly > specify the functionality of the functions described? > Exactly. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From kishore at mindriver-it.com Wed Sep 26 04:19:58 2007 From: kishore at mindriver-it.com (kishore at mindriver-it.com) Date: Wed, 26 Sep 2007 13:49:58 +0530 Subject: Python-list Digest, Vol 48, Issue 391 In-Reply-To: Message-ID: <20070926081642.C27CE1E4009@bag.python.org> Hi This is krishna kishore from MindRiver. We have an Urgent requirement for Python Developers with 5-7Yrs of Exp Mandatory Skills : Python and c and c++ Exp : 5-7 yrs Qualification : B.E ONLY Work Location : Bangalroe. If you are Looking for a change Please forward your Updated Profile. Thanks & Regards, Kishore Seethanraju |Senior Associate-People Consulting| MindRiver Information Technologies Pvt. Ltd. Suite# 512, 4th Floor and Suite # 104, Ground Floor ,Oxford Towers, 139, Airport Road, Bangalore 560 008| Tel: +91.80.3052.1600 |Direct: +91.80.3057.5799| Mobile: + 91.9901 96 1696 | Fax: +91.80.3057.5797| Email: kishore at mindriver-it.com | Web www.mindriver-it.com Information transmitted by this-mail is proprietary to MindRiver and / or its Customers and is intended for use only by the individual or entity to which it is addressed, and may contain information that is privileged, confidential or exempt from disclosure under applicable law. If you are not the intended recipient or it appears that this mail has been forwarded to you without proper authority, you are notified that any use or dissemination of this information in any manner is strictly prohibited. In such cases, please notify us immediately at the above mentioned telephone number or email to services at mindriver-it.com and delete this mail from your records. We believe this email to be virus free but do not warrant that this is the case and we will not accept liability for any losses arising from any virus being transmitted unintentionally by us' -----Original Message----- From: python-list-bounces+kishore=mindriver-it.com at python.org [mailto:python-list-bounces+kishore=mindriver-it.com at python.org] On Behalf Of python-list-request at python.org Sent: Wednesday, September 26, 2007 1:35 PM To: python-list at python.org Subject: Python-list Digest, Vol 48, Issue 391 Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." -------------- next part -------------- An HTML attachment was scrubbed... URL: From trekker182 at gmail.com Sat Sep 15 19:52:47 2007 From: trekker182 at gmail.com (Shawn Minisall) Date: Sat, 15 Sep 2007 19:52:47 -0400 Subject: string questions Message-ID: <46EC704F.5000101@gmail.com> Hi everyone, I'm a beginning programming student in Python and have a few questions regarding strings. If s1 = "spam" If s2 = "ni!" 1. Would string.ljust(string.upper(s2),4) * 3 start it at the left margin and move it 12 spaces to the right because of the 4 *3? If so, why is it in the parathesis for the upper command and not the ljust? I already know that it would cap it to NI! 2. To get the output "Spam Ni! Spam Ni! Spam Ni!" I could do something like this string.join ([s1, s2]), But I'm a little lost how to get it repeated three times on one line. Would I just have to put the same command on the next two lines? 3. To change spam to spm, the string.replace seems to be the best function to use. However, when I use string.replace(s1, "a", " ") in python to replace a with an empty space, it doesn't work...I just get spam back when I print s1. Any ideas? Thanks. -Shawn From http Fri Sep 28 11:51:41 2007 From: http (Paul Rubin) Date: 28 Sep 2007 08:51:41 -0700 Subject: Python 3.0 migration plans? References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> Message-ID: <7x3awyu6sy.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > All serious languages are turing-complete. So can we put away with this > non-sense argument right away, please? Actually the so called "total" languages aren't Turing-complete. I think Coq is an example: every Coq function must return a value. So Coq doesn't have any way to write an infinite loop, because that would allow writing functions that fail to return. So there is no halting program in Coq (every Coq program halts), which means Coq is not Turing-complete. That allows Coq to generate code about which it can make all kinds of guarantees that most languages can't (not simply that the programs halt but that they actually fulfill their computational specifications), so it's being used in various high-assurance applications, though usually to write just the most critical parts of a program, not the entire program. Of course it's a matter of semantics but in some meaningful ways, I'd say Coq is a more serious language than Python. Here is a famous early paper explaining why Turing-completeness isn't all it's cracked up to be: http://sblp2004.ic.uff.br/papers/turner.pdf This paper shows some of the advantages of the total approach. From xkenneth at gmail.com Wed Sep 12 15:52:40 2007 From: xkenneth at gmail.com (xkenneth) Date: Wed, 12 Sep 2007 12:52:40 -0700 Subject: xml question In-Reply-To: References: Message-ID: <1189626760.269992.252160@g4g2000hsf.googlegroups.com> There are built in tools for the DOM in Python. Also I'm using OSX to do XML parsing but I'm using the tools available from 4suite. On Sep 12, 2:21 pm, JYOUN... at kc.rr.com wrote: > Just curious if there's any python xml parsing tools built into the Mac (OS 10.4.10 Tiger)? If so, > could anyone > share some simple code (or maybe point me to a web-site) of how to parse xml data from a > file? For example, if I > had a file that contained this: > > > > Black > Light Blue > Green > > > I'd want to look in the 'colors' xml element, then look at each 'color' xml element inside and > pull any that have > values (which would be Black, Light Blue and Green). I'd like to know how to pull 'attributes' > too. > > Thanks very much for your help. > > Jay From prudek at bvx.cz Tue Sep 11 07:00:32 2007 From: prudek at bvx.cz (Milos Prudek) Date: Tue, 11 Sep 2007 13:00:32 +0200 Subject: zlib In-Reply-To: References: Message-ID: <200709111300.32633.prudek@bvx.cz> > > Although I have Python 2.5 with zlib in my Linux disto, I need to install > > my own Python (as most Zope developers do). > > Why? Because Zope often requires Python version slightly older than the most current one. > So why does your own Python version have to be 2.4.4? Because "Plone 3.0 requires Zope 2.10.4 and Python 2.4.4", as you can see on plone.org. -- Milos Prudek From ldo at geek-central.gen.new_zealand Thu Sep 27 00:53:43 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 27 Sep 2007 16:53:43 +1200 Subject: ~ bit-wise unary operator References: <87r6klm5fk.fsf@mulj.homelinux.net> Message-ID: In message <87r6klm5fk.fsf at mulj.homelinux.net>, Hrvoje Niksic wrote: > If you want 16-bit unsigned arithmetic, use 2**16 + ~a, which yields > 57557. Or why not use "0xffff ^ a", which returns the same thing. From david at asdf.asdf Tue Sep 11 22:34:58 2007 From: david at asdf.asdf (bambam) Date: Wed, 12 Sep 2007 12:34:58 +1000 Subject: function to do dynamic import? References: <13ecb84p1ghrd64@corp.supernews.com> Message-ID: <13eek2h7lcikm5b@corp.supernews.com> "Steve Holden" wrote in message news:mailman.378.1189513496.2658.python-list at python.org... > bambam wrote: >> import works in the main section of the module, but does >> not work as I hoped when run inside a function. >> >> That is, the modules import correctly, but are not visible to >> the enclosing (global) scope. >> >> Questions: >> (1) Where can I read an explanation of this? >> (2) Is there a work around? >> >> BTW, sys.modules("filename") shows that the module is >> loaded, I just don't know how to use it when loaded that >> way. Also, if I import again at the global scope, the module >> name becomes available. >> > There's not much wrong with doing this, since it gives you the best of > both worlds. But you mean sys.modules["filename"], don't you? > >>>>> def gim(): >> ... exec "import gamel" >> ... >>>>> gim() >>>>> sys.modules["gamel"] >> >>>>> gamel >> NameError: name 'gamel' is not defined >>>>> exec "import gamel" >>>>> gamel >> > Whoa there! There's a lot of difference between "importing a module inside > a function" and "executing an import statement inside a function". > > If you want to do dynamic imports then the __import__ function is what you > need. Trying to use exec like that is a bad idea unless you clearly > understand the relationship between the different namespaces involved. In > fact, trying to use exec at all is a bad idea until you understand Python > better, and even then it's not often a terrific idea. > > Think of exec more as a hack of last resort than the first tool to reach > for to solve a problem. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- > Yes, sys.modules["filename"], unfortunately, same mistake made already 4 or 5 times before I typed this, and still hadn't learned...many years working in an environment where the distinction was not important. Sorry. def gim(self): for gamel in self.gamel_list: __import__(gamel['file']) Works as hoped for. I did a web search for 'dynamic import' and the only examples I found used exec. Thanks Steve. From aine_canby at yahoo.com Thu Sep 27 09:03:41 2007 From: aine_canby at yahoo.com (aine_canby at yahoo.com) Date: Thu, 27 Sep 2007 06:03:41 -0700 Subject: Confusion regarding constructor as default value Message-ID: <1190898221.833936.40480@57g2000hsv.googlegroups.com> Why are the following different? def AddRow(self, rowName, tableRow=TableRow(ReleaseDate(""), ExpiryDate(""))): # check to see if the row already exists, if not add it to the container if not self.dict.has_key(rowName): self.dict[rowName] = tableRow def AddRow(self, rowName, tableRow): # check to see if the row already exists, if not add it to the container if not self.dict.has_key(rowName): self.dict[rowName] = TableRow(ReleaseDate(""), ExpiryDate("")) It seems that when I use the first function that I'm getting duplicate objects in self.dict Thanks for your help, Aine. From kay.schluehr at gmx.net Sun Sep 16 07:11:40 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 16 Sep 2007 04:11:40 -0700 Subject: Needless copying in iterations? In-Reply-To: <13epv3fnb6bak15@corp.supernews.com> References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> <13epv3fnb6bak15@corp.supernews.com> Message-ID: <1189941100.385721.45300@g4g2000hsf.googlegroups.com> > Haskell is a dynamic language, and there are optimizing compilers for it. Last time I used Haskell it was statically typed but this has been almost a year ago and times are changing fast. About optimizing compilers for Python. These won't work without restrictions a la Shedskin which uses C++ as its backend. But unlike Shedskin and the design mistake being made in this project we can learn the lesson from Psyco that there must be a fallback to bytecode interpretation when some argument does not fit the signature of a specialized function. I'm personally a bit skeptical about JIT compilation since I feel it's a waste of electric currency to start recording all the information at runtime and perform native compilations again and again. It doesn't mean that JIT compilation can't be effective. I have a conceptual bias against it. Instead I expect a rather stable behaviour and rather fixed nominal types despite the fact that Python supports duck-typing. Unfortunately I'm unable to recover an investigation about the effectiveness of adding tests to a rather well equipped testbase. The result was one of "declining profits". Stable behaviour emerged early with good coverage properties. Than one had to work hard to improve and find more bugs. A similar effect might also cause the effectiveness of dynamic typing for catching errors which is not easy to justify by purely theoretical arguments. ----- Note that I worked out some pieces of a type feedback mechanism that records types and displays the results in a slightly modified Python dialect called TPython. A TPython program can be regarded as a "typed hypothesis" about an otherwise untyped ( or dynamically typed ) Python program. You can keep the TPython program and translate it completely or fragments of it to other languages like C++, D, Java, OCaml etc. Obviously this approach shall be used for incremental progress and smooth integration and it might work even when only small portions can be translated ( typically functions that keep and return only integers/ floats which are bound in range are a good start ). So far everything is implemented in pure Python and the amount of source is < 1000 LOC. I have not published anything of it yet and i'm a rather slow publisher anyway. If anyone is interested in this kind of work and willing to contribute i might set it aside from the usual EasyExtend stuff ( which is the foundation nevertheless ) I'm working on and reframe the project context e.g. on Sourceforge or elsewhere. Email address and project page are still kay at fiber-space.de www.fiber-space.de If no one contributes the fun is exclusively on my side and everything is moving slower. That's all. From steve at holdenweb.com Fri Sep 7 15:19:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Sep 2007 12:19:12 -0700 Subject: unexpected behavior: did i create a pointer? In-Reply-To: <13e2jdobu2kqkf1@corp.supernews.com> References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <13e2jdobu2kqkf1@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-09-07, Peter Otten <__peter__ at web.de> wrote: >> Am Fri, 07 Sep 2007 10:40:47 +0000 schrieb Steven D'Aprano: >> >>> Python doesn't have any pointers. >> Thinking of python variables or "names" as pointers should >> get you a long way when trying to understand python's behaviour. > > But thinking of them as names bound to objects will get you > further (and get you there faster). ;) > True. Since it's only a matter of time before someone brings up the "post-It" analogy, let me cavil in advance about it. The thing I don't like about that particular pedagogic mechanism is that it always "attaches" the names to the objects. To me that blurs the fact that the names live strictly inside namespaces, and are destroyed (along with the references they make to other objects) when the namespace goes out of scope or otherwise ceases to exist (instance destruction being the obvious one). I only mention this because I too can be a pedantic little bugger when I want to be. Have a nice day. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bignose+hates-spam at benfinney.id.au Mon Sep 10 20:34:16 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 11 Sep 2007 10:34:16 +1000 Subject: Question about PEP 8 References: Message-ID: <877imy9h13.fsf@benfinney.id.au> Laszlo Nagy writes: > Here is my problem. There is ConfigParser, StringIO, Queue, > HTMLParser etc. They are all part of the standard library. Yes, many modules in the standard library don't conform to PEP 8; these are known bugs. > Most of these are modules with only a "main class" > defined. ConfigParser module contains ConfigParser class, Queue > module contains Queue class etc. Should I use CapWords for the > module (and file) name or not? Since that's what it's called, you can't reasonably avoid it. > E.g. should I > from mess.wxmegaeidgets.GenericDialog import GenericDialog > > or > from mess.wxmegaeidgets.genericdialog import GenericDialog Have you tried either of these? Use the one that works. > (suppose that the module contains only the GenericDialog class. BTW, > will Py3K change the standard library names in order to follow PEP > 8?) There is a distinct "clean up the standard library" project; I can't recall if it is intended to be part of Py3k. > Great, but what if I subclass wx widgets? They all have > CapWords. (wx.Window.ShowModal, wx.Window.Bind etc.) I must use > CapitalizedWords for method names because sometimes I have to override > inherited methods, and it is not possible to change their name. Where > should be the limit? PEP 8 can't retroactively change the code you're importing. It's a guideline for code that *you* write; i.e. when you write a new module, or a new class or function, follow the guidelines. Existing code is how it is, and a lot of code is already written that relies on the names in e.g. wxWidgets. Only a backwards-imcompatible upgrade (such as Py3k) can hope to remove those non-conformant names. > If I create a composite widget then should I use > lowercase and underscores? If it's a class, use TitleCase; if it's an instance or a function, use lower_case. If it *must* be the same name as something else (e.g. you're overriding an existing inherited function), you have no choice but to name it whatever the original is named. > If I create a class that is not itself a widget, but works with > widgets? The PEP defines the "theoretically good" coding style, but > what is the correct style in an environment where you have third > party libraries that are not following the PEP? Follow PEP 8 for your code. Grit your teeth and use the non-standard conventions of third-party libraries, until such time as they are (backward-incompatibly) changed to be compliant. -- \ "Don't be afraid of missing opportunities. Behind every failure | `\ is an opportunity somebody wishes they had missed." -- Jane | _o__) Wagner, via Lily Tomlin | Ben Finney From deets at nospam.web.de Mon Sep 3 05:04:41 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Sep 2007 11:04:41 +0200 Subject: ShowMeDo.com Announces Winner of Most-Video-Plays of the Month References: Message-ID: <5k2119F1p42tU1@mid.uni-berlin.de> Jeff Rush wrote: > ShowMeDo.com, a website offering over 361 instructional screencasts about > topics both Python and non-Python, has announced their first winner of the > month for the most-played video. And the winner is: > > "Learn Django: Create a Wiki in 20 minutes" > > by Siddharta Govindaraj, founder of Silver Stripe Software, with 1851 > views in > August, far outpacing the second-place entry. The prize is a ?20 (UK) > voucher > to Amazon. Congratulations, Siddhi! You can watch it at: > > http://showmedo.com/videos/video?name=1100000&fromSeriesID=110 > > Siddhi is also helping Doug Napoleone with PyCon this year, providing a > program for generating attendee badges and working to integrate it into > the Django-based conference site. > > You can find Siddhi at: > > http://siddhi.blogspot.com/ > http://www.silverstripesoftware.com/ > > So who will win this month? It could be you! How about a screencast > showcasing a different web framework like TurboGears or Twisted Web? Or > something about databases, either relational or object. Great work. I just have one small remark: given the increasing amount of spam in the NG/ML that reads "go bla.com to learn everything about ...", I was at first convinced that your post was one amongst these. Maybe a subject line that shows somewhat more python context would be a good idea? Just a suggestion. Diez From deets at nospam.web.de Mon Sep 24 02:47:27 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Sep 2007 08:47:27 +0200 Subject: building a GUI In-Reply-To: References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> <5lnp2rF90pqqU1@mid.uni-berlin.de> <46F6CB6C.3050609@gmail.com> <200709232234.54500.phil@riverbankcomputing.co.uk> Message-ID: <5lp4t1F99rmfU1@mid.uni-berlin.de> stef mientki schrieb: > Phil Thompson wrote: >> On Sunday 23 September 2007, stef mientki wrote: >> >>> Diez B. Roggisch wrote: >>> >>>> stef mientki schrieb: >>>> >>>>> Thomas Dybdahl Ahle wrote: >>>>> >>>>>> Den Sun, 23 Sep 2007 17:28:38 +0200 skrev stef mientki: >>>>>> >>>>>>> yadin wrote: >>>>>>> >>>>>>>> if i were up to make a GUI chich are the advantages of choosing >>>>>>>> python over matlab or java? >>>>>>>> >>>>>>> The best is Delphi, >>>>>>> second is VB, >>>>>>> >>>>>> That sounds mostly like a personal preference :) >>>>>> >>>>> Well I prefer Python ( because of it's OS-independancy and it's open >>>>> source), >>>>> but Python is really (still) much worse for GUI designs. >>>>> Just compare some parameters like: >>>>> - ease of use >>>>> - speed of development >>>>> - support of features >>>>> - availability of libraries >>>>> - documentation >>>>> >>>> Sounds like PyQt for me. Best GUI-designer I know, tremendous speed in >>>> development, giant sized lib that does all kinds of stuff & is >>>> brilliantly designed + professional grade docus. >>>> >>> Could well be, >>> but I never looked at PyQt seriously, >>> because of their weird license. >>> >> >> It's not weird. It's either GPL or proprietary. Your choice. That's as >> complicated as it gets. >> > This is what I find "weird": > == quote == > Trolltech's commercial license terms do not allow you to start > developing proprietary software using the Open Source edition. > == end quote == > Stef At least you do have the option to develop FOSS-software with it without prior buying it. Delpi you _have_ to by. Now what's more weird? Diez From robert.kern at gmail.com Sat Sep 22 21:06:58 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 22 Sep 2007 20:06:58 -0500 Subject: Odd files; just left behind? In-Reply-To: <46F52681.5090409@jessikat.plus.net> References: <878x725ts7.fsf@pobox.com> <46F191DF.7000908@jessikat.plus.net> <46f2bd9b$0$20143$426a74cc@news.free.fr> <46F38FBC.7090903@chamonix.reportlab.co.uk> <46F52681.5090409@jessikat.plus.net> Message-ID: Robin Becker wrote: > Robert Kern wrote: > ....... >> They're a cache. > > they're actually the files that get used by the installed extension in > this case (MySQLdb). Yes. They are extracted from the zipfile at runtime and left there so they don't have to be extracted again. That's why I called it a cache. I didn't mean anything else by the term. > .......... >>> it would seem simpler to have the .so files inside the site-packages and there's >>> the question of why this folder has to be obfuscated (name starts with .). Even >>> if these files are "resources" why should they be assumed to belong to the user? >> Because they are unpacked at runtime by the user that imported the module. >> Usually, they won't have write access to site-packages. > > in this particular case the python being used was installed with a user > prefix eg /myhome/PYTHON so everything belongs to the user; extensions > installed by the same user can surely be installed in those folders. > Upon checking I find that the same installs which produced the > ~/.python-eggs files also managed to put the eggs like > MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg inside the > various site-packages directories. > > I see no reason why the binary resources shouldn't be unpacked to > site-packages at install time. Then do so: Use the -Z argument to easy_install such that it always unpacks the zip file. If you don't, then the egg will be left zipped, and the resources extracted at runtime. Zipped eggs have benefits over the unzipped eggs in that they decrease the amount of import overhead of having many items in your sys.path. -- 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 yosuke at ccwf.cc.utexas.edu Mon Sep 3 15:47:55 2007 From: yosuke at ccwf.cc.utexas.edu (yosuke at ccwf.cc.utexas.edu) Date: Mon, 3 Sep 2007 19:47:55 +0000 (UTC) Subject: trap setting attribute when the attribute is dict References: <1188845236.417709.307160@50g2000hsm.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > On Sep 3, 7:00 pm, wrote: >> >> I want to do something like this. My class/instance has a dict as a >> property. I want the instance to catch the change in the dict (change >> in some values, addition/deletion of key/value etc) to be recognized by >> the class instance. >> >> How can I do this? Any suggestions are very well appreciated. >> >> Here is an example of what I want my class to behave: >> >> class test(object): >> def __init__(self): >> self._d = {} >> self._changed = False >> def getd(self): >> print 'called getd' >> return self._d >> # dont know what to do next >> def setd(self,val): >> print 'called setd', key, val >> self._d[key] = val > Where does the 'key' come from? Perhaps you need to look further into > how properties work. This obviously doesn't work... >> self._changed = True >> d = property(getd,setd,None,None) >> >> def getc(self): >> return self._changed >> changed = property(getc,None,None,None) >> >> if __name__ == '__main__': >> obj = test() >> print 'obj.changed = ', obj.changed >> print >> >> # I want obj to know that its propety d being changed here >> print "t.d['a'] = 1" >> obj.d['a'] = 1 >> print >> >> # I want the "changed" property to be True >> print 'obj.changed = ', obj.changed >> > You can't do that with plain dicts, and I'm not sure it is often a > good idea. However you could create a class that behaves like a dict > but calls a function each time an item is set, e.g. (made up > terminology): >>>> class TriggerDict(object): > ... def __init__(self, trigger, val=None): > ... self.trigger = trigger > ... self.dict_ = val or {} > ... def __setitem__(self, key, val): > ... self.trigger(self, key, val) > ... self.dict_[key] = val > ... def __getitem__(self, key): > ... return self.dict_[key] > ... >>>> def trigger(d, k, v): > ... print '%s => %s' % (k, v) > ... >>>> td = TriggerDict(trigger) >>>> td['spanish'] = 'inquisition' # see side effect below. > spanish => inquisition >>>> td['spanish'] > 'inquisition' >>>> > Obviously your trigger function would set the _changed attribute of > the test object instead. And again it is probably not a good idea > unless you know exactly what you are doing. If it was me, I'd try to > rethink my design instead. Thank you for suggestion, Arnaud. Since you are discouraging this idea of trigger, may I ask an advice of if my intention was legitimate one or not? My intention was to have a propery 'sum' in my object, and which has sum of all the values() of the dict (i have code to make sure that the value of dict are all numeric). I could just the propery being calculated everytime the property got __getattr__. But I thought that it was inefficient to calculate the same number over and over when the value is already known. So I was thiking of calculating the number only when the dict got modified. I also experimented with the idea of subclassing dict itself to calculate the sum. Is this what would be better solution? Thank you again, > -- > Arnaud -- yosuke kimura Center for Energy and Environmental Resources The Univ. of Texas at Austin, USA From robert.kern at gmail.com Sat Sep 15 14:50:10 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 15 Sep 2007 13:50:10 -0500 Subject: how to join array of integers? In-Reply-To: <13eo1rb73mg8b77@corp.supernews.com> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <46EBE498.9040800@ehas.org> <13eo1rb73mg8b77@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-09-15, Erik Jones wrote: > >>>> print ''.join([str(i) for i in [1,2,3]]) >>> It's better to use generator comprehension instead of LC: >>> >>> ",".join(str(i) for i in [1, 2, 3]) >> Why is that? That entire expression must be evaluated to obtain the >> result, so what is the advantage of using a generator comprehension >> v. a list comprehension? > > The generator avoids creating the intermediate list -- it > generates the intermediate values on the fly. For short > sequences it probably doesn't matter much. For a very long > list it's probably noticable. Not true. str.join() creates a list from the iterator if it is not already a list or a tuple. In Objects/stringobject.c, look at string_join(); it calls PySequence_Fast() on the argument. Looking in Objects/abstract.c, we see that PySequence_Fast() short-circuits lists and tuples but builds a full list from the iterable otherwise. map() seems to reliably be the fastest option, and list comprehensions seem to slightly edge out generator comprehensions if you do the timings. -- 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 bignose+hates-spam at benfinney.id.au Tue Sep 11 01:21:45 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 11 Sep 2007 15:21:45 +1000 Subject: Version numbering (was: Enum class with ToString functionality) References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <87bqca9hrw.fsf@benfinney.id.au> <1189472591.797327.189180@w3g2000hsg.googlegroups.com> <87sl5m7xxm.fsf@benfinney.id.au> <1189478288.237609.25140@50g2000hsm.googlegroups.com> <87odg99a6p.fsf@benfinney.id.au> <1189481628.270743.181300@g4g2000hsf.googlegroups.com> Message-ID: <87bqc993py.fsf_-_@benfinney.id.au> TheFlyingDutchman writes: > On Sep 10, 7:55 pm, "J. Cliff Dyer" wrote: > > Uh... The 1.0 version is vaporware? > > I think not. 42% of it is alive and kicking as we speak. That's odd. Do you think some similar matchematical relationship exists between Python version 2.4.4 and 3.0? You've made the common error of reading a package version as though it were a single number on a number line. That's not the customary semantic, though: versions are interpreted as a tuple of distinct integers. > When you were developing your Enum module, how did you determine you > were at the 0.4.2 version as opposed to the 0.7.1 version or the > 0.9.2 version? I initially developed at version 0.0, meaning "major level 0, minor level 0" ? i.e., no releases at all. Then, when the first "alpha" release was ready, I called it version 0.1, meaning "major level 0, minor level 1" ? i.e. no major releases yet, but the first minor release. Then, a small patch needed to be made, and the resulting release was version 0.1.1, meaning "major level 0, minor level 1, patch level 1" ? i.e. the first patch to version 0.1. Eventually some extra features warranted a release of version 0.2, meaning "major level 0, minor level 2" ? i.e. the second minor release with still no major releases. Implicit in this is "patch level 0", i.e. no patch-level versions yet; the version could be called 0.2.0 and have the same meaning. Each dot-separated integer is interpreted as a distinct level, subordinate to the preceding one: * Two versions with different major numbers can be expected to be incompatible. * If two versions have the same major number, one can expect only minor feature differences. * If two versions have the same major and minor number, one can expect that they differ only in bug fixes or the like. * Subsequent integers would imply even smaller differences at that same level if all preceding numbers were the same. Within a level, subsequent integers imply subsequent release times: version 0.4.1 can only be released before 0.4.2. However, this is not true across levels: a hypothetical version 0.2.7 could be released before *or* after 0.4.2, if the author decides a patch to the (equally hypothetical) version 0.2.6 is warranted. As for a putative version 1.0, that will not be released until I determine the package is functionally complete and warrants a first major release. Depending on how much changes between now and then, it may have most, some, or none of the code you see presently in version 0.4.2. -- \ "That's all very good in practice, but how does it work in | `\ *theory*?" ?Anonymous | _o__) | Ben Finney From grante at visi.com Mon Sep 17 10:26:39 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 17 Sep 2007 14:26:39 -0000 Subject: Python "with" References: Message-ID: <13et3kv409e355d@corp.supernews.com> On 2007-09-17, Laurent Pointal wrote: > Note3: Its funny to see how Python users tries to change the language, > does this occure with C, C++, Java, C# ? Yes. I remember somebody I worked with once who write a C program using a whole pile of macros to make it look like BASIC: #define IF if ( #define THEN ) { #define ELSE } else { #define ENDIF } and so on... -- Grant Edwards grante Yow! I am deeply CONCERNED at and I want something GOOD visi.com for BREAKFAST! From zentraders at gmail.com Sun Sep 2 10:35:00 2007 From: zentraders at gmail.com (Zentrader) Date: Sun, 02 Sep 2007 14:35:00 -0000 Subject: Pivy problem and some other stuff In-Reply-To: <13df1kmak87mbb@corp.supernews.com> References: <1188501707.593319.23330@m37g2000prh.googlegroups.com> <5jom54Fh543U2@mid.uni-berlin.de> <13df1kmak87mbb@corp.supernews.com> Message-ID: <1188743700.872880.21960@o80g2000hse.googlegroups.com> On Aug 30, 8:10 pm, Scott David Daniels wrote: > Marc 'BlackJack' Rintsch wrote: > > A fine repy > > > In [57]: funcs = [a, b] > > In [58]: funcs > > Out[58]: [, ] > > > In [59]: funcs[0]() > > Out[59]: 1 > > > In [60]: funcs[1]() > > Out[60]: 2 > > and a "list comprehension" allows you to call these things no matter how > long the list is. > > So after the above: > >>> results = [f() for f in funcs] > >>> print results > [1, 2] You can also use exec, but someone will tell you that the sky is going to fall if you do. I am one of the ones who think that calling a function with results = [f() for f in funcs] doesn't "work" because it gives a meaningless error message that the calling line didn't work. There is already enough discussion about this, so if you use "some_string()" to call a function, wrap it in a try/except with a traceback. From jergosh at wp.pl Sun Sep 9 07:29:16 2007 From: jergosh at wp.pl (=?UTF-8?B?R3J6ZWdvcnogU8WCb2Rrb3dpY3o=?=) Date: Sun, 09 Sep 2007 13:29:16 +0200 Subject: [OT] Re: So what exactly is a complex number? In-Reply-To: <5kcptmF32f64U1@mid.individual.net> References: <451mq4-les.ln1@ozzie.tundraware.com> <5k86hqF2if1hU1@mid.individual.net> <5kcptmF32f64U1@mid.individual.net> Message-ID: <46E3D90C.5030200@wp.pl> >> Interesting. It appears that we are ran into a mathematical >> cultural difference. Were I come from vectors *are* defined as >> having four properties that I enumerated. After some research I >> found that English sources (Wikipedia) indeed give the definition >> you supplied. >> > Indeed, interesting. > After some additional research I found that the most concise definition given here is 'A vector is an ordered pair of points'. From that follow the 4 properties: if we describe a vector by 2 points A(x_1, y_1) and B(x_2, y_2) we can convert this representation into the form [x_2 - x_1, y_2 - y_1] but some information is then lost in the process - conversion in the opposite direction is not possible without knowing the starting point. The article on the English Wikipedia (again, http://en.wikipedia.org/wiki/Vector_%28spatial%29) says: "*vector*, is a concept characterized by a magnitude and a direction. A vector *can be thought of as* (emphasis mine - G.) an arrow in Euclidean space, drawn from an *initial point* /A/ pointing to a *terminal point* /B/." Apparently what you know as the definition is a property where I come from, and vice versa. On a side note, I discovered more such differences (my studies are exclusively in English and we use mostly English textbooks even though I'm not in an English-speaking country). According to the article in the English Wikipedia a set is: "Definition (...)By a /set/ we understand any collection /S/ of definite, distinct objects /s/ of our perception or of our thought (which will be called the /elements/ of /S/) into a whole." In 'Basic Concepts of Mathematics' (available for free at http://www.trillia.com/zakon1.html), the author (who was, BTW, a Russian that settled in Canada) states: "A set is often described as a collection (?aggregate?, ?class?, ?totality?, ?family?) of objects of any specified kind. However, such descriptions are no definitions, as they merely replace the term ?set? by other undefined terms. Thus the term ?set? must be accepted as a primitive notion, without definition." To its credit, the Wikipedia article states that it describes the 'naive theory of sets'. Not a word about primary notions under http://en.wikipedia.org/wiki/Axiomatic_set_theory either, though. Similarly, I was once given a definition of a number as 'the common feature of sets with the same size' (or something to that effect), one that I couldn't find in any English source. Another, trivial, example can be the Abel theorem which is known as Buniakovsky (Buniakowski) theorem in Eastern Europe. There are also some inconsistencies in mathematical notation that I couldn't settle with my university lecturers but I don't want to deviate from the subject any further. I suppose they're the kind of doubts you get after reading too much Dijkstra ;) > I didn't say that you must not know the point of application, but I > said that it was not a property of the vector itself. It is true, > however, that in physical calculations you should not "mix" many > types of vectors (like force) that are, in the experiment, applied > to different points of application. > > Here it would be an intrinsic property of a vector ;). I think we've nailed the crux of the argument now. >> Again, I think we were given different definitions. Mine states >> that direction is 'the line on which the vector lies', sense is >> the 'arrow' and magnitude is the 'length' (thus non-negative). The >> definition is separate from mathematical description (which can be >> '[1 1] applied at (0, 0)' or 'sqrt(2) at 45 deg applied at (0, 0)' >> or any other that is unambiguous). >> > > Oh, I thought we were talking about quite mathematical vectors? > But we were, I think? >> No. In one-dimensional 'space' direction is a ? quantity (a >> 'sense'). In 2-d it can be given as an angle. >> > > Indeed, you're right. So, those vectors have different properties > depending on the used coordinate system? I myself prefer the > concise definition ... > I think it's similar to points in space: depending on the number of dimensions you need a corresponding number of coordinates to describe a point. Whether these are Cartesian or polar coordinates (complex plane also springs to mind) has no bearing on their number. Regards, Greg From lasses_weil at klapptsowieso.net Tue Sep 4 02:42:45 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Tue, 04 Sep 2007 08:42:45 +0200 Subject: Tkinter In-Reply-To: <1188882720.020666.67490@k79g2000hse.googlegroups.com> References: <1188882720.020666.67490@k79g2000hse.googlegroups.com> Message-ID: <46dcfe65$0$4522$9b4e6d93@newsspool3.arcor-online.net> vijayca wrote: > i tried to use python gui module Tkinter in solaris,aix,hpux..... > while importing the module it shows an error... > > import Tkinter > error says that your python may not be configured for Tk()... > how to get out of this... > Please copy and paste the invocation and (most importantly) the exact error you get. This will make it easier for everyone to help you. /W From python-url at phaseit.net Mon Sep 17 07:27:24 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 17 Sep 2007 11:27:24 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 17) Message-ID: QOTW: "I learn something valuable from comp.lang.python every week, and most of it has nothing to do with Python." - Richie Hindle "Ninety percent of all problems on top of the stove are caused because people don't preheat their pan properly." - Christopher Kimball, on the Zen that apparently applies even beyond software development http://www.powells.com/authors/kimball.html Comments on a blog post of Bruce Eckel where he feels a bit disappointed about Python 3.0: http://groups.google.com.ar/group/comp.lang.python/browse_thread/thread/70abee2f6f4dd5ee/ Attempts to explain how recursion works in clear words: http://groups.google.com.ar/group/comp.lang.python/browse_thread/thread/3a9287a528e3bab/ "Ordered dictionary" means different things for different people: http://groups.google.com.ar/group/comp.lang.python/browse_thread/thread/b16c34f8dd09a8a0 How to customize logging output in a common place: http://groups.google.com.ar/group/comp.lang.python/browse_thread/thread/ae5001bc1244e09a Using extended slicing and Ellipsis: http://groups.google.com.ar/group/comp.lang.python/browse_thread/thread/419d4ef17b2ecc67 How to remove undesired traceback entries: http://groups.google.com.ar/group/comp.lang.python/browse_thread/thread/387f76a210d6c456 Using self.name to access instance attributes is awful (newbie says): http://groups.google.com.ar/group/comp.lang.python/browse_thread/thread/a0ef8cf104c835a5 ======================================================================== 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 Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. 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 enthusiats": 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/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ 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/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch 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://aspn.activestate.com/ASPN/Cookbook/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 are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php 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/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. 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 *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python 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 kskuhlman at gmail.com Wed Sep 26 23:26:32 2007 From: kskuhlman at gmail.com (Ken Kuhlman) Date: Thu, 27 Sep 2007 03:26:32 -0000 Subject: Best way to do attribute docstrings? In-Reply-To: References: <1189195567.238990.54440@57g2000hsv.googlegroups.com> <1189540345.260656.115760@q5g2000prf.googlegroups.com> <1190770891.044084.123540@50g2000hsm.googlegroups.com> Message-ID: <1190863592.874028.49260@57g2000hsv.googlegroups.com> On Sep 26, 12:25 am, "Gabriel Genellina" wrote: > En Tue, 25 Sep 2007 22:41:31 -0300,KenKuhlman > escribi?: > > > Replying to myself in case someone finds this interesting. > > > Anyway, I took another shot at this with a little fresher mind, and it > > was quickly obvious that I was trying to force attributes to behave > > more like classes. It was a small step from there to creating a > > factory function to return instances of the appropriate class. I'm > > much happier with the result than either of the two previously posted > > kludges. > > Still there is something I don't understand on your design. You appear to > be always concerned about *class* attributes. *Instance* attributes are > far more comon, and usually they change their value many times. > ... > Gabriel Genellina I've only cared about class attributes to this point because my needs have been simple. They may not always be, however, so I'll take a shot at your challenge (below). I've basically just added a base class that defines __setattr__ to the mix. Thanks for the replies! -Ken # A factory function for generating attributes that can be annotated. def attr(value, doc=None): base = type(value) if base == bool: # bool class can't be used as a base, so we make one that can. class MyBool(int): def __str__(self): return str(bool(self)) __repr__ = __str__ base = MyBool class FancyAttr(base): pass fa = FancyAttr(value) fa.__doc__ = doc return fa class AnnotatedAttrsBase(object): _sticky_docs = True #False def __setattr__(self, name, value): """ Make sure attributes are fancy, maintaining docs if they're sticky. """ if type(value).__name__ != 'FancyAttr': doc = None if self._sticky_docs and hasattr(self, name): doc = self.__dict__[name].__doc__ self.__dict__[name] = attr(value, doc) else: self.__dict__[name] = value class Animal(AnnotatedAttrsBase): can_fly = attr(value = False, doc = "no Animal can fly unless explicitly noted") lives = attr(value = 1, doc = "most Animals have a single life") def __init__(self, color, legs, favorite_food): self.color = attr(color, "every animal has a color") self.legs = attr(legs, "most animals have legs") self.favorite_food = favorite_food class Mammal(Animal): pass class Cat(Mammal): def __init__(self, color): Mammal.__init__(self, color=color, legs=4, favorite_food='mice') self.lives = attr(value = 7, doc = "a cat starts with 7 lives") class Mouse(Mammal): def __init__(self, color, personality): Mammal.__init__(self, color=color, legs=4, favorite_food='cheese') self.personality = personality class Bird(Animal): can_fly = True _sticky_docs = False def __init__(self, color): Animal.__init__(self, color=color, legs=2, favorite_food='seed') tweety = Bird('yellow') tweety.lives = 42 sylvester = Cat('black') tom = Cat('blue') jerry = Mouse('brown', 'nice') itchy = Mouse('blue', 'sadist') scratchy = Cat('black') scratchy.lives = attr(7**7, "or so...") print scratchy.color, scratchy.color.__doc__ print scratchy.lives, scratchy.lives.__doc__ print tweety.legs, tweety.legs.__doc__ print tweety.lives, tweety.lives.__doc__ From munncha at gmail.com Sat Sep 22 22:28:46 2007 From: munncha at gmail.com (Kurtis Heimerl) Date: Sat, 22 Sep 2007 19:28:46 -0700 Subject: Preemption in python Message-ID: <9a4753250709221928s5768b15emecfd71a0f476cce@mail.gmail.com> Hi, I'm developing my first python application, a multi-threaded cell phone gadget on ubuntu 7.10. I've just split off my first thread, and I've noticed something extremely strange: There doesn't seem to be any preemption. There are currently two threads, one that pings a storage service to see if there are messages available, and the other that runs the gtk windows. If I do not explicitly yield either one, it runs forever. I'm assuming this is a setting somewhere, but that's a very strange default behavior. How do I get this to go about preempting these threads? Any advice would be helpful. Thanks! I apologize if anyone sees this twice, I sent a copy earlier but did not receive it from the mailing list, indicating to me that it wasn't received correctly. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcknight0219 at gmail.com Fri Sep 7 04:10:17 2007 From: mcknight0219 at gmail.com (Jimmy) Date: Fri, 07 Sep 2007 01:10:17 -0700 Subject: wxPython unexpected exit Message-ID: <1189152617.169438.296630@d55g2000hsg.googlegroups.com> Hi, wxPython is cool and easy to use, But I ran into a problem recently when I try to write a GUI. The thing is I want to periodically update the content of StatixText object, so after create them, I pack them into a list...the problem comes when I later try to extract them from the list! I don't know why? my code is as following: import wx, socket import thread class MyFrame(wx.Frame): firstrun = 0 def __init__(self): wx.Frame.__init__(self, None, -1, 'Notifier') self.panel = wx.Panel(self, -1) self.length = 50 self.scale = 0.6 self.count = 5 self.size = wx.Frame.GetSize(self) self.distance = self.size[1] / self.count self.labellist = [] self.gaugelist = [] def ParseAndDisplay(self, data): print "Successful access to main Frame class" print 'And receive data: ', data if MyFrame.firstrun == 0: print 'First time run' items = 3 for i in range(items): self.labellist.append(wx.StaticText(self.panel, -1, data+str(i), (150, 50+i*20), (300,30))) MyFrame.firstrun = 1 else: self.labellist[0].SetLabel('AAA')//PROGRAM WILL ABORT HERE!!! self.labellist[1].SetLabel("Guo") self.labellist[2].SetLabel("Qiang") class NetUdp: def __init__(self): self.port = 8081 self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.s.bind(("", self.port)) print "Listening on port", self.port def recvdata(self): data, addr = self.s.recvfrom(1024) return data def netThread(): netudp = NetUdp() while True: data = netudp.recvdata() frame.ParseAndDisplay(data) if __name__ == '__main__': firstrun = 0 app = wx.PySimpleApp() frame = MyFrame() frame.Show() # start network thread first id = thread.start_new_thread(netThread, ()) # main wxpython loop begins app.MainLoop() I know the code is ugly, but can anyone really save me here! From mail at timgolden.me.uk Mon Sep 10 12:06:13 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 10 Sep 2007 17:06:13 +0100 Subject: Silent SaveAs when using the Excel win32com module In-Reply-To: <1189439861.200686.245420@k79g2000hse.googlegroups.com> References: <1189439861.200686.245420@k79g2000hse.googlegroups.com> Message-ID: <46E56B75.7030301@timgolden.me.uk> Chris wrote: > I'm trying to create an excel file which will act as a log, however I > want to overwrite the file if it exists. > > Looking at the SaveAs method I can't find anything that would allow > it. I don't want the prompt to appear to ask whether to replace the > file or not. I just want to replace it without thinking. xl.DisplayAlerts = 0 where xl is the Application object. TJG From dhanlen at owt.com Tue Sep 11 23:54:42 2007 From: dhanlen at owt.com (Don Hanlen) Date: Tue, 11 Sep 2007 20:54:42 -0700 Subject: Basic GUI Message-ID: <1189569282.372083.264560@57g2000hsv.googlegroups.com> I'm writing a simple GUI that: ..gets info via telnet protocol (and sends) ..gets info via http (and sends) ..gets user-info from (currently) ...Tkinter Text windoze ...Tkinter buttons and such ..displays info in various Tkinter windoze ...graphic AND text... I can accomplish all of these functions individually and now seem to need to set up multi-processes to combine 'em. Back in my C days, I'd have used fork/exec to do so, but I'm confused by the number of modules available in Python. Is there a "best" for portability and simplicity? (Or am I on the wrong track here?) I could solve my problems with the following psuedo-code made into real code: ---- import blah t = blah.fork(runthisprogram.py) #OK still in main t.sendinfo(info) info = t.receiveinfo() ---- #runthisprogram.py def sendinfobacktopapa(): ? eventhere def getinfofrompapa(): ? eventhere ---- It seems to me that propagating events *may* be the best way to communicate. I'm wide open, including to non-multi-process solutions. Thanks for your comments, I searched old posts for a while, various other Python info-sources, and couldn't find an answer. -- don From steven.bethard at gmail.com Fri Sep 7 16:54:15 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Sep 2007 14:54:15 -0600 Subject: Is a Borg rebellion possible? (a metaclass question) In-Reply-To: References: <1189168282.665210.260840@19g2000hsx.googlegroups.com> <1189180478.257790.60160@g4g2000hsf.googlegroups.com> Message-ID: Carsten Haese wrote: > Indeed, if you have an __init__ method that shouldn't see the "group" > argument, you need a metaclass after all so you can yank the "group" > argument between __new__ and __init__. The following code seems to work, > but it's making my brain hurt: > > class SplinterBorgMeta(type): > def __call__(cls, *args, **kwargs): > inst = cls.__new__(cls, *args, **kwargs) > kwargs.pop("group",None) > inst.__init__(*args,**kwargs) > return inst > > class SplinterBorg(object): > __metaclass__ = SplinterBorgMeta > _shared_states = {} > def __new__(cls, *a, **k): > group = k.pop("group","BORG") > obj = object.__new__(cls, *a, **k) > obj.__dict__ = cls._shared_states.setdefault(group,{}) > return obj > > class MyClass(SplinterBorg): > def __init__(self, name): > self.name = name > I think I would probably write that as:: >>> class SplinterBorgMeta(type): ... def __init__(cls, name, bases, bodydict): ... cls._shared_states = {} ... def __call__(cls, *args, **kwargs): ... group = kwargs.pop('group', None) ... inst = cls.__new__(cls, *args, **kwargs) ... inst.__dict__ = cls._shared_states.setdefault(group, {}) ... inst.__init__(*args, **kwargs) ... return inst ... >>> class MyClass(object): ... __metaclass__ = SplinterBorgMeta ... def __init__(self, name): ... self.name = name ... >>> a = MyClass('a') >>> aa = MyClass('aa') >>> b = MyClass('b', group='b') >>> bb = MyClass('bb', group='b') >>> a.name, aa.name, b.name, bb.name ('aa', 'aa', 'bb', 'bb') That is, I don't think there's really a need for __new__ if you're using a metaclass. Just set the instance's __dict__ in the __call__ method of the metaclass. STeVe From rw at smsnet.pl Fri Sep 14 16:55:33 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 14 Sep 2007 22:55:33 +0200 Subject: why does Configparser change names to lowercase ? References: Message-ID: <87ejh1ezlm.fsf@merkury.smsnet.pl> stef mientki writes: > hello, > > Why does Configparser change names to lowercase ? > > As Python is case sensitive (which btw I don't like at all ;-) > but now when really need the casesensitivity, > because it handles about names which should be recognized by human, > it changes everything to lowercase ???? I don't know why, but I know how to change it and I found the solution here: http://docs.python.org/lib/RawConfigParser-objects.html You need to change the implementation of method `optionxform`, e.g.: # config [section1] option1=item1 Option2=item2 option2=item3 # cfg.py from ConfigParser import ConfigParser config = ConfigParser() config.optionxform = str config.read('config') print config.get('section1', 'option1') print config.get('section1', 'Option2') print config.options('section1') HTH, Rob From m.n.summerfield at googlemail.com Wed Sep 12 03:33:45 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Wed, 12 Sep 2007 07:33:45 -0000 Subject: An ordered dictionary for the Python library? Message-ID: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> I feel that Python lacks one useful data structure: an ordered dictionary. I find such data structures v. useful in C++. I know that in Python the sort function is v. fast, but often I prefer never to sort but simply to use an ordered data structure in the first place. (I'm aware that for ordered lists I can use the bisect module, but I want an ordered key-value data structure.) I think other people must find such things useful. There are three implementations on the Python Cookbook site, and one on PyPI, all in pure Python (plus I have my own implementation, also pure Python). I would suppose that it would be better if it was implemented in C--- for example, my own pure Python ordered dict loads data about eight times slower than the built-in dict. Nonetheless, I still find it worth using for the convenience it offers. Do other Python programmers feel this lack? Is this worth a PEP? [I originally asked about this on the P3K mailing list, but then realised that it isn't version-specific really.] From steve at holdenweb.com Thu Sep 6 16:49:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Sep 2007 13:49:51 -0700 Subject: parsing long `To' and 'Cc' from email In-Reply-To: <46E06244.80308@fmed.uba.ar> References: <46E06244.80308@fmed.uba.ar> Message-ID: Gerardo Herzig wrote: > Hi all. Im trying to develop yet another email filter. Just for fun for > now. Im having a little trouble parsing long 'To' and 'Cc' headers. > Sometimes p.e. the 'To' header comes like > > 'account1 at site.com, account at site2.com' > others comes like > '"My self" , "My brother" ', > other times a \r\t comes inside the `To' header. And any combination of > the above mentioned (and shurely more) can ocur. > > the email.* package dont seems to parse that kind of headers > `correctly'. What i want is to get a list with all the email address in > the `To' header. > > Someone know if there is a more sofisticated parser for doing this? > Have you tried using email.utils.getaddresses()? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From robin at reportlab.com Tue Sep 18 13:10:14 2007 From: robin at reportlab.com (Robin Becker) Date: Tue, 18 Sep 2007 18:10:14 +0100 Subject: can Python be useful as functional? In-Reply-To: References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Message-ID: <46F00676.4010406@chamonix.reportlab.co.uk> Steve Holden wrote: > Lorenzo Stella wrote: ...... > So, which environment do you habitually use that provides an *unlimited* > stack? > > You remind me of the conversation between the philosopher and an > attractive lady whom he was seated next to at dinner. He asked her if > she would sleep with him for a million dollars, to which she readily > agreed. So he followed this by asking her if she'd sleep with him for a > dollar. She replied: "No. Do you take me for a prostitutte?", to which > his riposte was "We have already established that fact, and are now > merely haggling about the price". > allegedly G B Shaw (http://findarticles.com/p/articles/mi_qn4158/is_19980925/ai_n14182408) -- Robin Becker From toby at tobiah.org Thu Sep 6 14:56:20 2007 From: toby at tobiah.org (Tobiah) Date: Thu, 06 Sep 2007 11:56:20 -0700 Subject: interesting puzzle......try this you will be rewarded... In-Reply-To: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> Message-ID: <46e04138$0$16377$88260bb3@free.teranews.com> My adblock extension must be doing a great job. I don't see any ads. The puzzle is fun really, but I'm stuck right now at 'eeiigg'. Renu wrote: > Hi, > > Just click on this link n use ur common sence to navigate. > > It has 23 pages one after the other, starting from this first > > Page. > The trick is to find a way to go to the next page. > > If u can really go to the 23rd page ur a genius in ur own respect :) > > So best of luck n keep clicking, tik tik.... > > http://iamhere.50webs.com > -- Posted via a free Usenet account from http://www.teranews.com From sjmachin at lexicon.net Wed Sep 5 07:34:07 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 05 Sep 2007 04:34:07 -0700 Subject: Looping through File Question In-Reply-To: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> References: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> Message-ID: <1188992047.858695.174790@r34g2000hsd.googlegroups.com> On Sep 5, 8:58 pm, planetmatt wrote: > I am a Python beginner. I am trying to loop through a CSV file which > I can do. What I want to change though is for the loop to start at > row 2 in the file thus excluding column headers. > > At present I am using this statement to initiate a loop though the > records: > > for line in f.readlines(): > > How do I start this at row 2? The quick answer to your literal question is: for line in f.readlines()[1:]: or, with extreme loss of elegance, this: for lino, line in enumerate(f.readlines()): if not lino: continue But readline and readlines are old hat, and you wouldn't want to read a file of a few million lines into a big list, so a better answer is: _unused = f.next() for line in f: But you did say you were reading a CSV file, and you don't really want to do your own CSV parsing, even if you think you know how to get it right, so best is: import csv rdr = csv.reader(f) heading_row = rdr.next() for data_row in rdr: HTH, John From http Sat Sep 1 03:09:36 2007 From: http (Paul Rubin) Date: 01 Sep 2007 00:09:36 -0700 Subject: ANN: SCF released GPL References: <2qnAi.21495$eY.19028@newssvr13.news.prodigy.net> <7x3ay5d1mn.fsf@ruckus.brouhaha.com> Message-ID: <7xhcmen9ov.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > > Does it have to be SVN? I think Savannah and Sourceforge both still > > use CVS. > Why would you want to use CVS rather than Subversion? Those sites have been around since before SVN. CVS was what was available, so they used it. Using CVS for something new would be silly, of course. From mh at pixar.com Wed Sep 12 16:52:30 2007 From: mh at pixar.com (mh at pixar.com) Date: Wed, 12 Sep 2007 20:52:30 GMT Subject: compiling an extension for several versions of python Message-ID: I don't have access to site-packages, but I would like to provide versions of my c-language package compiled against python 2.4 and 2.5. I "own" a library directory which is included in our site's sys.path. Currently this is where the 2.4 shared libary is installed. What's the most canonical way of doing this? This is on linux. Many TIA! Mark -- Mark Harrison Pixar Animation Studios From arkanes at gmail.com Thu Sep 13 10:46:50 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 13 Sep 2007 09:46:50 -0500 Subject: Possible suggestion for removing the GIL In-Reply-To: <1189694267.608577.288290@r34g2000hsd.googlegroups.com> References: <1189657576.772108.136550@d55g2000hsg.googlegroups.com> <5ksb3mF5828oU1@mid.uni-berlin.de> <1189694267.608577.288290@r34g2000hsd.googlegroups.com> Message-ID: <4866bea60709130746t121a04a3x3b15a0a8b2490410@mail.gmail.com> On 9/13/07, Prateek wrote: > On Sep 13, 1:36 pm, "Diez B. Roggisch" wrote: > > Prateek wrote: > > > Hi, > > > > > Recently there was some talk on removing the GIL and even the BDFL has > > > written a blog post on it. > > > I was trying to come up with a scalable and backwards compatible > > > approach for how to do it. > > > > > I've put my thoughts up in a blog post - and I'd really like to hear > > > what the community thinks of it. > > > Mainly it revolves around dedicating one core for executing > > > synchronized code and doing context switches instead of acquiring/ > > > releasing locks. > > > > Where is the gain? Having just one core doesn't give you true parallelism - > > which is the main reason behind the cries for a GIL-less Python. > > > > Diez > > Diez, > > I was talking of dedicating one core for synchronized code. In the > case of a threaded app on two cores, one core would be dedicated to > synchronized code and the other would run non-sync code (effectively > behaving like a single threaded machine). However, on machines with n > cores where n > 2 cores, we would have n-1 cores available to run code > in parallel. > What you're describing would have the same characteristics as the current code - code that is able to execute without the GIL held already will run in parallel on a multi-core machine. From chris.olekas at gmail.com Tue Sep 11 13:29:32 2007 From: chris.olekas at gmail.com (Chris) Date: Tue, 11 Sep 2007 10:29:32 -0700 Subject: Excel process still running after program completion. In-Reply-To: <1189531603.894247.218710@r29g2000hsg.googlegroups.com> References: <1189525558.721174.198370@19g2000hsx.googlegroups.com> <1189531603.894247.218710@r29g2000hsg.googlegroups.com> Message-ID: <1189531772.257865.292510@k79g2000hse.googlegroups.com> On Sep 11, 1:26 pm, Chris wrote: > On Sep 11, 12:59 pm, "Hamilton, William " wrote: > > > > > > From: Chris > > > > I have a python script that is driving Excel and using the win32com > > > module. However, upon program completion there's still an Excel.exe > > > process running in the background that I must terminate through Task > > > Manager. Reading up on other threads indicate that maybe I still have > > > some Excel objects referenced within my code. Is this why the process > > > doesn't terminate? > > > > The related (I hope) parts of my code is here. > > > > x1App = Dispatch("Excel.Application") > > > Book1 = x1App.Workbooks.Open(ExcelLogPath+"\\outputLog-template.xls") > > > x1App.Visible = 1 > > > for sheets in Book1.Worksheets: > > > if sheets.Name == file_name: > > > sheetExists = True > > > if sheetExists != True: > > > activeSheet = > > > Book1.Worksheets.Add(After=Book1.Worksheets(1)) > > > activeSheet.Name = file_name > > > testNum[file_name] = 0 > > > Book1.Worksheets(file_name).Select() > > > Book1.ActiveSheet.Cells(1+(testNum[file_name]*20),1).Value = "Original > > > File Name" > > > Book1.ActiveSheet.Cells(2+(testNum[file_name]*20),1).Value = > > > file_name > > > Book1.ActiveSheet.Pictures().Insert(output).Select() > > > Book1.SaveAs(Filename=path) > > > x1App.ActiveWorkbook.Close(SaveChanges=0) > > > x1App.Quit() > > > del x1App > > > del Book1 > > > del activeSheet > > > > What am I missing? > > > In my Excel projects, I terminate it with: > > > xlBook.Close() > > xlApp.Quit() > > > I haven't had a problem with Excel staying open after the program ends. > > > (On a tangent, I want to find the person who thought it was a good idea > > to use the same symbol in a font for 1, l, and I and do some unpleasant > > things.) > > > -- > > -Bill Hamilton > > That doesn't really fix the problem as I'm pretty sure its identical > code for > x1App.ActiveWorkbook.Close(SaveChanges=0) > > I think where my problem lies is within my for each loop where I > search to see if the worksheet with the name already exists > for sheets in Book1.Worksheets: > if sheets.Name == file_name: > sheetExists = True > > Since I'm assuming that it creates objects for each of the sheets and > I don't delete them... Which I'm right... I added this code and now there's no EXCEL.EXE process after my script completes for sheets in Book1.Worksheets: if sheets.Name == file_name: sheetExists = True sheets = None del sheets From exarkun at divmod.com Tue Sep 4 08:35:53 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 4 Sep 2007 08:35:53 -0400 Subject: Python is overtaking Perl In-Reply-To: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> Message-ID: <20070904123553.8162.1505839180.divmod.quotient.3578@ohm> On Tue, 04 Sep 2007 00:32:23 -0000, Ben wrote: >Here are the statistics from Google Trends: > >http://benyang22a.blogspot.com/2007/09/perl-vs-python.html > >From the graph, it seems more accurate to say that Perl is undertaking Python. Jean-Paul From Digvijoy.C at gmail.com Wed Sep 5 23:08:30 2007 From: Digvijoy.C at gmail.com (digz) Date: Thu, 06 Sep 2007 03:08:30 -0000 Subject: Python is overtaking Perl In-Reply-To: References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> <1188925214.716404.219920@22g2000hsm.googlegroups.com> Message-ID: <1189048110.057158.108750@g4g2000hsf.googlegroups.com> On Sep 4, 1:53 pm, "OKB (not okblacke)" wrote: > George Sakkis wrote: > > On Sep 4, 8:35 am, Jean-Paul Calderone wrote: > >> On Tue, 04 Sep 2007 00:32:23 -0000, Ben > >> wrote: > >> >Here are the statistics from Google Trends: > > >> >http://benyang22a.blogspot.com/2007/09/perl-vs-python.html > > >> >From the graph, it seems more accurate to say that Perl is > >> >undertaking Python. > > >> Jean-Paul > > > And to make it even more accurate, "Perl is undertaking Python in > > India", since that's where the difference in favor of Python comes > > from. > > No, it's the other way around. The big difference in India is in > favor of Perl. > I guess India is a big leader in perl coz all the decades old perl scripts are maintained in India. US Corporations have outsourced fixing/changing 80s-90s perl code to India. From Shawn at Milochik.com Wed Sep 19 14:31:56 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 19 Sep 2007 14:31:56 -0400 Subject: Finding prime numbers In-Reply-To: <1190225821.182650.227540@k79g2000hse.googlegroups.com> References: <1190218927.7991.25.camel@apprentice-laptop> <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> <1190219929.7991.28.camel@apprentice-laptop> <2dc0c81b0709191013k181d1a74m76a08cecadb005c4@mail.gmail.com> <1190225821.182650.227540@k79g2000hse.googlegroups.com> Message-ID: <2dc0c81b0709191131l3daa1507uf5efa79afd7b75ee@mail.gmail.com> > If you'd just search the archives, you would have found this: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/b134b2235e9c19a6/34857fb0b0b2a4b5?lnk=gst&q=prime+number&rnum=1#34857fb0b0b2a4b5 Yeah, but that's no fun. ;o) From horpner at yahoo.com Tue Sep 4 08:15:59 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 04 Sep 2007 12:15:59 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <5jn9qgFdmbcU3@mid.uni-berlin.de> <1188886461.236237.168230@y42g2000hsy.googlegroups.com> Message-ID: On 2007-09-04, Campbell Barton wrote: > Jason wrote: >> Returning -1 is not a good return value to indicate an error. >> After all, -1 is a valid index in most Python lists. >> (Negative numbers index from the tail of the list.) > > Agree in general tho its a bit inconsistent how... > > "string".find(val) > > ...can return -1 but .index() cant, though the inconsistency is > probably with string since most other areas of the py api raise > errors in cases like this. The two functions have different ranges, but also different domains. sequence.index domain: any item '==' to an item in sequence range: All non-negative indexes of sequence string.find domain: any string range: -1 for not found, and all non-negative indexes of string. If you want to search for subsequences in a sequence, a la string.find, you can use something like (what I naively assume will be a maximally efficent): def find(seq, subseq): """ Find a subsequence of seq in seq, and return its index. Return -1 if subseq is not found. >>> seq = [0, 1, 2, 3, 4, 5] >>> find(seq, [0, 1, 2]) 0 >>> find(seq, []) 0 >>> find(seq, [3, 4]) 3 >>> find(seq, [3, 2]) -1 >>> find(seq, [5, 6]) -1 >>> find(seq, [3]) 3 >>> find(seq, [0, 2]) -1 """ i = 0 j = 0 while i < len(seq) and j < len(subseq): if seq[i] == subseq[j]: j += 1 else: j = 0 i += 1 if j == len(subseq): return i - j else: return -1 It's probable that a simpler implementation using slice operations will be faster for shortish lengths of subseq. It was certainly easier to get it working correctly. ;) def find(seq, subseq): for i, j in itertools.izip(xrange(len(seq)-len(subseq)), xrange(len(subseq), len(seq))): if subseq == seq[i:j]: return i return -1 -- Neil Cerutti I pulled away from the side of the road, glanced at my mother-in-law and headed over the embankment. --Insurance Claim Blooper From mark at streamservice.nl Tue Sep 11 16:13:19 2007 From: mark at streamservice.nl (Stream Service || Mark Scholten) Date: Tue, 11 Sep 2007 22:13:19 +0200 Subject: Python.org mirror Message-ID: Dear sir, madam, Stream Service would be happy to provide a free mirror for python.org. We also host nl.php.net for free and we are happy to support more opensource websites with free hosting. Could you inform me about the options to become an officiel python.org mirror? With kind regards, Met vriendelijke groet, Mark Scholten Stream Service Web: http://www.streamservice.nl/ E-mail: mark at streamservice.nl NOC: http://www.mynoc.eu/ NOC e-mail: noc at streamservice.nl Tel.: +31 (0)642 40 86 02 Fax: +31 (0)20 20 101 57 KVK: 08141074 BTW: NL104278274B01 -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Sep 24 07:42:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Sep 2007 13:42:05 +0200 Subject: rules from an xml file References: <1190633685.275142.264540@r29g2000hsg.googlegroups.com> Message-ID: <5lpm4dF93534U1@mid.uni-berlin.de> jonny wrote: > I have a python code that manages some parameters using some variable > rules that may change from day to day. I'd like that the code will > self-modify according to rules parsed from a xml file: > > example: > > > > > > > > > > > > > > > > > > > Something is wrong! > > > ... > ... > > > Due to the fact that rules may change, I have to manage the python > program, parsing the whole xml file, and self-modify the python code > according to these variable rules. > How can I do? So, essentially you are creating a dynamic language? But you already have one - python! Who's responsible for creating these rules, and what do they allow to be done? Because I'd rather use python snippets to define them, that you compile using the exec-function. If you insist on using XML, use some module like lxml to parse and create your own language constructs. Just a note: the use of "par_X" as attributes is unfortunate, to say the least. It doesn't allow for easy argument swapping, can cause troubles because you delete one attribute and miss renaming the others, and in general it's not good design to have arbitrary numbers of parameters. Instead, you better go with a nested param-tag. Diez From trekker182 at comcast.net Thu Sep 27 15:19:32 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Thu, 27 Sep 2007 15:19:32 -0400 Subject: ValueError: too many values to unpack,>>> In-Reply-To: References: <5m24sfFatlbuU1@mid.uni-berlin.de> <46FBED79.6070207@comcast.net> Message-ID: <46FC0244.4010803@comcast.net> Fredrik Lundh wrote: > Shawn Minisall wrote: > > >> Sorry, it looks like it's on the fourth line with the 3 values on line >> 4...its reading line 3 fine >> >> Traceback (most recent call last): >> File "", line 1, in >> main() >> File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line 33, >> in main >> deposit1, deposit2, deposit3 = string.split(line, "\t") >> ValueError: too many values to unpack >> > > instead of fumbling around in the dark, try inserting a print statement > before the offending line, so you can see what you're trying to unpack: > > print string.split(line, "\t") # see what it is > deposit1, deposit2, deposit3 = string.split(line, "\t") > > > I did and it printed everything up until the 3rd line with 3 numbers for deposits. I have since figured it out...the teacher put in an extra tab after the last value so python thought it was 4 values for three. I went back into the file and deleted the extra tab after the 3rd number and saved it...now it's working fine. I'm going to kill her... ;) From exhuma at gmail.com Thu Sep 20 05:08:26 2007 From: exhuma at gmail.com (exhuma.twn) Date: Thu, 20 Sep 2007 02:08:26 -0700 Subject: Using python to create windows apps that everyone can use? In-Reply-To: <1190231182.174676.306980@r29g2000hsg.googlegroups.com> References: <7C008A37566.00000D2Atomharding@inbox.com> <1190231182.174676.306980@r29g2000hsg.googlegroups.com> Message-ID: <1190279306.582361.272730@19g2000hsx.googlegroups.com> On Sep 19, 9:46 pm, Simon Hibbs wrote: > On 9/18/07, Thomas Harding wrote: > > > Hi guys, sorry to post another topic on this, as I am aware that it > has > > already been posted a few times, but not with specifically what I > am looking > > for. I want an app that makes a gui interface for python (similar > to > > Microsoft visual studio or qt designer, not a code based one) and/ > or an app > > that can make this into a .exe that can be opened by any person on > any > > computer without python installed. > > For windows only, there's always Iron Python. This allows you to use > Visual Studio, the commercial or the express version, to create the > GUI in VB or C# and from that call Python code that does all the heavy > lifting. Any pointers to that. I might have to get started soon with Visual Studio, as our company *might* move to an all-windows development environment.... *sigh* /me still hopes that I can convince them that 1) developing on Linux is at all not too shabby, and that 2) Python is a great Language! ;) So far I am making good progress on point 2. :) > > I'd second the recommendation for QtDesigner if you want cross- > platform capability. > > Simon Hibbs From hiten at biochem.ucsf.edu Tue Sep 4 00:33:43 2007 From: hiten at biochem.ucsf.edu (Hiten Madhani) Date: Mon, 03 Sep 2007 21:33:43 -0700 Subject: scipy.org website Message-ID: <46DCE027.1010708@biochem.ucsf.edu> Hi, The scipy.org website has been down. Does anyone know whether it is coming back up? Hiten Madhani From earnclick at gmail.com Thu Sep 13 10:13:14 2007 From: earnclick at gmail.com (earnclick at gmail.com) Date: Thu, 13 Sep 2007 07:13:14 -0700 Subject: Get unlimited visitors to your website Message-ID: <1189692794.296572.158700@r34g2000hsd.googlegroups.com> Is your website getting very less no. of visitors .If so, then post your website to http://goodtolove.com to get unlimited visitors for lifetime...No need to pay a penny. From bj_666 at gmx.net Fri Sep 28 13:01:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Sep 2007 17:01:55 GMT Subject: Python 3.0 migration plans? References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> <1190997769.002795.59450@57g2000hsv.googlegroups.com> Message-ID: <5m4qc2Fbbk19U1@mid.uni-berlin.de> On Fri, 28 Sep 2007 09:42:49 -0700, TheFlyingDutchman wrote: > Which of the common languages have higher order functions and what is > the syntax? C, C++, Pascal, Perl, PHP, Ruby have them. And of course the functional languages, most notably Lisp and Scheme as you asked for common languages. Don't know if C#'s delegates qualify. Ciao, Marc 'BlackJack' Rintsch From paddy3118 at googlemail.com Fri Sep 14 16:49:00 2007 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 14 Sep 2007 20:49:00 -0000 Subject: regexp search on infinite string? Message-ID: <1189802940.518794.129130@r29g2000hsg.googlegroups.com> Lets say i have a generator running that generates successive characters of a 'string' >From what I know, if I want to do a regexp search for a pattern of characters then I would have to 'freeze' the generator and pass the characters so far to re.search. It is expensive to create successive characters, but caching could be used for past characters. is it possible to wrap the generator in a class, possibly inheriting from string, that would allow the regexp searching of the string but without terminating the generator? In other words duck typing for the usual string object needed by re.search? - Paddy. From laurent.pointal at limsi.fr Wed Sep 12 03:20:04 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 12 Sep 2007 09:20:04 +0200 Subject: Get the complete command line as-is In-Reply-To: <1189566000.793354.308420@19g2000hsx.googlegroups.com> References: <1189566000.793354.308420@19g2000hsx.googlegroups.com> Message-ID: wangzq a ?crit : > Hello, > > I'm passing command line parameters to my browser, I need to pass the > complete command line as-is, for example: > > test.py "abc def" xyz > > If I use ' '.join(sys.argv[1:]), then the double quotes around "abc > def" is gone, but I need to pass the complete command line ("abc def" > xyz) to the browser, how can I do this? > > I'm on Windows. As Windows command-line parsing seem to remove some chars, maybe you can try to use the GetCommandLine() function from Win32 API (I dont know if it is available in pywin32 package - you may need to write a wrapper with ctypes). See http://msdn2.microsoft.com/en-us/library/ms683156.aspx A+ Laurent. From fakeaddress at nowhere.org Tue Sep 25 05:20:11 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 25 Sep 2007 09:20:11 GMT Subject: Google and Python In-Reply-To: <7xejgr68pm.fsf@ruckus.brouhaha.com> References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> <7xejgr68pm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > You can also pass the open sockets around between processes instead of > reverse proxying, using the SCM_RIGHTS message on Unix domain sockets > under Linux, or some similar mechanism under other Unixes (no idea > about Windows). Python does not currently support this but one of > these days I want to get around to writing a patch. Windows can do it, but differently. What a surprise. I just looked it up: WSADuplicateSocket() is the key. Windows and Unix modules with the same Python interface would rock. -- --Bryan From bj_666 at gmx.net Thu Sep 27 12:47:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Sep 2007 16:47:13 GMT Subject: True of False References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> Message-ID: <5m254hFatlbuU2@mid.uni-berlin.de> On Thu, 27 Sep 2007 09:33:34 -0700, koutoo wrote: > I tried writing a true and false If statement and didn't get > anything? I read some previous posts, but I must be missing > something. I just tried something easy: > > a = ["a", "b", "c", "d", "e", "f"] > > if "c" in a == True: > Print "Yes" > > When I run this, it runs, but nothing prints. What am I doing wrong? Wow that's odd: In [265]: a = list('abcdef') In [266]: a Out[266]: ['a', 'b', 'c', 'd', 'e', 'f'] In [267]: 'c' in a Out[267]: True In [268]: 'c' in a == True Out[268]: False In [269]: ('c' in a) == True Out[269]: True In [270]: 'c' in (a == True) --------------------------------------------------------------------------- Traceback (most recent call last) /home/bj/ in () : argument of type 'bool' is not iterable What's going on there? Ciao, Marc 'BlackJack' Rintsch From bdesth.quelquechose at free.quelquepart.fr Mon Sep 17 18:13:37 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 00:13:37 +0200 Subject: Newbie question In-Reply-To: <1190140395.567419.16280@k79g2000hse.googlegroups.com> References: <1190139661.046103.45440@19g2000hsx.googlegroups.com> <1190140395.567419.16280@k79g2000hse.googlegroups.com> Message-ID: <46f01d0d$0$30530$426a34cc@news.free.fr> koutoo at hotmail.com a ?crit : > On Sep 18, 1:31 pm, "Shawn Milochik" wrote: > >>On 9/18/07, kou... at hotmail.com wrote: >> >> >>>If I have a file name: AVC1030708.14. How do I strip out certain >>>characters from the file name? I am so used to using MID, LEFT, and >>>RIGHT functions, that I have no idea how to do this in python? I have >>>had trouble as well with most newbies on finding the help. But I have >>>used the command line built in help, but with no luck. Thanks. >> >>>Kou >> >>Do you want to strip out specific characters, characters in specific >>positions, or characters matching certain patterns? > > > Yes, I want specific characters in specific positions. > Err... Sorry, but something is not clear here. When you say "strip out", you mean "get rid of", or "access to" ? For what I remember of basic, I guess it's the second answer, so: >>> fname = "AVC1030708.14" >>> print fname[0] A >>> print fname[-1] 4 >>> print fname[2:4] C1 >>> print fname[2:-4] C103070 >>> etc... Also and while we're at it, you also have: >>> fname.split('.') ['AVC1030708', '14'] >>> fname.split('.')[0] 'AVC1030708' >>> fname.split('.')[1] '14' >>> fname.strip('4') 'AVC1030708.1' >>> fname.strip('A') 'VC1030708.14' >>> fname.lstrip('A') 'VC1030708.14' >>> fname.rstrip('4') 'AVC1030708.1' >>> fname.rstrip('41.') 'AVC1030708' etc... HTH From sebastien.lannez at gmail.com Fri Sep 21 09:57:30 2007 From: sebastien.lannez at gmail.com (sebastien.lannez at gmail.com) Date: Fri, 21 Sep 2007 13:57:30 -0000 Subject: __contains__() and overload of in : Bug or Feature ??? Message-ID: <1190383050.514560.232660@50g2000hsm.googlegroups.com> Thanks for your quick response. > > I need to overload the operator in and let him > > return an object ... It seems it is not a > > behavior Python expect : > > > >>>> class A: > > ... def __contains__(self,a): > > ... return 'yop' > > ... > >>>> a=A() > >>>> print 'toto' in a > > True > >>>> print a.__contains__('toto') > > yop > > Not sure what you're trying to achieve, Using Python as an algebraic parser for symbolic mathematical equation and I need that the 'in' operator returns an object based on its two arguments. > but the semantics of the "in" operator > make it return a boolean value. That is why I need to overload it. > The string "yop" evaluates to the boolean > value True, as it is not empty. Does it means that when overloading an operator, python just wrap the call to the method and keep control of the returned values ??? Is there a way to bypass this wrapping ??? From grante at visi.com Wed Sep 19 12:58:40 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 19 Sep 2007 16:58:40 -0000 Subject: Embedding a executable inside Python Script References: Message-ID: <13f2la0dq3gm0bf@corp.supernews.com> On 2007-09-19, Shankarjee Krishnamoorthi wrote: > I have a exe made with py2exe for my Python routine. The issue > I am running into is this. All the exes (mycode.exe and > other_executable.exe) are placed in a Network drive(Say I:) so > that people can access it. > > When the user calls this from a Local Drice(Say C:) The output is like this > C:> I:\mycode.exe input_file other_executable_file.exe is not found..... The problem is that 'other_executable.exe' isn't in a directory that's on the current PATH. > Is there any way where I can circumvent this. Thanks Either set the PATH environment variable to include the directory where other_executable.exe is located or specify the complete path to other_executable.exe in your os.system() call. -- Grant Edwards grante Yow! I hope the at ``Eurythmics'' practice visi.com birth control ... From lasses_weil at klapptsowieso.net Sat Sep 1 05:22:28 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sat, 01 Sep 2007 11:22:28 +0200 Subject: So what exactly is a complex number? In-Reply-To: References: <451mq4-les.ln1@ozzie.tundraware.com> <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <46d92f54$0$4533$9b4e6d93@newsspool3.arcor-online.net> Lawrence D'Oliveiro wrote: > In message <46d89ba9$0$30380$9b4e6d93 at newsspool4.arcor-online.net>, Wildemar > Wildenburger wrote: > >> Tim Daneliuk wrote: >>> One of the most common uses for Complex Numbers is in what are >>> called "vectors". In a vector, you have both an amount and >>> a *direction*. For example, I can say, "I threw 23 apples in the air >>> at a 45 degree angle". Complex Numbers let us encode both >>> the magnitude (23) and the direction (45 degrees) as a "number". >>> >> 1. Thats the most creative use for complex numbers I've ever seen. Or >> put differently: That's not what you would normally use complex numbers >> for. > > But that's how they're used in AC circuit theory, as a common example. > OK, I didn't put that in the right context, I guess. The "magnitude and direction" thing is fine, I just scratched my head at the "23 apples at 45 degrees" example. Basically because I see no way of adding 2 apples at 16 degrees to 4 apples at 25 degrees and the result making any sense. Anyway, that was just humorous nitpicking on my side, don't take it too seriously :). /W From mcknight0219 at gmail.com Sun Sep 16 14:58:45 2007 From: mcknight0219 at gmail.com (Jimmy) Date: Sun, 16 Sep 2007 11:58:45 -0700 Subject: (curses) issue about inch() In-Reply-To: References: <1189955232.216664.167840@19g2000hsx.googlegroups.com> <1189960868.349377.249530@k79g2000hse.googlegroups.com> Message-ID: <1189969125.622966.112150@n39g2000hsh.googlegroups.com> On Sep 17, 2:25 am, Steve Holden wrote: > Jimmy wrote: > > On Sep 17, 12:07 am, Steve Holden wrote: > >> Jimmy wrote: > >>> hi, all > >>> I attempt to use the function inch() to get the character at the > >>> current position, and compare it with a particular character like : > >>> if screen.inch(x,y) == 'F' > >>> but this method doesn't seem work, can anyone tell me the reason and > >>> how to corrent it > >>> thanks > >> The reason is because something is wrong, and yo fix it by correcting > >> that issue. > > >> In other words, if you could be a bit more specific about *how* it > >> doesn't work (like, show us the code you are running,a nd any error > >> messages or evidence of incorrect results) you will be able to get some > >> help that actually helps you. > > >> Would you go to a car repair shop with faulty brakes and just tell them > >> "my car isn't working"? > > >> regards > >> Steve > >> -- > >> Steve Holden +1 571 484 6266 +1 800 494 3119 > >> Holden Web LLC/Ltd http://www.holdenweb.com > >> Skype: holdenweb http://del.icio.us/steve.holden > > >> Sorry, the dog ate my .sigline > > > thanks, > > actually i'm writing a game like mine,the pertainign code is: > > > def mark(): > > """mark the bomb""" > > (row, col) = gb.scrn.getyx() > > x = gb.scrn.inch(row,col) > > if x == 'F': > > gb.scrn.addch(row,col, 'X',curses.color_pair(3)) > > else: > > gb.scrn.addch(row,col, 'F',curses.color_pair(3)) > > > gb.scrn.move(row,col) > > gb.scrn.refresh() > > > the situation is x never equals 'F', even when it really is! > > I checked the mannual and found the return value of inch() consists > > the actual character(low 8bits) > > and the attributes, so I tried the following: (x<<24)>>24,cause I > > guess the int is 32bits long. > > but it still doesn't work :( > > Well first of all, thanks for reading the manual. > > Let's suppose the value you are receiving is 1234 (clearly more than 8 > bits). Unfortunately for you, recent versions of Python don't just use > 32-bit integers, but extend the values into Python's long values where > necessary. See: > > >>> (1234<<24)>>24 > 1234L > >>> > > What you really need is a logical and with 255: > > >>> 1234 & 255 > 210 > >>> > > Hope this helps. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline thanks, it works! python is cool, however, the python community is even cooler :) From kay.schluehr at gmx.net Sun Sep 23 02:07:22 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 22 Sep 2007 23:07:22 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> <1190454275.282176.90830@k79g2000hse.googlegroups.com> Message-ID: <1190527642.681501.18900@57g2000hsv.googlegroups.com> On 22 Sep., 23:17, Erik Max Francis wrote: > The attribute and method (not made distinct in Io; they're called > "slots") is much the same as with Python; the current instance is > checked for the object, then its parents, then _its_ parents, and so on. Repeating the same point as Marc doesn't mean that I have to repeat my reply as well. Doesn't it? From bj_666 at gmx.net Tue Sep 11 09:01:46 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Sep 2007 13:01:46 GMT Subject: memcpy References: <1189449530.171049.323230@22g2000hsm.googlegroups.com> <5klnsbF3vfqqU10@mid.uni-berlin.de> <1189512598.410810.224340@y42g2000hsy.googlegroups.com> Message-ID: <5knhtpF4b65dU6@mid.uni-berlin.de> On Tue, 11 Sep 2007 05:09:58 -0700, Tim wrote: > On Sep 10, 3:31 pm, Marc 'BlackJack' Rintsch wrote: >> On Mon, 10 Sep 2007 11:38:50 -0700, Tim wrote: >> > How do I memcpy from a pointer to an array of floats in python? >> >> > I get errors: NameError: global name 'row' is not defined >> >> Well than the (global) name `row` is not defined. Quite clear message, >> isn't it? ;-) >> >> > I want to be able to get the row[i] array element. In C I would >> > normally place the address of row as the first argument. >> >> > cdll.msvcrt.memcpy( row, pData, 256 ) >> >> > If I define row as the following I also get the following error: >> >> > row = ones( TOTAL_PARAMETER_ENTRIES, dtype=float ) >> >> > ArgumentError: argument 1: : Don't know >> > how to convert parameter 1 >> >> You don't give enough information so we have to guess. For example I >> guess the `ones()` function comes from one of the packages `numeric`, >> `numarray` or `numpy`!? >> >> This function returns a Python object. You can't use arbitrary Python >> objects with `ctypes`. `memcpy` expects a pointer not an object. > > Can I initialize something in Python that I can get access to it's > pointer? "It's pointer"? Then you have a pointer to a structure that represents the Python object but still no idea what data is at that pointer. This is an implementation detail of the Python version and of the particular object. > Here is what I would like to write: > > shared_memory_pointer = windll.kernel32.MapViewOfFile(hMapObject, > FILE_MAP_ALL_ACCESS, > 0, 0, TABLE_SHMEMSIZE) > > memcpy( self.data, shared_memory_pointer, my_size ) I haven't tested but it should be possible to declare the return type of `windll.kernel32.MapViewOfFile()` as ``ctypes.POINTER(ctypes.c_double * 256)`` and then do: test_data = numpy.ones(1000) shared_memory_pointer.contents[0:256] = test_data[0:256] Ciao, Marc 'BlackJack' Rintsch From dfedoruk at gmail.com Thu Sep 13 12:27:31 2007 From: dfedoruk at gmail.com (Dmitri Fedoruk) Date: Thu, 13 Sep 2007 16:27:31 -0000 Subject: lxml + mod_python: cannot unmarshal code objects in restricted execution mode In-Reply-To: <1189688758.587404.139360@r29g2000hsg.googlegroups.com> References: <1189688758.587404.139360@r29g2000hsg.googlegroups.com> Message-ID: <1189700851.771876.21350@g4g2000hsf.googlegroups.com> On Sep 13, 5:05 pm, Dmitri Fedoruk wrote: > So, my configuration is the following: > Python 2.5.1 > Server version: Apache/2.2.4 (FreeBSD) > mod_python-3.3.1 update: lxml-1.3.4 libxslt-1.1.21 libxml2-2.6.29 From mikael at isy.liu.se Mon Sep 24 04:40:53 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Mon, 24 Sep 2007 10:40:53 +0200 Subject: about __str__ In-Reply-To: <46f37540$0$16854$426a74cc@news.free.fr> References: <46f37540$0$16854$426a74cc@news.free.fr> Message-ID: <46F77815.1080007@isy.liu.se> Bruno Desthuilliers wrote: > def __str__(self): > return "<%s:%s>" % (self.commiterID_, self.commits_) I would write that in the following way: def __str__(self): return "<%(commiterID_)s:%(commits_)s>" % self.__dict__ More explicit IMHO. And easier to maintain, especially if the string would contain several insertions. /MiO From aleax at mac.com Sat Sep 1 19:57:00 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 1 Sep 2007 16:57:00 -0700 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <1i3ob5k.dm3jmoqx1z68N%aleax@mac.com> <5jtuabF16jr4U1@mid.uni-berlin.de> Message-ID: <1i3rtgi.9rbs05u5rx3gN%aleax@mac.com> Marc 'BlackJack' Rintsch wrote: > On Sat, 01 Sep 2007 13:44:28 -0600, Michael L Torrie wrote: > > > Alex Martelli wrote: > > > >> is the "one obvious way to do it" (the set(...) is just a simple and > >> powerful optimization -- checking membership in a set is roughly O(1), > >> while checking membership in a list of N items is O(N)...). > > > > Depending on a how a set is stored, I'd estimate any membership check in > > a set to be O(log N). > > Sets are stored as hash tables so membership check is O(1) just like Alex > said. "Roughly" O(1), as I said, because of the usual issues with cost of hashing, potential hashing conflicts, re-hashing (which requires thinking in terms of *amortized* big-O, just like, say, list appends!), etc, just like for any hash table implementation (though Python's, long used and finely tuned in dicts then adopted for sets, is an exceedingly good implementation, it IS possible to artificially construct a "worst case" -- e.g., set(23+sys.maxint*i*2+i for i in xrange(24,199))...) Alex From bbxx789_05ss at yahoo.com Sat Sep 15 18:32:48 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 15 Sep 2007 15:32:48 -0700 Subject: (wxPython) wx.ProgressDialog - how to cancel out of? In-Reply-To: References: Message-ID: <1189895568.251017.96460@22g2000hsm.googlegroups.com> On Sep 14, 11:57 pm, Terry Carroll wrote: > I'm trying to use wx.ProgressBar, and the cancel button is not > responding. > > Here is a simple program that exhibits the problem: > > ######################################################### > import wx > import time > > max = 10 > app = wx.PySimpleApp() > dlg = wx.ProgressDialog("Progress dialog example", > "variables to be shown here", > maximum = max, > style = wx.PD_CAN_ABORT > | wx.PD_CAN_SKIP > #| wx.PD_APP_MODAL > | wx.PD_ELAPSED_TIME > | wx.PD_ESTIMATED_TIME > | wx.PD_REMAINING_TIME > ) > > keepGoing = True > skip = False > count = 0 > > while keepGoing and count < max: > count += 1 > wx.MilliSleep(1000) > #time.sleep(1) > newtext = "(before) count: %s, keepGoing: %s, skip: %s " % \ > (count, keepGoing, skip) > print newtext > (keepGoing, skip) = dlg.Update(count, newtext) > newtext = "(after) count: %s, keepGoing: %s, skip: %s " % \ > (count, keepGoing, skip) > print newtext > dlg.Destroy() > ######################################################### > > The dialog looks right when this runs, but.... > > What's right: I get a progress bar; it includes "Skip" and "Cancel" > buttons; it shows 10 seconds of progress, and updates once per second > with the variables' values on each iteration. > > What's wrong is that I can't get clicking on the "Skip" or "Cancel" > buttons to have any effect. Instead, as soon as the dialog displays, > I get an hourglass, and it doesn't matter what I click on. Here's > what the print statements display, consistently, regardless of what I > try to click or whether I click nothing at all: > > I:\python>test1.py > (before) count: 1, keepGoing: True, skip: False > (after) count: 1, keepGoing: True, skip: False > (before) count: 2, keepGoing: True, skip: False > (after) count: 2, keepGoing: True, skip: True > (before) count: 3, keepGoing: True, skip: True > (after) count: 3, keepGoing: True, skip: True > (before) count: 4, keepGoing: True, skip: True > (after) count: 4, keepGoing: True, skip: True > (before) count: 5, keepGoing: True, skip: True > (after) count: 5, keepGoing: True, skip: True > (before) count: 6, keepGoing: True, skip: True > (after) count: 6, keepGoing: True, skip: True > (before) count: 7, keepGoing: True, skip: True > (after) count: 7, keepGoing: True, skip: True > (before) count: 8, keepGoing: True, skip: True > (after) count: 8, keepGoing: True, skip: True > (before) count: 9, keepGoing: True, skip: True > (after) count: 9, keepGoing: True, skip: True > (before) count: 10, keepGoing: True, skip: True > (after) count: 10, keepGoing: True, skip: True > > Two oddities here: > > 1) As I read the docs, the keepGoing variable should be set to True, > unless I click on "Cancel," in which case it should be set to False > (which would end the loop). That doesn't happen. This is really what > I'm most concerned here with. > > 2) The variable "skip: set to False on the first iteration, and then > set to True on subsequent iterations? Note that this happens even if > no buttons are selected. This is just a weirdness to me, and not my > main concern, but I thought I'd mention it in case it's relevant. > > You can see some variations in the commented-out code that I tried; > they did not help. > > Relevant software and releases: > > OS: Windows XP Home Edition, Version 2002, SP2 > Python: ActivePython 2.5.0.0 > wxPython: 2.8.1.1 (msw-unicode) > > Any help appreciated. Supposedly a progress dialog does not work well on its own because events get screwed up when there isn't a main loop. Try this: import wx app = wx.PySimpleApp() win = wx.Frame(None, -1, "Test Progress Dialog") button = wx.Button(win, -1, "start download") def on_button_click(evt): max = 10 dialog = wx.ProgressDialog( "Loading", "progress:", max, style = wx.PD_CAN_ABORT |wx.PD_ELAPSED_TIME |wx.PD_ESTIMATED_TIME |wx.PD_REMAINING_TIME ) keep_going = True skip = False count = 0 while keep_going and (count < max): count += 1 wx.MilliSleep(1000) (keep_going, skip) = dialog.Update(count) print skip dialog.Destroy() button.Bind(wx.EVT_BUTTON, on_button_click) win.Show() app.MainLoop() From tec at knology.net Mon Sep 10 11:21:24 2007 From: tec at knology.net (Tim) Date: Mon, 10 Sep 2007 08:21:24 -0700 Subject: shared memory pointer In-Reply-To: References: <1189436265.841415.234050@w3g2000hsg.googlegroups.com> Message-ID: <1189437684.476993.130390@g4g2000hsf.googlegroups.com> On Sep 10, 10:11 am, Tim Golden wrote: > Tim wrote: > > Hello Everyone, > > > I am getting shared memory in python using the following. > > > szName = c_char_p(name) > > hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE, > > None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName) > > if (hMapObject == 0): > > print "OpenKey: Could not open name file mapping object" > > raise WinError() > > > self.pData = windll.kernel32.MapViewOfFile(hMapObject, > > FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE) > > Without answering your question directly, why not use > the stdlib mmap module, which does exactly this for > you behind the scenes? > > Docs -http://docs.python.org/lib/module-mmap.html > Example -http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413807 > > TJG I saw the mmap function in the shared memory example. I had some concern with my large memory size being written to the disk drive. I though it might slow down my application. The reason I am writting this new code is because the existing method using a file. I thought shared memory would be much faster. I have tried using the memcpy and addresses, casting, etc. Is there a way to use memcpy with the pData returned by MapViewOfFile()? Thanks Tim From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 18 04:13:15 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 10:13:15 +0200 Subject: can Python be useful as functional? In-Reply-To: <1190073045.618869.261290@k79g2000hse.googlegroups.com> References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Message-ID: <46ef8895$0$21882$426a34cc@news.free.fr> Lorenzo Stella a ?crit : > Hi all, > I haven't experienced functional programming very much, but now I'm > trying to learn Haskell and I've learned that: 1) in functional > programming LISTS are fundmental; Not exactly. They are used quite a lot, yes, but that's also the case in other paradigms. What's important in functional programming is *functions*. > 2) any "cycle" in FP become > recursion. FP idioms tends to use recursion instead of iteration, yes. But that's only viable with implementations doing tail-recursion optimisation - which is not the case with CPython (not that it couldn't FWIW - it's a design choice, and one of the few I don't necessarily agree with). > I also know that Python got some useful tool such as map, filter, > reduce... And all there itertools versions... > so I told: "let's try some FP-style programming with > Python!". Most of the functional constructs that makes sens in Python are already idiomatic. And some common functional stuff are better reimplemented the pythonic way - as an example, while partial application is usually implemented with closures, and *can* indeed be implemented that way in Python, the class-based implementation is IMHO much better. > I took a little example of Haskell: > > listprimes :: Integer -> [Integer] > listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)] > where > sieve [] = [] > sieve (p:xs) = p : sieve (filter (\x -> mod x p > 0) xs) > > and I tried to "translate" it in Python: > > def sieve(s): > if s == []: > return [] > else: > return [s[0]] + sieve(filter((lambda x: x % s[0] > 0), > s[1:])) > > def listprimes(n): > return sieve(range(2,n)) > > These should be almost the same: listprimes actually lists prime > integers up to n-1. The result is: Haskell implementation works well, > maybe it's not the better way to do it, but it does what I wanted. > Python implementation gives me > > RuntimeError: maximum recursion depth exceeded in cmp > > My question is: how can we call a language "functional" if it's major > implementation has a limited stack? Or is my code wrong? Strictly speaking, a language is functional if it has functions as first class objects. Period. According to this definition, Python is a functional language. Now that doesn't mean you should try to write Haskell in Python... IOW, your code is not "wrong", but it's certainly not the best way to implement such an algorithm in Python. From koara at atlas.cz Sat Sep 22 11:57:30 2007 From: koara at atlas.cz (koara) Date: Sat, 22 Sep 2007 08:57:30 -0700 Subject: unicode categories -- regex Message-ID: <1190476650.222233.187800@57g2000hsv.googlegroups.com> Hello all -- my question regards special meta characters for the re module. I saw in the re module documentation about the possibility to abstract to any alphanumeric unicode character with '\w'. However, there was no info on constructing patterns for other unicode categories, such as purely alphabetical characters, or punctuation symbols etc. I found that this category information actually IS available in python -- in the standard module unicodedata. For example, unicodedata.category(u'.') gives 'Po' for 'Punctuation, other' etc. So how do i include this information in regular pattern search? Any ideas? Thanks. I'm talking about python2.5 here. From surekap at gmail.com Sun Sep 16 13:18:36 2007 From: surekap at gmail.com (Prateek) Date: Sun, 16 Sep 2007 10:18:36 -0700 Subject: Python Database Apps In-Reply-To: <1189713622.239555.164720@r29g2000hsg.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> <1189536987.259907.68650@e34g2000pro.googlegroups.com> <1189608814.932322.301950@22g2000hsm.googlegroups.com> <1189658282.646375.160150@19g2000hsx.googlegroups.com> <1189713622.239555.164720@r29g2000hsg.googlegroups.com> Message-ID: <1189963116.524203.34730@n39g2000hsh.googlegroups.com> On Sep 14, 1:00 am, Jonathan Gardner wrote: > On Sep 12, 9:38 pm, Prateek wrote: > > > Have you checked out Brainwave?http://www.brainwavelive.com > > > We provide a schema-free non-relational database bundled with an app > > server which is basically CherryPy with a few enhancements (rich JS > > widgets, Cheetah/Clearsilver templates). Free for non-commercial use. > > You might want to rethink how you are handling databases. What sets > your database apart from hierarchical or object-oriented databases? Do > you understand why people prefer relational databases over the other > options? There's a reason why SQL has won out over all the other > options available. You would do well to understand it rather than > trying out things we already know do not work. I didn't mention any details in my previous post. Basically, the Brainwave database is very similar to an RDF triple store which captures semantic information. There are some fundamental differences however, (e.g. a simplified API, no schema, ability to store objects by introspecting and breaking it up into its primitives etc.) In general, it works well if you're dealing with a lot of unstructured data or even semi-structured/structured data where the structure is constantly changing. Key areas of benefit are in terms of integrating legacy databases and also analytics heavy applications. This is because there is no concept of normalized/denormalized schemas so your data does not need to go through any structural transformations in preparation for OLAP use. Since we're new, I probably won't recommend using it with very very large data-sets. However, we've seen significant benefits with small and medium sized data-sets. At any rate, whatever you choose, you can import and export all data in CSV/XML at any time so your data is safe. Some of the benefits I have described above have been shown to be areas of concern when dealing with SQL stores. There is a lot of research and many opinion pieces available on this subject. I'd be happy to discuss any aspect with you further. Sorry for the delayed response. I've been in and around airplanes for the last 24 hours (and its not over yet). -Prateek From rcdailey at gmail.com Tue Sep 25 17:21:08 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 25 Sep 2007 16:21:08 -0500 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> Message-ID: <496954360709251421l578b9dfdwcc0e67d293ede1f3@mail.gmail.com> One thing I noticed is that it is placing an arbitrary space between " and />. For example: Notice that there's a space between "image" and /> Any way to fix this? Thanks. On 9/24/07, Gabriel Genellina wrote: > > En Mon, 24 Sep 2007 23:51:57 -0300, Robert Dailey > escribi?: > > > What I meant was that it's not an option because I'm trying to learn > > regular > > expressions. RE is just as built in as anything else. > > Ok, let's analyze what you want. You have for instance this text: > "" > which should become > "" > > You have to match: > (opening angle bracket)(any word)(closing angle bracket)(opening angle > bracket)(slash)(same word as before)(closing angle bracket) > > This translates rather directly into this regular expression: > > r"<(\w+)>" > > where \w+ means "one or more alphanumeric characters or _", and being > surrounded in () creates a group (group number one), which is > back-referenced as \1 to express "same word as before" > The matched text should be replaced by (opening <)(the word > found)(slash)(closing >), that is: r"<\1/>" > Using the sub function in module re: > > py> import re > py> source = """ > ... > ... > ... > ... > ... """ > py> print re.sub(r"<(\w+)>", r"<\1/>", source) > > > > > > > Now, a more complex example, involving tags with attributes: > --> > > You have to match: > (opening angle bracket)(any word)(any sequence of words,spaces,other > symbols,but NOT a closing angle bracket)(closing angle bracket)(opening > angle bracket)(slash)(same word as before)(closing angle bracket) > > r"<(\w+)([^>]*)>" > > [^>] means "anything but a >", the * means "may occur many times, maybe > zero", and it's enclosed in () to create group 2. > > py> source = """ > ... > ... > ... """ > py> print re.sub(r"<(\w+)([^>]*)>", r"<\1\2 />", source) > > > > > Next step would be to allow whitespace wherever it is legal to appear - > left as an exercise to the reader. Hint: use \s* > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.hankin at gmail.com Thu Sep 20 15:24:46 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 20 Sep 2007 19:24:46 -0000 Subject: A struct for 2.4 that supports float's inf and nan? In-Reply-To: <1190315989.268629.37520@22g2000hsm.googlegroups.com> References: <1190315989.268629.37520@22g2000hsm.googlegroups.com> Message-ID: <1190316286.963227.324260@57g2000hsv.googlegroups.com> Both str(f) should be str(a) in pack_one_safe. -- Paul Hankin From skulka3 at gmail.com Thu Sep 27 18:27:17 2007 From: skulka3 at gmail.com (Salil Kulkarni) Date: Thu, 27 Sep 2007 17:27:17 -0500 Subject: Streaming files from python cgi Message-ID: Hello, I am trying to create a cgi which downloads a pdf/tiff file from an ftpserver using ftplib. Everything works until this point. But, once the file has been retrieved, I want to be able to stream the file to the browser so that the user gets an option to save it, or open it with the necessary application. However, I am not able to figure out how this can be done. The code looks as follows: #!/usr/local/python2.1/bin/python import Path, cgi, sys, os from ftplib import FTP print "content-type: application/pdf\n\n" ftp = FTP("hostname", "salil", "passwd") try: ftp.cwd("/home/salil") except: print "Could change directory on remote server" sys.exit(1) f = open("temp.pdf", "w") ftp.retrbinary("RETR O_F.pdf", f.write) f.close() f = open("temp.pdf", "r") print f.read() I am using Apache 1.3 for this cgi. It would be great if someone can point out how this can be accomplished, or if there are any examples out there which I can refer to. Thanks, Salil. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 21 03:23:41 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 21 Sep 2007 09:23:41 +0200 Subject: An Editor that Skips to the End of a Def In-Reply-To: <874phou1pa.fsf@benfinney.id.au> References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <874phou1pa.fsf@benfinney.id.au> Message-ID: <46f3717e$0$29940$426a74cc@news.free.fr> Ben Finney a ?crit : > "W. Watson" writes: > >> Is vim just an editor or is it capable of running and debugging a >> program, as well? > > (Please don't top-post. Instead, reply below each point to which > you're responding, removing quoted text irrelevant to your response.) > > Both Emacs and Vim are highly customisable text editors. They are > configurable with complete programming languages specific to the > program, and both have a huge community of programmers writing useful > extensions. > > So, neither of them is "just an editor"; they are editors at their > core, that can become complete programming environments by taking > already-written components for them. FWIW, emacs has - a python-mode that let you run either your whole script or parts of it into a python shell - that of course stays open, so you can examine the state after execution etc... and it works just fine with pdb. - ECB (emacs-code-browser), that adds a file explorer and functions/classes inspector The combination gives you a full-blown IDE. From stefan.behnel-n05pAM at web.de Tue Sep 25 03:32:21 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 25 Sep 2007 09:32:21 +0200 Subject: Python script to optimize XML text In-Reply-To: References: <496954360709241336i43173947sda5245c2d7477ecb@mail.gmail.com> Message-ID: <46F8B985.7000803@web.de> Gabriel Genellina wrote: > En Mon, 24 Sep 2007 17:36:05 -0300, Robert Dailey > escribi?: > >> I'm currently seeking a python script that provides a way of >> optimizing out >> useless characters in an XML document to provide the optimal size for the >> file. For example, assume the following XML script: >> >> >> >> >> >> >> >> >> By running this through an XML optimizer, the file would appear as: >> >> > > ElementTree does that almost for free. As the OP is currently using lxml.etree (and as this was a cross-post to c.l.py and lxml-dev), I already answered on the lxml list. This is just to mention that the XMLParser of lxml.etree accepts keyword options to ignore plain whitespace content, comments and processing instructions, and that you can provide a DTD to tell it what whitespace-only content really is "useless" in the sense of your specific application. Stefan From jd at nospam.com Fri Sep 21 13:36:34 2007 From: jd at nospam.com (Jd) Date: Fri, 21 Sep 2007 10:36:34 -0700 Subject: threading.local _threading_local problems Message-ID: Hi I have the following situation.. Have a worker thread, that does the "work" given to it. While doing work, some of the objects use thread local storage for storing that requires explicit close. e.g. connection handles. These objects are long living. The worker, does not have any direct access to the objects. I would like to clean up thread local area explicitly so that I do not run out of connection handles. Any ideas on how to access local storage from the thread ? (threading.local() gives new object everytime.. I am looking for something like singleton / global access from within the thread) Or is there anyway to notify the object when the thread for which it set the local storage is going away ? This looks to me a bit like design shortcoming. or I have missed something completely. Thanks /Jd From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Sep 21 08:35:37 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 21 Sep 2007 14:35:37 +0200 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> Message-ID: <5lhs4pF8bkunU1@mid.individual.net> Lawrence D'Oliveiro wrote: > After two decades of putting up with vi just to ensure > compatibility with every proprietary *nix system I might come > across, let me just say ... > > USE EMACS! Nah. Use vim. > Oh, and > . Esc-Meta-Alt-Ctrl-Shift? :) Regards, Bj?rn -- BOFH excuse #418: Sysadmins busy fighting SPAM. From yosuke at ccwf.cc.utexas.edu Mon Sep 17 20:00:09 2007 From: yosuke at ccwf.cc.utexas.edu (yosuke at ccwf.cc.utexas.edu) Date: Tue, 18 Sep 2007 00:00:09 +0000 (UTC) Subject: class that keeps track of instances References: Message-ID: yosuke at ccwf.cc.utexas.edu wrote: > I want to have a class in my python application that does not allow > multiple instance with same "name". Thank you very much for very quick and precise answers to my questions! input for garbage collector and id are appreciated as well. I head to bookstore for the cookbook (O'reily's, right?). i thought it was too cryptic but maybe time for met to revisit the book. -- yosuke kimura Center for Energy and Environmental Resources The Univ. of Texas at Austin, USA From bj_666 at gmx.net Tue Sep 11 13:50:43 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Sep 2007 17:50:43 GMT Subject: Car-ac-systems References: <1189532573.728913.306470@g4g2000hsf.googlegroups.com> Message-ID: <5ko2rjF4om2bU1@mid.uni-berlin.de> On Tue, 11 Sep 2007 17:42:53 +0000, Zentrader wrote: > > What is it about "please do not top-post" that you have difficulty > understanding? Or do "MVP"s feel that their time is so much more > valuable than anyone else's that they are free to ignore the norms? > > Who made this the norm? Common sense and (western) reading habits. > In my travels through web-land, it appears to be the opposite. You must travel strange territories. ;-) > Don't waste space repeating everything in every post, and it wastes > everyone's time by have to go over the same thing again and again. That's why you trim the quoted part to the minimum to understand what one is answering. Top posting and full quoting wastes time for people who want to see the context because context and answer are way apart and in the wrong order so one has to scroll back and forth to keep track of the discussion. Ciao, Marc 'BlackJack' Rintsch From frgo at goenninger.net Sat Sep 29 06:54:32 2007 From: frgo at goenninger.net (Frank Goenninger) Date: Sat, 29 Sep 2007 12:54:32 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <13frd6vtarbee75@corp.supernews.com> Message-ID: On 2007-09-29 01:27:04 +0200, Damien Kick said: > Giorgos Keramidas wrote: >> On Fri, 22 Jun 2007 23:08:02 -0000, nebulous99 at gmail.com wrote: >>> So much for the "free" in "free software". If you can't actually use >>> it without paying money, whether for the software or for some book, it >>> isn't really free, is it? >> >> Please do not confuse the term 'free' in 'free software' with 'gratis'. >> >> 'Gratis', i.e. 'lacking a monetary price tag' is something *very* >> different from the meaning of 'free' in 'free software'. > > If you were referring to the "free" in "free Mumia Abu Jamal", I would > agree with you. I don't think anyone would imagine that this phrase > meant that someone was going to get Mumia Abu Jamal gratis. Like it or > not, "free software" referring to "free as in beer" is probably the > most common interpretation of the phrase for a native English speaker. > Admittedly, I do not have a "scientific" survey handy. However, I just > asked my wife--who has absolutely no interest in anything related to > programming, has never heard of the FSF, Eric Raymond, nor the > disagreement between those two camps, nor probably will she ever have > an interest--what she thinks I mean when I say "free software". After > getting over the "why are you asking such a stupid question" phase, the > first thing that jumped to her mind was "free as in beer". You can > stamp, growl, swagger, spit, curse, and bluster all you want on this > point, but millions of English speakers are going to ignore you anyway. > Lucky for most of them, they do not have to suffer the lectures of > sociopolitically motivated language mavens trying to "correct" them > from the error of mistaking the meaning of a phrase to be the normal > meaning of that phrase. Fully true for non-native English speakers as well. Just did the "wife test" also - she is a pure software user - and yes, free is "no money, do what you want" and that's it. I *never* use the term "free" if I don't want to imply "free beer" (which is a Good Thing and as such highly valuated - ask any Bavarian). Using "free" as by FSF or any other lawyer-style 6 pixel font printed phrasing is pure perfidiousness. Frank -- Frank Goenninger frgo(at)goenninger(dot)net "Don't ask me! I haven't been reading comp.lang.lisp long enough to really know ..." From kasimmominov at gmail.com Sat Sep 29 06:10:50 2007 From: kasimmominov at gmail.com (kasim) Date: Sat, 29 Sep 2007 10:10:50 -0000 Subject: 4000 every month Message-ID: <1191060650.145937.294850@y42g2000hsy.googlegroups.com> Zamanla ne kadar ?ok para kazanm??siniz kendiniz bile inanamiyacaksiniz. Bu ger?ektir. Hayal etti?iniz ?eyleri ger?ekle?tirebilirsiniz. Eyleme ge?mek d???nerek durmaktan daha iyidir. Bizde bir nakil var d???nen d???n?nceye kadar tevekk?l eden menzile varm??. Sizde hayal etti?iniz menzillere varabilirsiniz. Knedinize g?venin. Ben bunu yapabilirim. Arkada?lar?m? ?ye yapabilirim. ?imdiden sizleri kutlar?m siz bu mektubu almakla ?ansl?s?n?z. ??nk? sizing i?in bir yeni g?n ba?liyor.!!!!!!!!!!!!!!!!!!!!!!!! Allah s?reklili?in, alem ise yenili?in alan?d?r. Yeniden yaratma ile ortaya ??kan alem hareketin, olu?un ve ak???n alan?d?r. ?u halde hareket ve yenilik alemin ruhudur...Allah'ta aslonan vahdet, alemde aslolan kesrettir Davet linkiniz: http://www.superteklif.com/redirect.aspx?rid=dQDJb1CgiuY_____eql____ http://www.superteklif.com/redirect.aspx?rid=dQDJb1CgiuY_____eql____ http://www.superteklif.com/redirect.aspx?rid=dQDJb1CgiuY_____eql____ http://www.superteklif.com/redirect.aspx?rid=dQDJb1CgiuY_____eql____ S?perTeklif Nedir? E-maillerinizde, cep telefonlar?n?zda, TV'lerde, radyoda, metroda, sokakta... K?saca her g?n say?s?z reklamla kar?? kar??ya kal?yorsunuz. Ama kimse size para ?demiyor. Gelin ?imdi, g?rd???n?z her reklamdan para kazan?n! S?perTeklif'te; ? E-mailinize gelen reklam ve anketlerden, ? Cep telefonunuza gelen SMS reklamlar?ndan, ? Ev adresinize g?nderilen ?cretsiz promosyon ?r?nleri hakk?nda verece?iniz fikir ve g?r??lerden, ? Size ?nerece?imiz ve profilinize uygun web sitelerine ?ye olarak, ? ClubCard anla?mal? e-ticaret sitelerinden yapt???n?z al??veri?lerde, ? Sizin referans?n?zla ?ye olan arkada?lar?n?z?n g?rd??? t?m reklamlardan s?rekli Puan kazan?rs?n?z. Bu puanlar 100,000'e ula??nca da banka hesab?n?za hemen 100 YTL olarak yat?r?l?r. S?perTeklif'te Kazanmak ?ok Kolay! ?imdi ?ye olun, sadece ki?isel bilgilerinizi ve tercihlerinizi tamamlayarak hemen 5.000 Puan kazan?n! ?stelik S?perTeklif'te sizin referans?n?zla ?ye olan arkada?lar?n?z?n g?rd??? t?m reklamlardan da s?rekli puan toplayacaks?n?z. S?perTeklif, yukar?da belirtilen pazarlama ?al??malar?ndan elde etti?i net kazanc?n y?zde 45'ini ?yelerine da??tmaktad?r. Unutmay?n, "izinli pazarlama" prensibimiz gere?i, g?nl?k reklamlar ve anketler, sadece sizin istedi?iniz say? ve s?kl?kta taraf?n?za g?nderilir. S?perTeklif ?yeli?i ?cretsizdir. Ancak ?ye olmak i?in S?perTeklif ?yesi bir arkada??n?z taraf?ndan sisteme davet edilmelisiniz. Hen?z davet edilmediyseniz ?z?lmeyin, ?imdilik kay?t olmak i?in sistemden davet istemeniz yeterli! Ayr?ca arkda?lar bu yenilik bunuda okuyun bu ?ok super super teklif gibi her ikisine ?ye olun daha ?ok kazan? elde edin http://www.agloco.com/r/BBFR2592 www.agloco.com/r/BBFZ3904 www.agloco.com/r/BBGR9751 for marketing and win more Money plase do not forget to apply for this site too this very usefull link to win free please do not forget to apply http://www.clixsense.com/?2159840 www.agloco.com/r/BBFR6434 http://www.yuwie.com/yuwie.asp?r=102001 Dear ______, I recently joined AGLOCO because of a friend recommended it to me. I am now promoting it to you because I like the idea and I want you to share in what I think will be an exciting new Internet concept. AGLOCO's story is simple: Do you realize how valuable you are? Advertisers, search providers and online retailers are paying billions to reach you while you surf. How much of that money are you making? NONE! AGLOCO thinks you deserve a piece of the action. AGLOCO collects money from those companies on behalf of its members. (For example, Google currently pays AOL 10 cents for every Google search by an AOL user. And Google still has enough profit to pay $1.6 billion dollars for YouTube, an 18-month old site full of content that YouTube's users did not get paid for! AGLOCO will work to get its Members their share of this and more. AGLOCO is building a new form of online community that they call an Economic Network. They are not only paying Members their fair share, but they're building a community that will generate the kind of fortune that YouTube made. But instead of that wealth making only a few people rich, the entire community will get its share. What's the catch? No catch - no spyware, no pop-ups and no spam - membership and software are free and AGLOCO is 100% member owned. Privacy is a core value and AGLOCO never sells or rents member information. So do both of us a favor: Sign up for AGLOCO right now! If you use this link to sign up, I automatically get credit for referring you and helping to build AGLOCO. http://www.agloco.com/r/BBFR2592 Agloco is the re-birth of AllAdvantage, which paid out over $100,000,000 to its members. * Agloco costs you nothing. It's free. And it always will be. * Agloco's Viewbar shows ads and lets you search the Web. Advertisers and search engines pay Agloco when you do that, and Agloco then pays you. * Agloco pays you by the hour to have that Viewbar open on your desktop. * Agloco pays you by the hour to have your friends have their Viewbar open. * Once you start using the Viewbar, you'll get a check every month in the mail. * Once you sign up, you'll get your own referral URL that your friends can use to sign up. * Every 5 people that you refer to Agloco will double your income. Please follow this link and create own membership by this link http://www.e4l.biz/money.htm?kasim http://adbuddy.net/?rb=kasimmominov, Thanks 1. Hi everyone, For all of you that are asking for caculations for how much pay, just consider this. There is truly no way anyone can calculate with all variables. The pay is dependent upon the advertisers paying agloco, the search engines paying agloco, the merchants paying agloco the commissions on the sales to agloco members, and any other sources of income. This money all goes into a pool, of which agloco management gets 10% and the rest is divided among the owners/members. There you have it. income is variable, percentages for management and the owners ia fixed. membership is variable. These variable parts will change by the minute. No reasonable mathmatician will attempt to arrive at meaningful calculations with two massive variables and one fixed quantity. All the mathmatician can do at this point is offer statistical possibilities. In the short view, every person you sponsor now cuts down on the value of the cash pool individually. In the longer term, more members means agloco can charge more for the ads and make the cash pool larger. As far as clicking the ads, That will create cash pool money when the few make purchases and the merchant pays agloco the commission on the sale. In at least some cases, the member will immediately benefit from any discounts that are given to the agloco membership. Regards searches, I do not know what deal agloco has with google or the other search engines at this time, but I do know that as the membership goes up, so does the price google and the others will pay agloco for each search performed. Google currently pays aol 10 cents per search performed. Best I can tell you is the per hour pay will fall into a range somewhere between .00001 cents and 1,000.00 dollars per hour.( both top and bottom values estimated with the fact that everyone is so desparate for promises that poor Brian cannot say anything without it being considered a set in concrete promise.) I intentionally used extremes. Try to keep your shirt on and wait and see what materializes. - CEV?Z D?KEN ?L?R ( YANLI? ) - CEV?Z D?KEN ?OK YA?AR ( DO?RU ) ?lkemizin k?y?lar?ndan, ovalar?ndan ba?layarak yayla ve da?lar?na var?ncaya kadar her y?kselti ve mesafede yay?l?? g?sterebilen ender a?a?lardan biri olan ceviz a?ac? hakk?nda ne yaz?k ki bir?ok hurafe uydurulmu?tur. Bunlardan biri de "Ceviz diken ?l?r." s?z?d?r. "Ceviz diken ?l?r" s?z? asl?nda ?u ?ekildedir. "Ceviz diken, beli kal?nl???na gelince ?l?r". Bu s?z?n "beli kal?nl???na gelince" si k?sa olsun diye kald?r?lm??, geriye, "Ceviz diken ?l?r" s?z? kalm??. Olay budur. Yoksa halk?m?z, ceviz hakk?nda bu kadar t?rk? yakar m?, bu kadar deyimler s?yler mi, bu kadar ?iirler yazar m?? ?rne?in; Hamit' li A??k Dursun Kaya bak?n ne demi?: Fidan b?y?r ye?il yaprak dal olur, Hayat verir oksijeni bol olur, ?eyiz olur, sand?k olur, sal olur, Ceviz diken ?ok ya?ayan can olur. Di?er yandan resimde g?r?len Bolu/ Mudurnu il?esinin Da?yolu k?y?nde 86 ya??ndaki ki?i, askerden geldi?inden bu yana k?y?n i?ine ve civar?na, buldu?u bo? yerlere devaml? ceviz dikmi?, say?s?n? kendisi bile bilmiyor. Ayr?ca kendim (Selami Bayrak) 1967 y?l?ndan bu yana devaml? ceviz dikiyorum. ?lmeyi bir tarafa b?rak?n ceviz sayesinde sa?l?kl?y?m ve ikinci bahar?m? ya??yorum. Ceviz meyvesini tan?mayan biri, ye?il kabuklu cevizi elma zannederek ?s?r?p yemeye kalkm??, a?z? burulunca "Bu meyve olgunla?mam??" diye yere atm??.Bu olaydan anla??laca?? gibi ?nsanlar ve Toplum bazen bir i?in asl?n? ??renmeden YANLI? karar verebiliyorlar " Torunlar?m?za iyi bir d?nya b?rakabilecek miyiz?" CEV?Z SERA GAZINI AZALTIR Ceviz yapra?? Karbon S?lf?r gaz? salg?lar. Bu gaz, havadaki di?er gazlardan a??r oldu?u i?in cevizin alt?na iner. Yaz?n s?cakta cevizin kaba g?lgesine oturan insan, haliyle bu gazdan etkilenerek biraz sersemler. Cevizin kaba g?lgesinden dolay? dibinde ot bitmedi?i de g?r?l?nce cevizin zehirli gaz salg?lad??? d???ncesi a??rl?k kazan?r. Kesinlikle bu do?ru de?ildir. Bug?ne kadar cevizin dibinde oturan insan?n veya yatan hayvan?n ?ld??? duyulmam??t?r. Grafik' te g?r?ld??? gibi, cevizin insan? ?ld?rd??? de?il tam aksine ya?att??? bilimsel olarak da ispatlanm??t?r. ?te yandan ceviz a?ac?n?n, sera gaz?n? olu?turan Karbondioksiti emerek OZON tabakas?ndaki deli?in b?y?mesini ve k?resel ?s?nmay? engelledi?i g?r?lmektedir. (Reyhan OKSAY, Cumhuriyet Bil. Tek. Der.) Di?er yandan ABD Ulusal Birlik Akademisi' nin a??klamas?na g?re; Karbondioksit ve Metan gazlar?, 12000 y?l uygun bir d?zeyde kald?ktan sonra 20. y?zy?ldan ba?layarak keskin bir y?kseli? sonucu sera etkisi yapmaya ba?lam??t?r ( 24.06.2006 Tarihli TRT Teletex'inin 166. sayfas?) - As?rlard?r y?zlerce ceviz a?a?lar? aras?nda bulunan bir mahalle, ?u anda 81 ya??nda olan mahalle sakinlerinden A??t OMUZ, "Bug?ne kadar mahalleye ne y?ld?r?m d??t???n? g?rm?? ne de i?itmi?" ( Yandaki Resim- Liman Mh. Bah?esaray / VAN, 2001) - ?? Anadolu'nun k?ra? bir yerinde, etraf?nda tek bir a?ac?n dahi bulunmad??? devasa bir ceviz a?ac?. Bu ve buna benzer ceviz a?a?lar?nda bir tek y?ld?r?m izi g?r?lmemi?tir. (K?r?ehir, 1995) " O, 300 y?ld?r orada ya??yor, ya biz?" (Foto?raf: Selami Bayrak, 2003) Kastamonu, Do?anyurt il?esi Kayran K?y?'nde denize 100 m. mesafede, neredeyse 0 rak?mda 3 Da. yeri kaplayan, an?t olabilecek bir ceviz a?ac?. Ka? nesle miras kal?yor? - Ceviz, en uzun ?m?rl? meyve a?a?lar?n?n ba??nda gelmekte olup, 1000 y?l ya?ayabilmektedir. - Gordiyon (Beypazar?/ Ankara) Kral mezar? kaz?lar?nda ortaya ??kar?lan buluntular aras?nda 2700 y?l ?nce ceviz a?ac?ndan yap?lm?? mobilyalara rastlanm??t?r. Bunlar masif olarak, k?vr?k masa bacaklar?, ?? ayakl? d?z masa tablas? ve "pagoda" masa ?st? (tabla) d?r. (Prof. Dr. Burhan Aytu?, Do?. Dr. Ertu?rul G?rcelio?lu, ?.?.Orman Fak?ltesi, 1987) - En ?ok meyve veren ceviz a?ac?, K?r?m'da Balaklava yak?n?ndaki Bayd?r Vadisi'nde yeti?en cevizlerdir. Burada bir ceviz a?ac? y?lda 100 000 ceviz verir( ort. 800 Kg.). ?lkemizde ise Ankara Beypazar? il?esinin Sekli k?y?nde 50 000 adet ( 650 Kg.) , K?r?ehir'in Kaman il?esinde 47 000 adet ( 600 Kg.) veren cevizler bulunmaktad?r. - D?nyan?n en b?y?k organik cevizinin K.Mara?'da yeti?tirildi?i ortaya ??km??t?r. Cevizin; Kabuklu a??rl??? 28 gr. ?? a??rl??? ise 17 gr. gelmi?tir. Rand?man % 61' dir. Not: Standart ?l??ler: Kabuklu a??rl?k en az 10 gr. , i? a??rl?k ise en az 5 gr. d?r. (Gazete Haberi: S?t?? ?mam ?niversitesi Rekt?r Prof. Dr. Osman Tekinel'den yap?lan a??klama) - D?nyan?n en de?erli ceviz g?vdeleri Anadolu' da yeti?mektedir. ??nk? bu g?vdeler Ur'ludur. Ur ve benzeri ?i?kinliklerden "Ayna" ad? verilen desenli levhalar elde edilir. Ayr?ca Anadolu cevizi, di?erlerine nazaran i?lenmi? y?zeylerde koyu renkli ?izgi, ?erit veya par?alar?n meydana getirdi?i g?zel ?ekillere sahiptir. Bu nedenle kaplamac?l?k de?eri ?ok ?st?nd?r. - Nitekim, Kud?s' teki Mescidi Aksa' n?n minberinin asl?na uygun olarak yeniden yap?lmas?nda kullan?lacak ceviz a?a?lar?n?n yurtd???na ??kar?lmas? i?in Bakanlar Kurulunca ?zel kararname ??kar?lm??t?r. 15 m? ceviz a?ac?na 36.000 dolar de?er bi?ilmi?tir. Bu durumda 1 m?' ? 2.400 dolara gelmektedir ( Gazetelerden) "Fakire Kat?k, ustaya K?t?k" - Cevizin ya?l? oldu?u ve insanlara dokundu?u zannedilmektedir. Cevizin ya?l? oldu?u do?rudur. Ancak Cetvelde g?r?ld??? gibi, ortalama %60 olan bu ya??n neredeyse %91'i doymam?? ya?d?r. Doymam?? ya? asitleri, kan kolesterol' u birikimini ?nleyici etkiye sahiptir. Bu ya? asitlerinin bir k?sm? ne v?cut taraf?ndan yak?lmakta, ne de hayvansal ya?larda bulunmaktad?r. Oysa bu ya? asidinin b?y?k bir k?sm? (%61) cevizde bulunmaktad?r. Yine doymam?? ya? asitlerinin baz?lar?, kan?n p?ht?la?mas?n? durdurmakta ve bu sayede koroner damarlar?n t?kanmas?n? ?nleyerek KALP KR?Z?'nin ?n?ne ge?mektedir. Atardamarlarla beslenen dokular besin maddelerinden ve oksijenden mahrum kalarak ?lebilirler. Bu durum, beyinde meydana gelirse fel?, kalp damarlar?nda meydana geldi?indeyse kalp krizi olmaktad?r. - ?nsan beyninde milyonlarca sinir h?cresi ( n?ron ) vard?r. V?cut yeni sinir h?creleri ?retmez. Fakat beslenme ve kullanma ile kapasitesi artar. Do?umdan ?nce b?y?k bir h?zla ( dakikada 250 000 kadar ) olu?an sinir h?creleri ?remesi do?umdan sonra tamamen durur. ?len sinir h?creleri yerine yenileri gelmez. Cevizin, insan v?cudunun ?ok ?nemli organ? olan kalp ve beyine benzemesi bo?una de?ildir. Yukar?daki resimlerde g?r?ld??? gibi, ?in cevizi (J. Ailantiolfa) ayn? kalp ?eklinde, ceviz i?lerinin ise beyin ?eklinde oldu?u a??k?a g?r?lmektedir. - N?tr besinlerden olan ceviz meyvesi rahatl?kla di?er besinlerle yenebilir. Milyarlarca h?crenin bir araya gelerek birle?mesinden ortaya ??kan organlar insan v?cudunda bir?ok sistem meydana getirir.Dola??m, sindirim, sinir, solunum ve ?reme gibi. Cevizin bile?imindeki besinlerin, mineral ve vitaminlerin bu sistemler ?zerinde ?ok b?y?k etkileri vard?r. ?rne?in; ceviz, kolesterol' ? d???r?r, damarlar? a?ar, kans?zl??? giderir, kalp krizi ve fel? riskini d???r?r, ?eker hastal???na faydal?d?r, cinsel g?c? art?r?r, strese iyi gelir, vereme kar?? korur, ?ks?r??? keser, guatra iyi gelir, sivilce ve yaralar?n iyile?mesinde etkilidir, sindirim sistemine iyi gelir, kab?zl??? ve ishali ?nler, parazitleri d???r?r. - Bu ?ok de?erli meyveyi t?ketirken i?inin k?fl? ve kabuk renginin ?ok parlak olmamas?na dikkat etmeliyiz. Kabuklar? ?ok parlak olan ve anormal g?r?n??l? olan cevizler maalesef kimyasal etkilerle parlat?ld??? i?in ?ok zararl?d?r. ?? olarak t?ketece?imiz zaman kabu?undan ??kar?p taze olarak t?ketirsek k?flenmeyi ?nlemi? oluruz. "Sertifikal? fidanlarla bah?e kurarsan?z buradan elde edece?iniz ?r?nleri EUROGAP ?er?evesinde i? ve d?? piyasalarda pazarlayabilirsiniz. Bu t?r bir organize i?inde ?retilen i? cevizin fiyat? a?a??da g?r?lmektedir. Bas?ndan, 2006 Ara Besleyici meyvesi, ?ok de?erli g?vdesi ile ceviz; insanlara sa?lad??? sonsuz yararlar?ndan dolay? halk deyimlerinde ve t?rk?lerde s?k?a yer alm??t?r. http://kgsm.websitesiekle.com/ From jstroud at mbi.ucla.edu Wed Sep 5 14:23:04 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 05 Sep 2007 11:23:04 -0700 Subject: Text processing and file creation In-Reply-To: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> Message-ID: malibuster at gmail.com wrote: > I have a text source file of about 20.000 lines. >>From this file, I like to write the first 5 lines to a new file. Close > that file, grab the next 5 lines write these to a new file... grabbing > 5 lines and creating new files until processing of all 20.000 lines is > done. > Is there an efficient way to do this in Python? You should use a nested loop. > In advance, thanks for your help. > You're welcome. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steve at REMOVE-THIS-cybersource.com.au Wed Sep 19 20:30:52 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Sep 2007 00:30:52 -0000 Subject: cannot create my own dict References: <46f17c26$0$26298$426a74cc@news.free.fr> Message-ID: <13f3fpsa0133142@corp.supernews.com> On Wed, 19 Sep 2007 21:43:59 +0200, Bruno Desthuilliers wrote: >> So if copying all methods of a native dictionary is not enough, what >> should I do to make my class work as a dictionary WITHOUT deriving from >> dict (which will obviously work). >> >> > Sorry, I missed this last requirement. BTW, why don't you want to > subclass dict ? Possibly because it is a learning exercise? -- Steven. From ldo at geek-central.gen.new_zealand Fri Sep 7 20:42:40 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 08 Sep 2007 12:42:40 +1200 Subject: Best practice prompting for password References: Message-ID: In message , GiBo wrote: > what's the best practice to securely prompt user for password on console > in Python? IIRC some programs like SSH do a lot to ensure that the input > comes from TTY and is not redirected from somewhere and several other > checks. Does it? Why bother? It's not where the password comes _from_ that you have to be careful about, it's what you do with it after you get it. From duncan.booth at invalid.invalid Tue Sep 4 03:37:49 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Sep 2007 07:37:49 GMT Subject: parameter list notation References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> Message-ID: TheFlyingDutchman wrote: > I am trying to use a database written in Python called buzhug. > > In looking at some of the functions I see this prototype: > > def create(self,*fields,**kw): > > I am not clear on what the * and the ** are for or what they > represent. Or, what are they referred to as so I can do a query for > information on them. > You could try searching for 'function definitions'. That might lead you to http://docs.python.org/ref/function.html "Python Reference Manual, 7.6 Function definitions": > Function call semantics are described in more detail in section 5.3.4. > A function call always assigns values to all parameters mentioned in > the parameter list, either from position arguments, from keyword > arguments, or from default values. If the form ``*identifier'' is > present, it is initialized to a tuple receiving any excess positional > parameters, defaulting to the empty tuple. If the form > ``**identifier'' is present, it is initialized to a new dictionary > receiving any excess keyword arguments, defaulting to a new empty > dictionary. From paul.nospam at rudin.co.uk Mon Sep 17 11:57:24 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 17 Sep 2007 16:57:24 +0100 Subject: how to join array of integers? References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <13eos6ihf2mjg4a@corp.supernews.com> <87lkb6o4bx.fsf@rudin.co.uk> <13erbtbos7ld123@corp.supernews.com> Message-ID: <87hcltnv2z.fsf@rudin.co.uk> Steven D'Aprano writes: > On Sun, 16 Sep 2007 19:25:22 +0100, Paul Rudin wrote: > >>> The generator expression takes about twice as long to run, and in my >>> opinion it is no more readable. So what's the advantage? >> >> If you do it with a decent size list they take more or less the same >> time. > > Did you try it, Yes. > or are you guessing? Well - I guessed first, otherwise it wouldn't have been worth trying :) > What do you call a decent size? I used 10,000. > > >> You'd presumably expect the generator to use less memory; which >> might be an advantage if you have large lists. > > Unfortunately, Python doesn't make it as easy to measure memory use as it > does to time snippets of code, so that's just a hypothetical. Well - as it turns out the list gets made anyway by the join method, so in this case there's probably little difference. However there (obviously) are siturations where a generator is going to save you a significant memory over the similar list comprehension. > > >> Isn't it odd that the generator isn't faster, since the comprehension >> presumably builds a list first and then iterates over it, whereas the >> generator doesn't need to make a list? > > Who says it doesn't need to make a list? string.join() needs a sequence. > The generator doesn't make a list. The implementation of str.join does apparently needs a sequence and so makes a list from the generator passed to it, which is presumably why you get essentially the same performance once you factor out setup noise for small lists. Although it's not clear to me why the join method needs a sequence rather than just an iterator. From robert.rawlins at thinkbluemedia.co.uk Tue Sep 18 08:14:22 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 18 Sep 2007 13:14:22 +0100 Subject: Wait For Application Start Message-ID: <008701c7f9ed$72996790$57cc36b0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm kick starting my application using the inittab to ensure its re-spawned if it dies. However I need to ensure several other applications and service are up and running before my application is started, things such as dbus and a couple of other hardware stacks. A concept I've been advised to use is that I should make the application wait for the existence of a file before it starts, then create that file on the FS using the rc.local file which is called at the end of all other start items. Only once that file exists will my application commence with its job. This seems like a very logical method, but I'm not sure how to implement it into my python code? Is there a simple way to make it wait for that file? Without the need to build my own conditional loop? Can anyone perhaps help with a simple code example? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From mydomdom at gmail.com Fri Sep 14 10:27:53 2007 From: mydomdom at gmail.com (Dominique) Date: Fri, 14 Sep 2007 14:27:53 +0000 (UTC) Subject: Install Mac OS X - Idle doesn't show up References: <46EA8FB6.4040405@codebykevin.com> Message-ID: Kevin Walzer codebykevin.com> writes: > > > > How did you install/build Python? On the Mac, you really aren't supposed > to start it from the terminal unless you are running it under X11 or are > using a non-framework build. If you built it the standard Mac way, or if > you use the binary installer from python.org, Idle is installed in > /Applications/MacPython 2.5. Look there, and you should be able to drag > the Idle icon to the dock. > Hum Hum Hum... That's what I did. It did not work. Now yes. ???!!!!! I should have dreamt. I don't understand.... Thank you Kevin for your help Dominique From jstroud at mbi.ucla.edu Sat Sep 15 15:48:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 15 Sep 2007 19:48:37 GMT Subject: Python statements not forcing whitespace is messy? In-Reply-To: <1189884110.006272.240840@50g2000hsm.googlegroups.com> References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> Message-ID: buffi wrote: > Am I the only one that thinks that python statements should force > whitespace before and after them? > > Right now this is not enforced and for an example these statements are > valid > > print"hello" > "foo"if"bar"else"foobar" > for(x,y)in[(1,2),(3,4)]:print(x,y) > [(y)for(x,y)in[("foo",2),("bar",4)]if"foo"in(x)] > > ...and so on. > > I know that writing code like this really shouldn't be done but > wouldn't it be a good idea to enforce the use of whitespace around > statements? > > (I wrote a short blog post about this here http://blog.buffis.com/?p=55 > but thought I would post here as well to see what other developers > think) > - Bj?rn Kemp?n > You may have a point--but on the other hand, this may be purposefully allowed help to recruit perl programmers. James From byte8bits at gmail.com Wed Sep 26 17:50:16 2007 From: byte8bits at gmail.com (byte8bits at gmail.com) Date: Wed, 26 Sep 2007 21:50:16 -0000 Subject: Script to extract text from PDF files In-Reply-To: <1190839750.537205.193110@d55g2000hsg.googlegroups.com> References: <1190746968.162359.39890@r29g2000hsg.googlegroups.com> <1190747931.415834.75670@n39g2000hsh.googlegroups.com> <1190839750.537205.193110@d55g2000hsg.googlegroups.com> Message-ID: <1190843416.313377.13700@w3g2000hsg.googlegroups.com> On Sep 26, 4:49 pm, Svenn Are Bjerkem wrote: > I have downloaded this package and installed it and found that the > text-extraction is more or less useless. Looking into the code and > comparing with the PDF spec show a very early implementation of text > extraction. Luckily it is possible to overwrite the textextraction > method in the base class without having to fiddle with the original > code. I tried to contact the developer to offer some help on > implementing text extraction, but he didn't answer my emails. > -- > Svenn Well, feel free to send any ideas or help to me! It seems simple... Do a binary read. Find 'stream' and 'endstream' sections. zlib.decompress() all the streams. Find BT and ET markers (Begin Text & End Text) and finally locate the parens within those and string the text together. This works great on 3 out of 10 PDF documents, but my main issue seems to be the zlib compressed streams. Some of them don't seem to be FlateDecodeable (although they claim to be) or the header is somehow incorrect. But, once I get a good stream and decompress it, things are OK from that point on. Seriously, if you have ideas, please let me know. I'll be glad to share what I've got so far. Not many people seem to be interested. I'll stop adding to this thread... I don't want to beat a dead horse. Anyone interested in helping, can contact me via emial. Thanks, Brad From carsten at uniqsys.com Thu Sep 27 13:14:13 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 27 Sep 2007 13:14:13 -0400 Subject: True of False In-Reply-To: <5m254hFatlbuU2@mid.uni-berlin.de> References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> <5m254hFatlbuU2@mid.uni-berlin.de> Message-ID: <1190913253.3391.6.camel@dot.uniqsys.com> On Thu, 2007-09-27 at 16:47 +0000, Marc 'BlackJack' Rintsch wrote: > On Thu, 27 Sep 2007 09:33:34 -0700, koutoo wrote: > > > I tried writing a true and false If statement and didn't get > > anything? I read some previous posts, but I must be missing > > something. I just tried something easy: > > > > a = ["a", "b", "c", "d", "e", "f"] > > > > if "c" in a == True: > > Print "Yes" > > > > When I run this, it runs, but nothing prints. What am I doing wrong? > > Wow that's odd: > > In [265]: a = list('abcdef') > > In [266]: a > Out[266]: ['a', 'b', 'c', 'd', 'e', 'f'] > > In [267]: 'c' in a > Out[267]: True > > In [268]: 'c' in a == True > Out[268]: False > > In [269]: ('c' in a) == True > Out[269]: True > > In [270]: 'c' in (a == True) > --------------------------------------------------------------------------- > Traceback (most recent call last) > > /home/bj/ in () > > : argument of type 'bool' is not iterable > > > What's going on there? What's going on here is that both 'in' and '==' are comparison operations, and Python allows you to chain comparisons. Just like "a < x < b" is evaluated as "a < x and x < b", "'c' in a == True" is evaluated as "'c' in a and a == True". Obviously, since a==True is false, the chained comparison is False. -- Carsten Haese http://informixdb.sourceforge.net From exhuma at gmail.com Mon Sep 10 07:58:30 2007 From: exhuma at gmail.com (exhuma.twn) Date: Mon, 10 Sep 2007 04:58:30 -0700 Subject: easy_install only stable packages Message-ID: <1189425510.836884.40140@y42g2000hsy.googlegroups.com> easy_install is great. But it always automatically installs the *latest* version. Even if that is beta,alpha (or however else the developers call it). Is there no switch or possibility to disable this feature? So that it installs the latest *stable* version? I know that you can specify a specific version of a package with (for example) easy_install -U "SQLAlchemy==0.3.10" This is undocumented on the web-page by the way ;) But having to specify the version number for each package is quite cumbersome. From __peter__ at web.de Tue Sep 11 13:34:57 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Sep 2007 19:34:57 +0200 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <13e2jdobu2kqkf1@corp.supernews.com> <13e4rno5qal6h4b@corp.supernews.com> Message-ID: Am Sat, 08 Sep 2007 09:44:24 +0000 schrieb Steven D'Aprano: > Ways that Python objects are not like C pointers: > > (1) You don't have to manage memory yourself. > > (2) You don't have typecasts. You can't change the type of the object you > point to. > > (3) Python makes no promises about the memory location of objects. > > (4) No pointer arithmetic. > > (5) No pointers to pointers, and for old-school Mac programmers, no > handles. > > (6) No dangling pointers. Ever. > > (7) There's no null pointer. None is an object, just like everything else. > > (8) You can't crash your computer by writing the wrong thing to the wrong > pointer. You're unlikely even to crash your Python session. > > > > Ways that Python objects are like pointers: > > (1) ... um... > > Oh yeah, if you bind the _same_ object to two different names, _and_ the > object is mutable (but not if it is immutable), mutating the object via > one name will have the same effect on the object -- the same object, > naturally -- bound to the other name. Had you put it that way in the first place I would have stayed in in my hole ;) Peter From steve at holdenweb.com Tue Sep 18 09:30:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Sep 2007 09:30:39 -0400 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: Amer Neely wrote: > Bryan Olson wrote: >> Amer Neely wrote: >>> I don't have shell access but I can run 'which python' from a Perl >>> script, and I will try the different shebang line you suggested. >> And after trying it, Amer Neely reported: >> >>> I tried `which python` and `whereis python` and got 0 back as a >>> result. So it seems Python is not installed at all. >> Probably right, but just to be thorough... Since you do not >> have shell access, I'm guessing you are running these within >> a Perl cgi script, and getting the results via a browser. Is >> that right? > > Yes. >> Can you backtick other commands? What do you get if you run >> `which perl` the same way? How about `whoami`, `whereis sh`, >> and `which nosuchthingas5748614`? Can you list /, /bin and >> /usr/bin? > > I just looked at my code and tried something else: > @SysCmd="which python"; > system(@SysCmd); > > and it came back > /usr/local/bin/python > >> How did you learn that this system could run your Perl >> scripts? Can that source give us anything to go on here? >> If Python is not installed, do you have some avenue for >> requesting it? >> >> We're down to long shots. Still, hosts that support Perl >> but will not support Python are getting to be the rare. >> >> > > I've asked my host to put in a request for it. > > So it seems python IS installed, but not where I thought it was. > > I just tried my script with the new path, but still got a 500 server > error. Can I trap errors to a file locally? > You could try putting an ErrorLog directive in your local .htaccess file. http://httpd.apache.org/docs/1.3/logs.html#errorlog regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From rdm at rcblue.com Tue Sep 11 18:31:07 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 11 Sep 2007 15:31:07 -0700 Subject: Speed of Python In-Reply-To: References: Message-ID: <20070911223113.C2F091E4011@bag.python.org> At 09:42 AM 9/7/2007, wang frank wrote: >Are there any way to speed it up? How about psyco? Dick Moores XP, Python 2.5.1, editor is Ulipad From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 24 05:43:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 24 Sep 2007 11:43:59 +0200 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190606861.982113.25240@d55g2000hsg.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <1190419720.811685.145880@r29g2000hsg.googlegroups.com> <46f6eb3d$0$32060$426a34cc@news.free.fr> <1190606861.982113.25240@d55g2000hsg.googlegroups.com> Message-ID: <46f786cc$0$8901$426a74cc@news.free.fr> Cristian a ?crit : > On Sep 21, 5:21 pm, Bruno Desthuilliers > wrote: > >> Ok, then what about classes ? They also are objects-like-any-other, >> after all. So should we have this syntax too ? >> >> MyClass = class(ParentClass): >> __init__ = function (self, name): >> self.name = name >> >> ?-) > > For consistency I would suggest this, but Python already does this! > > Foo = type('Foo', (object, ), {'bar': lambda self, bar: bar}) > > I've created a new class and then binded it to name afterwards. If you > can import modules without special syntax and you can create classes > without special syntax, why should functions be treated any > differently? > You already can create functions without using the def statement: Help on class function in module __builtin__: class function(object) | function(code, globals[, name[, argdefs[, closure]]]) | | Create a function object from a code object and a dictionary. | The optional name string overrides the name from the code object. | The optional argdefs tuple specifies the default argument values. | The optional closure tuple supplies the bindings for free variables. | HTH From bj_666 at gmx.net Sat Sep 8 13:25:39 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Sep 2007 17:25:39 GMT Subject: /dev/null as a file-like object, or logging to nothing References: <87k5r1jdzq.fsf@wilson.homeunix.com> Message-ID: <5kg48jF33dv5U3@mid.uni-berlin.de> On Sat, 08 Sep 2007 18:52:57 +0200, Torsten Bronger wrote: > Is there a portable and simply way to direct file-like IO to simply > nothing? I try to implement some sort of NullLogging by saying `os.devnull`? Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Sat Sep 1 02:32:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Sep 2007 02:32:29 -0400 Subject: list index() In-Reply-To: <13dhvs3p5drsd99@corp.supernews.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> <6ftgd35rd1g4mddqg2f44d7svd4r85ev17@4ax.com> <13dhvs3p5drsd99@corp.supernews.com> Message-ID: Dennis Lee Bieber wrote: > On Fri, 31 Aug 2007 21:15:10 +0100, DaveM > declaimed the following in comp.lang.python: > > >> No - but I would pronounce "lever" and "fever" the same way, if that helps. >> > To me, those are different... I suppose you also add an > extra "i" to aluminum No, he just spells it with two i's like sensible people do. Who would ever want *three* I's in "aluminium" (which, by the way, you misspelled ;-)? Such things are matters of practical significance to me, since I have adopted a policy of using English spelling when in the UK and US spelling when elsewhere. Since I am now pretty much full-time in the US, I am finally having to come to terms with its crazy spelling. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From tjreedy at udel.edu Thu Sep 13 17:16:14 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Sep 2007 17:16:14 -0400 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com><46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net><1189618530.872819.136450@57g2000hsv.googlegroups.com><1189619033.968437.286580@g4g2000hsf.googlegroups.com><5kr8vlF53m8gU3@mid.individual.net><1189643616.826715.58150@d55g2000hsg.googlegroups.com><5ksoaoF5am8cU1@mid.individual.net> <1189701793.466307.93210@g4g2000hsf.googlegroups.com> Message-ID: "TheFlyingDutchman" wrote in message news:1189701793.466307.93210 at g4g2000hsf.googlegroups.com... | Here's a FAQ item where they refer to it as I think Python should have | done it - a special predefined variable: | | http://www.faqs.org/docs/javap/c5/s5.html | | "Java provides a special, predefined variable named "this" that you | can use for such purposes. The variable, this, is used in the source | code of an instance method to refer to the object that contains the | method. This intent of the name, this, is to refer to "this object," | the one right here that this very method is in. If x is an instance | variable in the same object, then this.x can be used as a full name | for that variable. If otherMethod() is an instance method in the same | object, then this.otherMethod() could be used to call that method. | Whenever the computer executes an instance method, it automatically | sets the variable, this, to refer to the object that contains the | method." In Python, methods are (functions) contained in (are attributes of) classes. Hence, by the above, 'this' or 'self' would be set to the class and not the instance. So the above would require some rewording for Python. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 19 03:59:52 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 09:59:52 +0200 Subject: Pseudo-Private Class Attributes In-Reply-To: References: Message-ID: <46f0d6ec$0$8912$426a74cc@news.free.fr> Ricardo Ar?oz a ?crit : > That is self.__attributes > > Been reading about the reasons to introduce them and am a little > concerned. As far as I understand it if you have a class that inherits > from two other classes which have both the same name for an attribute > then you will have a name clash because all instance attributes "wind up > in the single instance object at the bottom of the class tree". > > Now I guess this means that in any real OOP project you'd better use > __attr for all your attributes, because classes are usually meant to be > subclassed and you can never know when you'll be subclassing from two > classes with attributes with the same name, and I guess you can't take > the risk of this happening because when it happens it will be hell to > find out what's going on. > > Is this right? Wild guess : you're coming from Java or C++ ?-) I don't know for sure what you mean by "real OOP project", but any non-trivial Python project surely qualifies IMHO, and it seems that so far no one had too much problem with this, so you're perhaps needlessly worrying. Note that given Python's type system, inheritence is mostly about implementation - you don't need it for polymorphic dispatch. This results in class hierarchies being way much flatter in Python than in languages with declarative static typing - IOW, Python's classes are not necessarily "meant to be subclassed". Also, while Python does support multiple inheritance, it's rarely used in practice (except perhaps in Zope 2, which is that pythonic). Python has great support for delegation, so composition/delegation is often used where MI would have been used in C++. FWIW, __private names are of very rare use in Python. As far as I'm concerned, I must have use this feature a couple of times at most, in base classes or metaclasses of a small framework, because these couple attributes where really vital to the sytem and should by no mean be overloaded. My 2 cents. From luojiang2 at tom.com Wed Sep 5 21:30:52 2007 From: luojiang2 at tom.com (Ginger) Date: Thu, 6 Sep 2007 09:30:52 +0800 Subject: Text processing and file creation References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> <2dc0c81b0709051003n6b81493ah373ce626e172309e@mail.gmail.com> Message-ID: <008401c7f025$90623580$4de1a8c0@amd.com> file reading latency is mainly caused by large reading frequency, so reduction of the frequency of file reading may be way to solved your problem. u may specify an read bytes count for python file object's read() method, some large value(like 65536) can be specified due to ur memory usage, and u can parse lines from read buffer freely. have fun! ----- Original Message ----- From: "Shawn Milochik" To: Sent: Thursday, September 06, 2007 1:03 AM Subject: Re: Text processing and file creation > On 9/5/07, malibuster at gmail.com wrote: >> I have a text source file of about 20.000 lines. >> >From this file, I like to write the first 5 lines to a new file. Close >> that file, grab the next 5 lines write these to a new file... grabbing >> 5 lines and creating new files until processing of all 20.000 lines is >> done. >> Is there an efficient way to do this in Python? >> In advance, thanks for your help. >> > > > I have written a working test of this. Here's the basic setup: > > > > > open the input file > > function newFileName: > generate a filename (starting with 00001.tmp). > If filename exists, increment and test again (0002.tmp and so on). > return fileName > > read a line until input file is empty: > > test to see whether I have written five lines. If so, get a new > file name, close file, and open new file > > write line to file > > close output file final time > > > Once you get some code running, feel free to post it and we'll help. > > From sjmachin at lexicon.net Sat Sep 15 19:17:57 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 16 Sep 2007 09:17:57 +1000 Subject: Python statements not forcing whitespace is messy? In-Reply-To: References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> <1189890755.870694.29790@r29g2000hsg.googlegroups.com> Message-ID: <46ec6826$1@news.eftel.com.au> On 16/09/2007 8:11 AM, James Stroud wrote: > Steve Holden wrote: >> I don't know why you have a bug up your ass about it, as the >> Americans say. > > I think most Americans say "wild hare up your ass". The essence of Steve's point appears to be that the OP has ridden into town to preach a misguided crusade against the heretofore-unknown non-spacing heretics. It also seems to be alleged that at some stage, the OP's donkey has been severely molested by some malevolent fauna; I am having difficulty understanding the connection between the two themes, and which is cause and which is effect. Enlightenment, please. From daniel.j.larsson at gmail.com Tue Sep 4 17:01:17 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Tue, 4 Sep 2007 23:01:17 +0200 Subject: doctest and decorators In-Reply-To: <200709042236.37712.python@cx.hu> References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> <200709042236.37712.python@cx.hu> Message-ID: <2bfa72fa0709041401g63e5f6aem55bcabe9e00134b@mail.gmail.com> On 9/4/07, Ferenczi Viktor wrote: > > > I assume this is a FAQ, but I couldn't find much helpful information > > googling. I'm having trouble with doctest skipping my functions, if I'm > > using decorators (that are defined in a separate module). If I'm > > understanding what is happening correctly, it's because doctest checks > if > > the function's func_global attribute is the same as the module's > __dict__ > > attribute. The decorator in question returns a wrapping function, > though, > > so this check fails. > > What are some solutions to this? I can define __test__, but it seems > rather > > cumbersome. > > Please take a look at the documentation of the functools standard module > in > the Python manual, especially the wraps decorator. It could probably help. > Hmm, not really. # decorator.py import functools def simplelog(f): @functools.wraps def new_f(*args, **kwds): print "Wrapper calling func" return f(*args, **kwds) return new_f # test.py from decorator import simplelog @simplelog def test(): """ >>> test() 'works!' """ return "works!" if __name__ == '__main__': import doctest doctest.testmod() $ python test.py -v 1 items had no tests: __main__ 0 tests in 1 items. 0 passed and 0 failed. Test passed. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Sep 21 12:13:02 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Sep 2007 12:13:02 -0400 Subject: calling extension's autoconf/make from distutils In-Reply-To: <1190386224.536371.136640@q3g2000prf.googlegroups.com> References: <1190349834.894931.128050@q3g2000prf.googlegroups.com> <1190386224.536371.136640@q3g2000prf.googlegroups.com> Message-ID: Gary Jefferson wrote: > On Sep 20, 10:43 pm, Gary Jefferson > wrote: >> I've got a python extension that comes with its own standard autoconf/ >> automake system, and I can "python setup.py build" just fine with it >> as long as I have previously done "./configure" in that directory. >> >> However, 'python setup.py bdist_rpm' can't hope to have done './ >> configure' first, as it untars and tries to build the extension there. >> >> Is there a hook for bdist_rpm (and friends) that will allow me to >> insert a './configure' in the build process, sometime before it tries >> to build the extension? >> >> Thanks, >> Gary > > > I ended up simply subclassing 'Extension' and having it os.system('./ > configure') before proceeding. > > This isn't perfect, as it does the './configure' everytime, but it > works. > [Sorry: it's config.status you shoudl check for, not config-status]. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From Shawn at Milochik.com Fri Sep 14 09:44:23 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Fri, 14 Sep 2007 09:44:23 -0400 Subject: [Tutor] Just bought Python in a Nutshell In-Reply-To: References: Message-ID: <2dc0c81b0709140644w629acda6vee05d589a2e54043@mail.gmail.com> My best advice: Skim it -- just flip the pages, glancing at each one without really reading it -- maybe just read the bold type. You'll find that very rewarding when you run into a problem in your coding and remember that you saw *something* which could be related. You will probably notice some built-in functions that you will need and possibly would have re-invented if you didn't know they were there. I don't really find it to be a "reading" book -- it's more of a reference book. Flip through it, then keep it within reach of your keyboard. Shawn From steve at REMOVE-THIS-cybersource.com.au Thu Sep 13 09:55:28 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Sep 2007 13:55:28 -0000 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189666095.727426.135170@o80g2000hse.googlegroups.com> <1189685403.306218.13270@22g2000hsm.googlegroups.com> Message-ID: <13eigagsuk74l55@corp.supernews.com> On Thu, 13 Sep 2007 12:10:03 +0000, timothy.soehnlin at gmail.com wrote: > Why not use '_' as the self variable. It is minimal and achieves close > to '.var', as '_.var' isn't that different. I know its a little > perl-esque, but its not a bad convention if you are aiming to up > readability of your code. I think the definitions of "up" or "readability" you are using are very different from mine. To me, to up something means to increase it, and readability means the ease of comprehension when reading something. You seem to be using the opposite definition for one or the other. -- Steven. From aahz at pythoncraft.com Thu Sep 13 22:21:05 2007 From: aahz at pythoncraft.com (Aahz) Date: 13 Sep 2007 19:21:05 -0700 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@1 <874phz5i9n.fsf@benfinney.id.au> Message-ID: In article <874phz5i9n.fsf at benfinney.id.au>, Ben Finney wrote: > >Specifically an easier way of doing it provided by the language syntax >(hence "syntactic sugar"). As in, "the form 'foo += 1' is syntactic >sugar for 'foo = foo + 1'". Except, of course, that it isn't, quite. ;-) -- 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 http://www.lysator.liu.se/c/ten-commandments.html From alexandre.badez at gmail.com Wed Sep 5 05:01:56 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Wed, 05 Sep 2007 09:01:56 -0000 Subject: Multi Heritage with slots Message-ID: <1188982916.071976.160170@g4g2000hsf.googlegroups.com> Hye, I'm developing a little app, and I want to make multi heritage. My problem is that my both parent do have __slots__ define. So I've got something like: class foo(object): __slots__ = ['a', 'b'] pass class foo2(object): __slots__ = ['c', 'd'] pass class crash(foo, foo2): pass If you write only that in a sample file or in python console (as I did), python refuse to load the module and report something like: Traceback (most recent call last): File "", line 1, in ? TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict Do you know why it append? And how could I make this work? From ldo at geek-central.gen.new_zealand Fri Sep 7 01:40:19 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 07 Sep 2007 17:40:19 +1200 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> Message-ID: In message <13dv4uqqb806ff0 at corp.supernews.com>, bambam wrote: > The devices are in a list, and are removed by using pop(i). This > messes up the loop iteration, so it is actually done by setting a > flag on each device in the exception handler, with ANOTHER > loop after each write/read/calculate sequence. Why not just build a new list? E.g. newdevs = [] for dev in devs : ... if not removing_dev : newdevs.append(dev) #end if #end for devs = newdevs From martin at v.loewis.de Fri Sep 28 18:26:42 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 Sep 2007 00:26:42 +0200 Subject: marshal bug? In-Reply-To: References: <1190961020.258850.215130@g4g2000hsf.googlegroups.com> <18c1e6480709280011g1fcc4976v77dd0eec0e416752@mail.gmail.com> Message-ID: <46FD7FA2.2020409@v.loewis.de> > [1] http://coverage.livinglogic.de/Python/marshal.c.html. (Actually, I > checked the downloaded bz2, but this is the only URL for marshal.c I > could find) A better URL is http://svn.python.org/projects/python/trunk/Python/marshal.c or http://svn.python.org/view/python/trunk/Python/marshal.c Regards, Martin From stefan.behnel-n05pAM at web.de Sat Sep 15 12:42:42 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 15 Sep 2007 18:42:42 +0200 Subject: find and remove "\" character from string In-Reply-To: References: Message-ID: <46EC0B82.40309@web.de> Konstantinos Pachopoulos wrote: > i have the following string s and the following code, which doesn't > successfully remove the "\", but sucessfully removes the "\\". > >>>> s="Sad\\asd\asd" >>>> newS="" >>>> for i in s: > ... if i!="\\": > ... newS=newS+i I'm not quite sure what you're trying to achieve, but I'd use >>> r"\\a\\b\c".replace("\\\\", "") 'ab\\c' >>> r"\\a\\b\c".replace("\\", "") 'abc' Note that "\\" in the source is unescaped to "\" in the string. Use r"\\" to prevent that. Stefan From jura.grozni at gmail.com Sat Sep 22 13:29:12 2007 From: jura.grozni at gmail.com (azrael) Date: Sat, 22 Sep 2007 10:29:12 -0700 Subject: Video from image Message-ID: <1190482152.556818.19300@k79g2000hse.googlegroups.com> I'd like to ask you if you know a module that makes it possible to create a number of images and than to use them as frames and finaly export them to a video file From ebgssth at gmail.com Sat Sep 15 12:14:01 2007 From: ebgssth at gmail.com (js) Date: Sun, 16 Sep 2007 01:14:01 +0900 Subject: RFC-3986 or 2396 implementation in Python? Message-ID: Hi list. Is there any module that is compatible with RFC-3986 or 2396, which is like Perl's URI module(http://search.cpan.org/~gaas/URI-1.35/URI.pm)? I like to normalize lots of URIs I've got in my database to make them all unique ones. Thank you in advance. From eduardo.padoan at gmail.com Sat Sep 15 16:31:47 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Sat, 15 Sep 2007 17:31:47 -0300 Subject: Python statements not forcing whitespace is messy? In-Reply-To: <46EC3C6E.6050002@sdf.lonestar.org> References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> <46EC3C6E.6050002@sdf.lonestar.org> Message-ID: On 9/15/07, J. Cliff Dyer wrote: > And I'd hate to have to remember all of the rules for what can go > together and what can't, especially when it comes time to debug. No. > I don't think it should be forced, but maybe put it in PEP8 or PEP3008. It is: see "Whitespace in Expressions and Statements" in PEP 8. -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From morphine at despammed.com Sun Sep 30 06:33:55 2007 From: morphine at despammed.com (morphine) Date: Sun, 30 Sep 2007 12:33:55 +0200 Subject: Can you please give me some advice? References: Message-ID: <46ff7b44$0$4798$4fafbaef@reader4.news.tin.it> Byung-Hee HWANG wrote: > Hi there, > > What is different between Ruby and Python? I am wondering what language > is really mine for work. Somebody tell me Ruby is clean or Python is > really easy! Anyway I will really make decision today what I have to > study from now on. What kind of advice do you expect on a NG called comp.lang.PYTHON ? > What I make the decision is more difficult than to > know why I have to learn English. Yeah I do not like to learn English > because it is just very painful.. Then stop learning it ;) ciao -- morphine From jcd at sdf.lonestar.org Fri Sep 14 09:43:27 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Fri, 14 Sep 2007 09:43:27 -0400 Subject: recursion In-Reply-To: References: Message-ID: <20070914134327.GA15615@sdf.lonestar.org> On Fri, Sep 14, 2007 at 01:40:17PM +0200, Gigs_ wrote regarding Re: recursion: > > what i mean is how python knows to add all thing at the end of recursion > > >>> def f(l): > if l == []: > return [] > else: > return f(l[1:]) + l[:1] > The following script does exactly the same thing, except it creates print statements to help you figure out what's going on, and it binds f(L[1:]) to a variable so you can use it again. def f(L): # l capitalized to accentuate difference between l and 1. print "L =", L print "L[1:] =", L[1:] print "L[:1] =", L[:1] if L == []: print "Return: ", [] return [] else: next = f(L[1:]) print "Return: ", next, "+", L[:1], "=", next + L[:1] return next + L[:1] if __name__=='__main__': print f(['A', 'B', 'C', 'D']) Try it out. See what happens. Cheers, Cliff From aahz at pythoncraft.com Wed Sep 5 08:44:44 2007 From: aahz at pythoncraft.com (Aahz) Date: 5 Sep 2007 05:44:44 -0700 Subject: creating really big lists References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> Message-ID: In article <1188985838.661821.41530 at k79g2000hse.googlegroups.com>, Dr Mephesto wrote: > >I would like to create a pretty big list of lists; a list 3,000,000 >long, each entry containing 5 empty lists. My application will append >data each of the 5 sublists, so they will be of varying lengths (so no >arrays!). Why do you want to pre-create this? Why not just create the big list and sublists as you append data to the sublists? -- 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 http://www.lysator.liu.se/c/ten-commandments.html From gagsl-py2 at yahoo.com.ar Mon Sep 24 04:18:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Sep 2007 05:18:10 -0300 Subject: annoying stdin/stdout + pipes problem References: <1190554821.677666.93530@w3g2000hsg.googlegroups.com> <46f69324$0$90263$14726298@news.sunsite.dk> <1190617447.995633.48480@n39g2000hsh.googlegroups.com> Message-ID: En Mon, 24 Sep 2007 04:04:07 -0300, per9000 escribi?: > On 23 Sep, 18:24, Damjan wrote: >> > I want to create a program that reads input from stdio that can prompt >> > a user for input while doing so without getting into problems. >> ... >> >> The trick (which works on Linux for sure) is to open /dev/tty and ask >> question/get input on/from it. > > it worked just fine on my Gnu/Linux machine, but I'd really like it to > be independent of OS. Any one else got some idea - or a windows > version of the same? On Windows it's almost the same, using "conin$" as the filename for console input, and "conout$" as the filename for console output. -- Gabriel Genellina From rschroev_nospam_ml at fastmail.fm Tue Sep 25 06:03:04 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 25 Sep 2007 10:03:04 GMT Subject: Newbie completely confused In-Reply-To: References: Message-ID: Jeroen Hegeman schreef: > Thanks for the comments, > >> (First, I had to add timing code to ReadClasses: the code you posted >> doesn't include them, and only shows timings for ReadLines.) >> >> Your program uses quite a bit of memory. I guess it gets harder and >> harder to allocate the required amounts of memory. > > Well, I guess there could be something in that, but why is there a > significant increase after the first time? And after that, single- > trip time pretty much flattens out. No more obvious increases. Sorry, I have no idea. >> If I change this line in ReadClasses: >> >> built_classes[len(built_classes)] = HugeClass(long_line) >> >> to >> >> dummy = HugeClass(long_line) >> >> then both times the files are read and your data structures are built, >> but after each run the data structure is freed. The result is that >> both >> runs are equally fast. > > Isnt't the 'del LINES' supposed to achieve the same thing? And > really, reading 30MB files should not be such a problem, right? (I'm > also running with 1GB of RAM.) 'del LINES' deletes the lines that are read from the file, but not all of your data structures that you created out of them. Now, indeed, reading 30 MB files should not be a problem. And I am confident that just reading the data is not a problem. To make sure I created a simple test: import time input_files = ["./test_file0.txt", "./test_file1.txt"] total_start = time.time() data = {} for input_fn in input_files: file_start = time.time() f = file(input_fn, 'r') data[input_fn] = f.read() f.close() file_done = time.time() print '%s: %f to read %d bytes' % (input_fn, file_done - file_start, len(data)) total_done = time.time() print 'all done in %f' % (total_done - total_start) When I run that with test_file0.txt and test_file1.txt as you described (each 30 MB), I get this output: ./test_file0.txt: 0.260000 to read 1 bytes ./test_file1.txt: 0.251000 to read 2 bytes all done in 0.521000 Therefore I think the problem is not in reading the data, but in processing it and creating the data structures. >> You read the files, but don't use the contents; instead you use >> long_line over and over. I suppose you do that because this is a test, >> not your actual code? > > Yeah ;-) (Do I notice a lack of trust in the responses I get? Should > I not mention 'newbie'?) I didn't mean to attack you; it's just that the program reads 30 MB of data, twice, but doesn't do anything with it. It only uses the data that was stored in long_lines, and which never is replaced. That is very strange for real code, but as a test it can have it's uses. That's why I asked. > Let's get a couple of things out of the way: > - I do know about meaningful variable names and case-conventions, > but ... First of all I also have to live with inherited code (I don't > like people shouting in their code either), and secondly (all the > itemx) most of these members normally _have_ descriptive names but > I'm not supposed to copy-paste the original code to any newsgroups. Ok. > - I also know that a plain 'return' in python does not do anything > but I happen to like them. Same holds for the sys.exit() call. Ok. > - The __init__ methods normally actually do something: they > initialise some member variables to meaningful values (by calling the > clear() method, actually). > - The __clear__ method normally brings objects back into a well- > defined 'empty' state. > - The __del__ methods are actually needed in this case (well, in the > _real_ code anyway). The python code loads a module written in C++ > and some of the member variables actually point to C++ objects > created dynamically, so one actually has to call their destructors > before unbinding the python var. That sounds a bit weird to me; I would think such explicit memory management belongs in the C++ code instead of in the Python code, but I must admit that I know next to nothing about extending Python so I assume you are right. > All right, thanks for the tips. I guess the issue itself is still > open, though. I'm afraid so. Sorry I can't help. One thing that helped me in the past to speed up input is using memory mapped I/O instead of stream I/O. But that was in C++ on Windows; I don't know if the same applies to Python on Linux. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From horpner at yahoo.com Fri Sep 7 13:22:03 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 07 Sep 2007 17:22:03 GMT Subject: library to launch program in linux References: <1189103678.484278.321650@r34g2000hsd.googlegroups.com> <13e0itfgm0ida1c@corp.supernews.com> Message-ID: On 2007-09-07, Lawrence D'Oliveiro wrote: > In message , Laszlo Nagy > wrote: > >> Grant Edwards wrote: >> >>> On 2007-09-06, idzwan.nizam at gmail.com wrote: >>> >>>> I'm a new user. What library should I use so that I can launch >>>> program in linux using python? >>>> >>> >>> subprocess >>> >> Hmm, there are some others... > > subprocess subsumes them all. And someday soon, subprocess will RULE THE WORLD! BWA-HAHAHAHAH! -- Neil Cerutti From evan at yelp.com Fri Sep 7 02:49:14 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 06 Sep 2007 23:49:14 -0700 Subject: Why 'class spam(object)' instead of class spam(Object)' ? In-Reply-To: References: Message-ID: <1189147754.6277.7.camel@thinkpad> On Fri, 2007-09-07 at 01:30 -0500, Sergio Correia wrote: > Hi, I'm kinda new to Python (that means, I'm a total noob here), but > have one doubt which is more about consistency that anything else. > > Why if PEP 8 says that "Almost without exception, class names use the > CapWords convention", does the most basic class, object, is lowercase? The convention is that classes written in C use lower case, while classes written in Python use capital letters. That's why list, tuple, set, dict, and so forth are all classes with lower case letters. > I found a thread about this: > http://mail.python.org/pipermail/python-list/2007-April/437365.html > where its stated that -object- is actually a type, not a class; but > the idea still doesn't convince me. > > If i create a class Spam using -object- as a parent class, I would > expect -object- to be a class, not a type as in type(object) (what is > the difference between both btw?). But, on the other hand, if I do > help(object), I get: > > >>> help(object) > Help on class object in module __builtin__: > > class object > | The most base type > > So is this a class? No... > > >>> object > > > My doubts get compounded when strange stuff starts to happen: > > >>> class Eggs(object): > def __init__(self): > self.x = 1 > >>> type(Eggs) > > > Type 'type'? What is that supposed to mean? I'm not 100% sure how new style classes work, but my understanding is that while normally we refer to objects as instances of classes, classes are really instances of type objects! Types are treated specially (IIRC, types are instantiated exactly once, on the stack) in Python, so you shouldn't worry about them, other than to know they are the "class" that classes belong to. -- Evan Klitzke From stefan.behnel-n05pAM at web.de Wed Sep 19 12:24:38 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 19 Sep 2007 18:24:38 +0200 Subject: Extracting xml from html In-Reply-To: <1190210892.719313.51680@22g2000hsm.googlegroups.com> References: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> <46EF769E.4080103@web.de> <1190144020.294613.167800@57g2000hsv.googlegroups.com> <46F0DA24.5030000@web.de> <1190210892.719313.51680@22g2000hsm.googlegroups.com> Message-ID: <46F14D46.3040407@web.de> kyosohma at gmail.com wrote: >> row = tree.find("//Row") >> print row.findtext("primaryowner") >> print row.findtext("customeraddress") > > I tried this your way and Laurent's way and both give me this error: > > AttributeError: 'NoneType' object has no attribute 'findtext' Well, error handling is up to you. If find() doesn't find what you are looking for, it will return None. Note that tag names are case sensitive - or maybe there are namespaces involved, cannot tell from the example you posted. Stefan From whamil1 at entergy.com Fri Sep 7 09:12:09 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Fri, 7 Sep 2007 08:12:09 -0500 Subject: application version checking against database In-Reply-To: <1189165916.268515.10360@d55g2000hsg.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB32@LITEXETSP001.etrsouth.corp.entergy.com> > From: imageguy > > We are trying to implement a system that checks the version of the > application against a version number stored in the database. We don't > want the app and the db don't become out of sync. > > We have tried setting a __version__ variable in the top most module, > however, it seems that this is not accessible for the modules that are > subsequently imported. There are a several locations in the app where > we want to do the version check, but we would like to have one place > to set the version number, namely the top level module. > > We have thought of creating a Version class and passing it around, but > aren't really keen on that idea. > > Any suggestions/ideas would be helpful. > > > NOTE: the app is developed in wxPython. > You could add a Version module that contains the version number and any functions related to the version checking, and import that into the modules that do version checking. -- -Bill Hamilton From fd.calabrese at gmail.com Sun Sep 16 06:21:59 2007 From: fd.calabrese at gmail.com (cesco) Date: Sun, 16 Sep 2007 10:21:59 -0000 Subject: generate list of partially accumulated values In-Reply-To: <1189937183.100462.175070@o80g2000hse.googlegroups.com> References: <1189936564.932553.148800@50g2000hsm.googlegroups.com> <1189936979.276166.103080@w3g2000hsg.googlegroups.com> <1189937183.100462.175070@o80g2000hse.googlegroups.com> Message-ID: <1189938119.469599.171960@w3g2000hsg.googlegroups.com> > l = [1, 2, 3, 4] > [sum(l[:x+1]) for x in xrange(len(l))] Thanks, actually my problem is a bit more complex (I thought I could get a solution by posting a simplified version...) The list is composed of objects: l = [obj1, obj2, obj3, obj4] and I need to call a method (say method1) on each object as follow: l1 = [obj1.method1(obj2), obj2.method1(obj3), obj3.method1(obj4), obj4] Is there a clean way of doing this? Thanks again Francesco From tigerb at yahoo.com Wed Sep 12 17:23:37 2007 From: tigerb at yahoo.com (TonyB) Date: Wed, 12 Sep 2007 14:23:37 -0700 Subject: struct is saving 4 bytes instead of 2 Message-ID: <1189632217.661924.25520@r34g2000hsd.googlegroups.com> Using UBUNTU python 2.4.3 I'm using struct to save a variable to a file. My goal is to save it as a 2 byte signed integer. Its being saved using: f.write(struct.pack('h',thevariable)) When I inspect the file with a hex editor it show that the variable is being saved as 4 bytes. How can I make it save the value as 2 bytes? Tony From wizzardx at gmail.com Thu Sep 20 16:14:30 2007 From: wizzardx at gmail.com (David) Date: Thu, 20 Sep 2007 22:14:30 +0200 Subject: Tapping into the access of an int instance In-Reply-To: <96f089100709201021m25e2243ey5fb9fa48917c3bc0@mail.gmail.com> References: <96f089100709201021m25e2243ey5fb9fa48917c3bc0@mail.gmail.com> Message-ID: <18c1e6480709201314q3add229fu3d0022e7529b90c2@mail.gmail.com> On 9/20/07, Tor Erik S?nvisen wrote: > Hi, > > Does anyone know how to interrupt the lookup of an integer value? I > know I need to subclass int, since builtin types can't be altered > directly... > > Below is how far I've come... What I want is to tap into the access of > instance i's value 1... You can cheat in your example by overriding the __str__ method. That method (or __repr__) is what gets called from the interpreter to display your variable. You can also override the __int__ method. Then int(i) can return a custom value. You can also do something close to what you want with properties: x = X() # Where X is a class with appropriate setter and getter methods x.i = 5 print x.i # Outputs something besides 5 However, it sounds like you want the equivalent of a non-existant __getvalue__ method that you could override to return a custom value instead of the one you initialised the variable with. Like a kind of "proxy to self" method. However, Python variables don't work that way :-) From carsten at uniqsys.com Sat Sep 29 08:40:54 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 29 Sep 2007 08:40:54 -0400 Subject: Python 3.0 migration plans? In-Reply-To: References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <%q0Li.725$ih1.539@nlpi068.nbdc.sbc.com> <1i555ag.9ez4uvf4583jN%aleax@mac.com> <1191010125.107578.67700@g4g2000hsf.googlegroups.com> Message-ID: <1191069654.3276.4.camel@localhost.localdomain> On Sat, 2007-09-29 at 04:09 +0000, John Nagle wrote: > [...] > For example, MySQL AB supports a Perl binding to MySQL, but not a > Python binding. And what's your point, other than that apparently MySQL AB doesn't care about Python? -- Carsten Haese http://informixdb.sourceforge.net From __peter__ at web.de Thu Sep 13 02:49:22 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Sep 2007 08:49:22 +0200 Subject: File Parsing Question References: <1189634861.631219.143310@57g2000hsv.googlegroups.com> <13ehmjf33b3d029@corp.supernews.com> Message-ID: Dennis Lee Bieber wrote: > for line in inp: > > will read one line at a time (I'm fairly sure the iterator doesn't > attempt to buffer multiple lines behind the scenes) You are wrong: >>> open("tmp.txt", "w").writelines("%s\n" % (9*c) for c in "ABCDE") >>> instream = open("tmp.txt") >>> for line in instream: ... print instream.tell(), line.strip() ... 50 AAAAAAAAA 50 BBBBBBBBB 50 CCCCCCCCC 50 DDDDDDDDD 50 EEEEEEEEE >>> Here's the workaround: >>> instream = open("tmp.txt") >>> for line in iter(instream.readline, ""): ... print instream.tell(), line.strip() ... 10 AAAAAAAAA 20 BBBBBBBBB 30 CCCCCCCCC 40 DDDDDDDDD 50 EEEEEEEEE >>> Peter From steve at holdenweb.com Fri Sep 7 17:48:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Sep 2007 14:48:33 -0700 Subject: How to convert None to null value In-Reply-To: <1189192525.3367.97.camel@dot.uniqsys.com> References: <13e38g6poh2jre3@corp.supernews.com> <1189192525.3367.97.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > On Fri, 2007-09-07 at 12:10 -0700, Dennis Lee Bieber wrote: >> On Fri, 07 Sep 2007 09:07:49 -0400, Carsten Haese >> declaimed the following in comp.lang.python: >> >> >>> doesn't have a parameter binding mechanism, you should throw it away and >>> replace it with a DB-API complaint module. >>> >> I hadn't realized the DB-API defined a "complaint" module > > Yeah, I noticed the typo a minute too late. Dyslexics of the world, > untie! ;-) > Dyslexia rules, KO regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From steve at holdenweb.com Thu Sep 27 11:34:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 11:34:12 -0400 Subject: setuptools without unexpected downloads In-Reply-To: <1190903184.578243.192110@n39g2000hsh.googlegroups.com> References: <87ejgmklep.fsf@benfinney.id.au> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> <5luv0iFaai82U1@mid.uni-berlin.de> <1190808836.056298.232640@57g2000hsv.googlegroups.com> <1190840682.716950.131830@r29g2000hsg.googlegroups.com> <1190903184.578243.192110@n39g2000hsh.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Sep 26, 5:52 pm, Steve Holden wrote: >> kyoso... at gmail.com wrote: >>> On Sep 26, 8:30 am, Steve Holden wrote: >>>> Fredrik Lundh wrote: >>>>> Paul Boddie wrote: >>>>>> P.S. Of course, the package maintainer problem manifests itself most >>>>>> prominently on Windows where you often see people asking for pre-built >>>>>> packages or installers. >>>>> for the record, I'd love to see a group of volunteers doing stuff like >>>>> this for Windows. there are plenty of volunteers that cover all major >>>>> Linux/*BSD distributions (tons of thanks to everyone involved in this!), >>>>> but as far as I can remember, nobody has ever volunteered to do the same >>>>> for Windows. >>>> I'd like to see something like this happen, too, and if a group of >>>> volunteers emerges I'll do what I can through the PSF to provide >>>> resources. Activities that benefit the whole community (or a large part >>>> of it) are, IMHO, well worth supporting. >>> What would it entail to do this? Using py2exe + some installer (like >>> Inno Setup) to create an installer that basically copies/installs the >>> files into the site-packages folder or wherever the user chooses? If >>> that's all it is, I would think it would be fairly easy to create >>> these. Maybe I'm over-simplifying it though. >>> What are a some examples of packages that need this? >> MySQLdb and psycopg are two obvious examples I have had to grub around >> or produce my own installers for. There's generally some configuration >> work to do for packages that have been produced without considering >> Windows requirements, and ideally this will be fed back to the developers. >> >> I think you may be oversimplifying a little. Pure Python packages aren't >> too problematic, it's mostly the extension modules. Unless a copy of >> Visual Studio is available (and we *might* get some cooperation from >> Microsoft there) that means resorting to MingW, which isn't an easy >> environment to play with (in my occasional experience, anyway). >> >> There's going to be increasing demand for 64-bit implementations too. >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 >> Holden Web LLC/Ltd http://www.holdenweb.com >> Skype: holdenweb http://del.icio.us/steve.holden >> >> Sorry, the dog ate my .sigline > > Steve, > > We have Visual Studio 2005 at work and my boss is a Python nut, so I > could probably use it. I also have academic versions of VS 6 and 2003 > (maybe 2005 too...I forget, it might be 2004) at home as well...I > think I can use those for open source development, although knowing > Microsoft, there's probably something draconian hiding in the EULA > somewhere. > > If someone is willing to give me some guidance, I'll give it a try. > Mike: The existing Python Windows installation is, IIRC, produced with VS 2003. Though much work has been done on making a VS2005 version, I do not believe it has yet been completed. But I don't believe there's anything horrendous in the EULA waiting to bite us in the ass. I think I could probably get Microsoft to make low-cost software available for individuals who were helping the Python community out in this way (and if not then I might persuade the PSF to apply some funding if individuals were seen to be committed to the task). At least as important as individual volunteers to do the packaging work (and feed back changes to non-Windows implementation teams) is the need for someone to coordinate all the work done on different packages. Without someone who has an overall grasp of what's going on such work might tend to founder. Are you interested in that side of things at all? I'm happy to give you what guidance I can [off line would probably be best], but my version of Visual Studio hasn't been used in two months ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From jstroud at mbi.ucla.edu Wed Sep 12 19:51:25 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 12 Sep 2007 16:51:25 -0700 Subject: compiling an extension for several versions of python In-Reply-To: References: Message-ID: mh at pixar.com wrote: > I don't have access to site-packages, but I would like > to provide versions of my c-language package compiled against > python 2.4 and 2.5. > > I "own" a library directory which is included in our site's > sys.path. Currently this is where the 2.4 shared libary > is installed. > > What's the most canonical way of doing this? This is on linux. > > Many TIA! > Mark > Normally, you would make 2 different distros which people could download, etc. But in this setting, if I get your meaning correctly, your best bet would be to wrap them in another module and let people import the wrapper module. The wrapper module would then use one the following calls to decide which version of your package to import: py> import sys py> sys.version '2.5 (r25:51908, Oct 10 2006, 03:45:47) \n[GCC 4.0.1 (Apple Computer, Inc. build 5363)]' py> sys.version_info (2, 5, 0, 'final', 0) James From sjmachin at lexicon.net Sat Sep 22 06:50:07 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Sep 2007 20:50:07 +1000 Subject: find difference in days from YYYYMMDD to YYYYMMDD In-Reply-To: References: Message-ID: <46f4f360@news.eftel.com.au> On 22/09/2007 7:37 PM, Konstantinos Pachopoulos wrote: > Hi, > does any body now any such algorith? to find difference in days from > YYYYMMDD to YYYYMMDD? The literal answer to your question is, unsurprisingly, "Yes". Now, what do you really want/need: (a) details of an algorithm so that you can code it in Python (b) an implementation of (a) (c) a hint that Python might already have a standard module for date calculations (d) a hint that there are things called search engines ... just copy your subject and paste it in > Or just an algorithm, that converts YYYYMMDD to seconds since the epoch? > There is no such thing as "the" (unqualified) epoch. Try days_difference(from_date=your_chosen_epoch, to_date=some_date) * 24 * 60 * 60 From sjmachin at lexicon.net Sat Sep 15 07:03:19 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Sep 2007 21:03:19 +1000 Subject: reading xls file from python In-Reply-To: References: <21903009.66741189806994236.JavaMail.www@wwinf4602> Message-ID: <46EBBBF7.8060003@lexicon.net> On 15/09/2007 1:50 PM, Gabriel Genellina wrote: > En Fri, 14 Sep 2007 18:56:34 -0300, escribi?: > >> I have installed python 2.5 for windows in my pc, I have a file xls >> say "file.xls" in c:/python25. How I can read this files from Python. >> Many thanks in advance. > > Try xlrd: http://www.python.org/pypi/xlrd In the interests of even-handedness: http://www.velocityreviews.com/forums/t352440-how-to-read-excel-files-in-python.html covers other possibilities. OT: A note for the OP: It is not a good idea to store your data files (example: file.xls) in the folder of some installed software (example: c:/python25). You may need to re-install the software and this may trash your data. Consider storing data files in folders whose names give some hint as to their contents. HTH, John From jstroud at mbi.ucla.edu Mon Sep 17 21:50:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 17 Sep 2007 18:50:52 -0700 Subject: Try this In-Reply-To: References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> Message-ID: <46EF2EFC.2040802@mbi.ucla.edu> Steve Holden wrote: > mensanator at aol.com wrote: >> Makes you wonder what other edge cases aren't >> handled properly. >> >> Makes you wonder why Microsoft doesn't employ >> professional programmers. >> > Makes *me* wonder why you haven't got better things to do with your time. Contributing to this thread is only slightly worse than just reading it in terms of wasting one's... Just a moment, I'm having an epiphany! From steve at REMOVE-THIS-cybersource.com.au Thu Sep 13 18:42:28 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Sep 2007 22:42:28 -0000 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189666095.727426.135170@o80g2000hse.googlegroups.com> <1189685403.306218.13270@22g2000hsm.googlegroups.com> <13eigagsuk74l55@corp.supernews.com> <1189712847.666826.230680@50g2000hsm.googlegroups.com> Message-ID: <13ejf6k4b29o8db@corp.supernews.com> On Thu, 13 Sep 2007 12:47:27 -0700, Carl Banks wrote: > On Sep 13, 9:55 am, Steven D'Aprano cybersource.com.au> wrote: >> On Thu, 13 Sep 2007 12:10:03 +0000, timothy.soehn... at gmail.com wrote: >> > Why not use '_' as the self variable. It is minimal and achieves >> > close to '.var', as '_.var' isn't that different. I know its a >> > little perl-esque, but its not a bad convention if you are aiming to >> > up readability of your code. >> >> I think the definitions of "up" or "readability" you are using are very >> different from mine. To me, to up something means to increase it, and >> readability means the ease of comprehension when reading something. You >> seem to be using the opposite definition for one or the other. > > > He's not. People who've never done a lot of numerical programming might > have a hard time understanding this, but what is considered readable for > "ordinary" programming is just does not apply when reading and writing > pages of mathematical formulae. Teaching your grandmother to suck eggs. I'm not a professional coder, but I'm not a stranger to numerical programming either. [snip] > The most readable numerical code looks as much like the printed > equations as possible. "self." is a distraction; it's not in the > original formula; it's boilerplate. It takes away from the readability > of the code. Assuming that you can't get rid of the attribute syntax, Why would you assume that? Go back to the beginning of this thread, and you'll see that I suggested that the Original Poster stop forcing his maths functions into classes and put them in functions where they belong. As far as I'm concerned, this thread has clearly evolved to no longer be specifically about the OP's problem that classes don't read like maths functions (that's a solved problem -- don't use classes) and is now discussing the generic issue that some people don't have good taste when it comes to programming languages. -- Steven. From s.mientki at id.umcn.nl Mon Sep 17 10:55:12 2007 From: s.mientki at id.umcn.nl (stef) Date: Mon, 17 Sep 2007 16:55:12 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <46e9b09c$0$7685$9b4e6d93@newsspool2.arcor-online.net> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> <5ktfb5F5ctrvU1@mid.individual.net> <46e98e01$0$30383$9b4e6d93@newsspool4.arcor-online.net> <46e9921e$0$26251$426a74cc@news.free.fr> <46e995d1$0$16120$9b4e6d93@newsspool1.arcor-online.net> <46e9b09c$0$7685$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <9825f$46ee9550$83aef404$1658@news2.tudelft.nl> Wildemar Wildenburger wrote: > stef mientki wrote: >> Wildemar Wildenburger wrote: >>> Bruno Desthuilliers wrote: >>> >>>> OTHO, simple math-illeterate programmers like me will have hard >>>> time maintaining such a code. >>>> >>> Certainly, but again: Such main people are not the intended >>> audience. The code is for people that know how to read these >>> equations. I think a general rule of (any form of) writing is to >>> write with your audience in mind. I always do that and happily, that >>> audience is usually naked. >>> >>> >>> >> Wouldn't Mathematica, Maple or MathCad be a far better choice ? >> > Well, those cost money ... Maxima doesn't cheers, Stef From torerik81 at gmail.com Sat Sep 15 04:08:33 2007 From: torerik81 at gmail.com (=?ISO-8859-1?Q?Tor_Erik_S=F8nvisen?=) Date: Sat, 15 Sep 2007 10:08:33 +0200 Subject: Just bought Python in a Nutshell In-Reply-To: <96f089100709150107t10275d23p6b8cb7be6e748b7f@mail.gmail.com> References: <1189784843.896396.108960@g4g2000hsf.googlegroups.com> <59f9c5160709141412q1098a4cbi989b6eed2f2cc899@mail.gmail.com> <46EB5B10.2020100@gmail.com> <96f089100709150107t10275d23p6b8cb7be6e748b7f@mail.gmail.com> Message-ID: <96f089100709150108t7619b726h42a6005892f80ed1@mail.gmail.com> Python in a nutshell also comes in a second edition: http://www.oreilly.com/catalog/pythonian2/index.html. Here, many of the new features in Python 2.5 are included. I haven't read through the first the edition, but I can honestly say that reading through the second edition has made me a better programmer, not just a better Python programmer. I only wish I'd read through it earlier, which would have saved me a lot of agony:) -Tor Erik From zentraders at gmail.com Sun Sep 2 10:17:27 2007 From: zentraders at gmail.com (Zentrader) Date: Sun, 02 Sep 2007 14:17:27 -0000 Subject: list index() In-Reply-To: <1188498199.557521.31700@z24g2000prh.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <1188498199.557521.31700@z24g2000prh.googlegroups.com> Message-ID: <1188742647.266967.33720@w3g2000hsg.googlegroups.com> On Aug 30, 11:23 am, zzbba... at aol.com wrote: > Neil, Steve, > > Thanks for the responses on sets. I have not used them before and was > not even aware Python had them. I will try them out. And if there weren't sets you would still not use find or index but a brute force method or dictionaries for each in dir_a_list : if each not in dir_b_list : print each, "not in dir_b" From deets at nospam.web.de Thu Sep 27 09:34:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Sep 2007 15:34:11 +0200 Subject: Confusion regarding constructor as default value References: <1190898221.833936.40480@57g2000hsv.googlegroups.com> Message-ID: <5m1pqjFb5l19U1@mid.uni-berlin.de> aine_canby at yahoo.com wrote: > Why are the following different? > > def AddRow(self, rowName, tableRow=TableRow(ReleaseDate(""), > ExpiryDate(""))): > # check to see if the row already exists, if not add it to the > container > > if not self.dict.has_key(rowName): > self.dict[rowName] = tableRow > > def AddRow(self, rowName, tableRow): > # check to see if the row already exists, if not add it to the > container > > if not self.dict.has_key(rowName): > self.dict[rowName] = TableRow(ReleaseDate(""), ExpiryDate("")) > > It seems that when I use the first function that I'm getting duplicate > objects in self.dict > > Thanks for your help, It's a FAQ. http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm Diez From facundobatista at gmail.com Mon Sep 10 16:25:11 2007 From: facundobatista at gmail.com (Facundo Batista) Date: Mon, 10 Sep 2007 17:25:11 -0300 Subject: Python tickets summary Message-ID: People: I modified my tool, whichs makes a summary of all the Python tickets (I moved the source where the info is taken from SF to our Roundup). In result, the summary is now, again, updated daily: http://www.taniquetil.com.ar/facundo/py_tickets.html Enjoy it. Regards, -- . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From guettli.usenet at thomas-guettler.de Wed Sep 19 05:32:27 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 19 Sep 2007 09:32:27 GMT Subject: AttributeError: How to list existing attributes? Message-ID: <5lc8lbF79ba8U1@mid.individual.net> Hi, how can you list the attributes of an object if you catch an AttributeError? I couldn't find a reference in the exception object, which points to the object. I want to call dir() on the object to list the user the known attributes. Is there a way to find the object by inspecting the stacktrace? Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From stefan.behnel-n05pAM at web.de Sun Sep 16 13:03:34 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 16 Sep 2007 19:03:34 +0200 Subject: SVG to raster conversion. In-Reply-To: References: Message-ID: <46ED61E6.9010500@web.de> J. Cliff Dyer wrote: > Does anybody know a good solution (preferably in python) for rasterizing > SVG or other vector graphics. > > I'm thinking something like > > vector_image = SVGFile(path_to_image) > raster_image = vector_image.rasterize(format, (width, height), dpi) > raster_image.write(out_file) > > Thanks for any pointers you might have. The GIMP can do it, and you can even program it in Python. Stefan From googlegroupie at coloraura.com Sun Sep 30 13:12:22 2007 From: googlegroupie at coloraura.com (Daniel Pitts) Date: Sun, 30 Sep 2007 17:12:22 -0000 Subject: which language allows you to change an argument's value? In-Reply-To: <1191149233.346818.246170@22g2000hsm.googlegroups.com> References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> Message-ID: <1191172342.592020.116230@k79g2000hse.googlegroups.com> On Sep 30, 3:47 am, Summercool wrote: > I wonder which language allows you to change an argument's value? > like: > > foo(&a) { > a = 3 > > } > > n = 1 > print n > > foo(n) # passing in n, not &n > print n > > and now n will be 3. I think C++ and PHP can let you do that, using > their reference (alias) mechanism. And C, Python, and Ruby probably > won't let you do that. What about Java and Perl? > > is there any way to prevent a function from changing the argument's > value? > > isn't "what i pass in, the function can modify it" not a desireable > behavior if i am NOT passing in the address of my argument? For one > thing, if we use a module, and call some functions in that module, and > the module's author made some changes to his code, then we have no way > of knowing what we pass in could get changed. Of course, if it is in > Java, Python, and Ruby, and we pass in a reference to object (not C+ > +'s meaning of alias reference), so the object can get changed, but > that can be expected, vs passing in n, when n = 1. Even when it is > Ruby, when everything is an object, passing n in when n = 1 won't ever > make n become 3. Is there a way to prevent it from happening in the > languages that allows it? Some would say that in truely good OO design, the state should be protected by the object (not the constness of the reference to the object) From jeff at jmcneil.net Wed Sep 12 16:15:06 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 12 Sep 2007 16:15:06 -0400 Subject: xmlrpclib and SimpleXMLRPCServer questions In-Reply-To: <1189626704.033328.9500@k79g2000hse.googlegroups.com> References: <1189626704.033328.9500@k79g2000hse.googlegroups.com> Message-ID: <82d28c40709121315k375dee7eu902261f1d0f0aaf@mail.gmail.com> Have a look at the XMLRPC specification @ http://www.xmlrpc.com/spec. There is no representation of NULL/None, thus server refuses to Marshall the 'None' value. Update your server methods to return a value other than None and that message will go away. The other option is to set 'allow_none' to True on the Marshaller object. Doing so will turn your 'None' return values into XML-RPC '' entities. The 'nil' type is defined as an XMLRPC extension (I'm not sure how widely adopted it is, though). See http://ontosys.com/xml-rpc/extensions.php. I'm not sure you can do that without inheriting from the dispatcher code and "rolling your own." I find it much easier to 'return True' and ignore the value. -Jeff On 9/12/07, xkenneth wrote: > So i've been trying to set up a simple server and client through > XMLRPC in python. > > Here's my code: > > SERVER > > import SimpleXMLRPCServer > > > class DataServer: > def __init__(self): > pass > > def test(self,test): > self.this = test > > def show(self): > print self.this > > server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8005)) > server.register_instance(DataServer()) > server.serve_forever() > > CLIENT > import xmlrpclib > server = xmlrpclib.Server('http://localhost:8005') > server.test(5) > server.show() > > > Now, I'm getting the most odd callback from the client side: > > >>> server.show() > Traceback (most recent call last): > File "", line 1, in ? > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/ > lib/python2.4/xmlrpclib.py", line 1096, in __call__ > return self.__send(self.__name, args) > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/ > lib/python2.4/xmlrpclib.py", line 1383, in __request > verbose=self.__verbose > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/ > lib/python2.4/xmlrpclib.py", line 1147, in request > return self._parse_response(h.getfile(), sock) > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/ > lib/python2.4/xmlrpclib.py", line 1286, in _parse_response > return u.close() > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/ > lib/python2.4/xmlrpclib.py", line 744, in close > raise Fault(**self._stack[0]) > xmlrpclib.Fault: unless allow_none is enabled'> > > What is causing this? The server recieves the data and seems to > respond properly regardless of this error, so by all means i can > always catch it, but that sounds stupid. > > Here I can verify the server process is indeed recieving the data > (calling the client with two different values): > > localhost - - [12/Sep/2007 14:35:18] "POST /RPC2 HTTP/1.0" 200 - > 5 > localhost - - [12/Sep/2007 14:35:41] "POST /RPC2 HTTP/1.0" 200 - > 10 > > Looking at the documentation: > > class SimpleXMLRPCServer( addr[, requestHandler[, > logRequests[allow_none[, encoding]]]]) > > I'm not sure how to specify the allow_none value or it's type, how can > i find out more? > > Thanks for the help! > > Regards, > Ken > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Mon Sep 17 15:16:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Sep 2007 16:16:11 -0300 Subject: return codes from os.spawn References: <014901c7f91c$52493b40$9817100a@INDIALASON.COM> Message-ID: En Mon, 17 Sep 2007 08:17:22 -0300, Nirmal escribi?: > Hi, > > When I try running java through os.spawnv with P_NOWAIT, it returns the > process id > >>>> os.spawnv(os.P_NOWAIT, '$JAVA_HOME/bin', ('java', '$JAVA_HOME/bin/java > ex3178 true')) > 19524 > > then I removed the command line parameter in the java command to fail > ( it > should throw an exception) the process and ran it. This time also it > returned the process id . > >>>> os.spawnv(os.P_NOWAIT, '$JAVA_HOME/bin', ('java', '$JAVA_HOME/bin/java > ex3178')) > 21947 > > > And I tried the same by using P_WAIT and it returned the same exit code > >>>> os.spawnv(os.P_WAIT, '$JAVA_HOME/bin', ('java', '$JAVA_HOME/bin/java > ex3178 true)) > 127 >>>> os.spawnv(os.P_WAIT, '$JAVA_HOME/bin', ('java', '$JAVA_HOME/bin/java > ex3178')) > 127 > please let me know how can we identify that the process is completed > successfully or not ? All your examples fail to execute your program. The second argument is the program being executed, not only the directory. Should be the same as the first element of `args`. And the individual arguments should be separated. os.spawnv(os.P_WAIT, '$JAVA_HOME/bin/java', ['$JAVA_HOME/bin/java', 'ex3178', 'true']) In this case it's easier to use spawnl: os.spawnl(os.P_WAIT, '$JAVA_HOME/bin/java', 'java', 'ex3178', 'true') -- Gabriel Genellina From laurent.pointal at limsi.fr Wed Sep 19 04:19:04 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 19 Sep 2007 10:19:04 +0200 Subject: lxml codespeak pages empty ? Come back. In-Reply-To: References: Message-ID: Laurent Pointal a ?crit : > I can no longer get codespeak's lxml page at http://codespeak.net/lxml/ > (get an empty HTML document Transitional//EN">)... > > > Am-I alone in this case ? > Any codespeaker reading ? It magically come-back.... From kyosohma at gmail.com Tue Sep 4 11:01:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 04 Sep 2007 15:01:54 -0000 Subject: Calling a dos batch file from python In-Reply-To: <1188913362.279426.290370@r34g2000hsd.googlegroups.com> References: <1188913362.279426.290370@r34g2000hsd.googlegroups.com> Message-ID: <1188918114.131796.302250@19g2000hsx.googlegroups.com> On Sep 4, 8:42 am, n o s p a m p l e a s e wrote: > Suppose I have a batch file called mybatch.bat and I want to run it > from a python script. How can I call this batch file in python script? > > Thanx/NSP The subprocess module should work. Mike From jd at nospam.com Thu Sep 13 03:56:20 2007 From: jd at nospam.com (Jd) Date: Thu, 13 Sep 2007 00:56:20 -0700 Subject: hang in multithreaded program / python and gdb. Message-ID: Hi I want to debug a locking situation in my program. http://wiki.python.org/moin/DebuggingWithGdb Where do I get binaries for ? - debug python 2.5 binary/rpm for FC7 Also, the description of the hang is as follows. 2 therads waiting in sem_wait at GLIBC_2.0 ... from PyThread_acquire_lock() 1 thread in _poll from _socketmodule.so. Any ideas what might be going on. (Isnt PyThread_acquire_lock() trying to get the global interpreter lock ?) Any help.. pointers are welcome. Thanks /Jd From conra2004 at yahoo.com Sun Sep 23 10:21:33 2007 From: conra2004 at yahoo.com (yadin) Date: Sun, 23 Sep 2007 07:21:33 -0700 Subject: building a GUI Message-ID: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> if i were up to make a GUI chich are the advantages of choosing python over matlab or java? From gagsl-py2 at yahoo.com.ar Sun Sep 23 17:16:20 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 23 Sep 2007 18:16:20 -0300 Subject: Small changes in side library References: <1190509647.227883.226460@d55g2000hsg.googlegroups.com> Message-ID: En Sat, 22 Sep 2007 22:07:27 -0300, maxim.gavrilov at gmail.com escribi?: > I have the side library which provides wide set of different > functions, but I'm going to replace some of them with mine and > provided such 'modified' library thought my project. > > The following way works well for my purpose: > > ------- mylib.py ------- > import sidelib > > import os, sys, .... > > def func(): > ..... > sidelib.func = func > ...... > ?!?!?!?! > -------------------------- > > But this cause to write mylib.sidelib.func() to function call, is it > any way to 'map' definitions from sidelib to mylib (possible at point > marked ?!?!?!?!) such that constructions like mylib.func() will be > provided and client code don't see difference between changed and > original library in syntax way? Your code already works as you like: import sidelib sidelib.func() and you get the modified function. You don't have to say mylib.sidelib.func - in fact, mylib.sidelib is the same module object as sidelib But you have to ensure that the replacing code (mylib.py) runs *before* anyone tries to import something from sidelib. > One my idea was to do from sidelib import * and then modify globals() > dictionary, but this isn't good too because mylib imports many other > modules and they all mapped into it's namespace (like mylib.os, > mylib.sys). As you said, a bad idea. -- Gabriel Genellina From deets at nospam.web.de Fri Sep 21 07:26:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Sep 2007 13:26:25 +0200 Subject: Who can develop the following Python script into working application ? References: <1190334828.210230.293980@50g2000hsm.googlegroups.com> <1190372423.768184.60080@19g2000hsx.googlegroups.com> Message-ID: <5lho31F84jgjU1@mid.uni-berlin.de> > Please help and let me know your terms. There are websites dedicated to this - like e.g. http://www.guru.com/ Make an offer there. Diez From http Sat Sep 22 05:28:54 2007 From: http (Paul Rubin) Date: 22 Sep 2007 02:28:54 -0700 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87odfxjgjy.fsf@pobox.com> <7x4phpt9nf.fsf@ruckus.brouhaha.com> <87wsuj4152.fsf@pobox.com> Message-ID: <7xabrf2gmh.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > > I think mousing takes more mental work than typing, > I'm not sure this is a matter for debate, as much as physical > measurement. I don't know of any way to physically measure mental work. From horpner at yahoo.com Fri Sep 14 12:59:55 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 14 Sep 2007 16:59:55 GMT Subject: where is help file? References: <13el4vvna6jildc@corp.supernews.com> <46eab4bc$0$3811$5402220f@news.sunrise.ch> Message-ID: On 2007-09-14, Carsten Haese wrote: > On Fri, 2007-09-14 at 18:20 +0200, Martin Blume wrote: >> AFAIK you have to import the module first, before you can get >> help on that module. > > While that is true of the help(module_name) form, this is not > necessary in the interactive helper you start by calling > help(). The interactive help function is cool. You need to download and install the HTML version of the standard docs to take the utmost advantage of it. -- Neil Cerutti From gandalf at designaproduct.biz Thu Sep 13 05:59:51 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 13 Sep 2007 11:59:51 +0200 Subject: I want py2exe not to create library.zip In-Reply-To: <3P6dnfdlGPbez3XbnZ2dnUVZ_oaonZ2d@comcast.com> References: <3P6dnfdlGPbez3XbnZ2dnUVZ_oaonZ2d@comcast.com> Message-ID: <46E90A17.303@designaproduct.biz> > That is correct. People want less files to distribute not more. People > complain on py2exe list that it doesn't create a single .EXE file. Don't > try to update the program via patching "pieces". Wrap everything in a proper > installer (I use and highly recommend Inno Setup). It can handle version > control, there is a plug-in for over-the-wire updates, etc. Best way I know of > to automate everything. > It would be the best way for Windows. My program must work on different platforms: FreeBSD, Linux MS Windows and possibly Mac OS. 1. It would be too difficult to create an different auto updating method for MS Windows. 2. My auto update method updates only the changed .py files. Hopefully I will have many users. I do not want them to download a 10MB inno setup file after a small change in a py file. The skip_archive option is the best. Thank you so much! Laszlo From super.sgt.pepper at gmail.com Fri Sep 21 18:36:32 2007 From: super.sgt.pepper at gmail.com (Cristian) Date: Fri, 21 Sep 2007 22:36:32 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190413322.962737.53900@r29g2000hsg.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> Message-ID: <1190414192.636397.146450@57g2000hsv.googlegroups.com> On Sep 21, 3:22 pm, chris.monsa... at gmail.com wrote: > On Sep 21, 6:07 pm, Cristian wrote: > > > > > On Sep 21, 2:48 pm, chris.monsa... at gmail.com wrote: > > > > There are already anonymous functions in Python. > > > > lambda x, y, z: x + y + z > > > > is the same as: > > > > def _(x, y, z): return x + y + z > > > > As for the method stuff, check out staticmethod(). If you assign > > > staticmethod() to an object, it will be treated as a > > > normal function and not as a "method." > > > > I have my own personal opinions about how methods should be in Python, > > > but, whatever. It's weird to deal with stuff like this: > > > > x.y = re.match # Assign a function to an attribute of a class, but it > > > doesn't work because you can't assign anything but methods! > > > x.y = staticmethod(re.match) # Ugly > > > True, there is lambda, but that is very limited. It might be useful > > for key arguments, but not much else. It doesn't solve the teaching > > problem of "See, functions are just like any other data type. You can > > assign it to a variable." It would be a footnote if it's mentioned at > > all. My hope is to subtly reinforce the notion that functions are data > > and can be passed around. The current function declaration doesn't > > help with this. Creating a function and assigning it to a name is > > exactly what Python does, why not have it come out in the syntax? It's > > not necessary, yes, but I think it would be helpful for teaching > > purposes. > > > Again, it's not necessary as much as it's more intuitive and obvious > > what's going on. This helps a beginner sort out the process from the > > syntax without taking it on faith. They can see the class declaration > > and see "I'm defining just another attribute to this class only this > > time it happens to be method". > > > There is nothing functionally lacking in Python. I'm just curious if > > there's anything Python can do syntax-wise to help a person better > > grasp programming ideas and Python's inner workings. > > Guido apparently doesn't like lambda; I'm not really sure why, it's > extremely useful. There were rumors of it leaving in Python 3000, but > thankfully there was the decision to keep them. (I have a feeling if > they weren't kept in, a project fork would have happened or such.) > Anyway, one of the biggest problems implementation wise is indentation > in an expression - there is no expression currently that uses > significant whitespace. Python draws a pretty clear line between > expression and statement. I do agree with you however, it seems as if > there is an arbitrary line between function definitions and normal > variable assignment that shouldn't be there for the sake of > consistency. > > A question: if you WERE to implement function definitions as normal > expressions, how would you go about embedding it within an expression? > > x = map(def a: > > > > , [1, 2, 3]) > > It looks hideous in my opinion and lining up the , with the def is > ugly. Not to mention currently, inside groupings, whitespace is > ignored. How would you handle a whitespace signif. expression inside a > grouping which by definition ignores whitespace? Yeah, I agree, that does look pretty ugly. Correct me if I'm wrong, but I thought the way Python determines a block is by the whitespace of the first line. So, as long as the spacing (or !tabbing!) is consistent from line to line the parser will know it's part of the same block. From that I don't think the parser would have much trouble extracting the function definition from the above example. I would change the word "def". That's never been informative enough for me. I would follow Javascript and call it "function." Also, I think parentheses should be required. If there's no implementation problem, I don't see why Python shouldn't allow the above example, but I would certainly discourage it. Just like Python doesn't prevent you from writing an insanely long and convoluted function, Python shouldn't enforce any arbitrary length in anonymous functions. I think the above example should be discouraged as a style violation, not syntax. From sbassi at clubdelarazon.org Mon Sep 17 09:32:26 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Mon, 17 Sep 2007 10:32:26 -0300 Subject: Saving parameters between Python applications? In-Reply-To: <1190032732.277479.221680@o80g2000hse.googlegroups.com> References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> <1190032732.277479.221680@o80g2000hse.googlegroups.com> Message-ID: <9e2f512b0709170632l461136b6sf8f98225ded3b3ea@mail.gmail.com> On 9/17/07, Stodge wrote: > Good idea, but I can't guarantee that the two scripts will be run from > the same directory - so where to store the pickle? It doesn't matter if is the same directory or not, as long as both programs has access to the pickle file (one program should have write access and the other program should have at least read access). -- Sebasti?n Bassi (???????). Diplomado en Ciencia y Tecnolog?a. Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From brenNOSPAMbarn at NObrenSPAMbarn.net Thu Sep 13 13:17:49 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Thu, 13 Sep 2007 17:17:49 GMT Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <13eim00ha4lf356@corp.supernews.com> Message-ID: Steven D'Aprano wrote: >> And I agree with the OP that the convention is really annoying. >> >> self.rect.width = self.foo(self.rect.x + self.rect.y) * self.boo() >> >> is much less concise than >> >> s.rect.width = s.foo(s.rect.x + s.rect.y) * s.boo() > > > Y do u thnk bng cncis is lwys a gd thng? No, but the point being made is that it would be better IN THIS CASE. -- --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 steve at holdenweb.com Tue Sep 4 09:42:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Sep 2007 06:42:24 -0700 Subject: REGULAR EXPRESSION In-Reply-To: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> References: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> Message-ID: AniNair wrote: > hi.. I am trying to match '+ %&/-' etc using regular expression in > expressions like 879+34343. I tried \W+ but it matches only in the > beginning of the string Plz help Thanking you in advance... > Perhaps you could give a few example of strings that should and shouldn't match? It isn't clear from your description what pattern you are trying to find. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From gagsl-py2 at yahoo.com.ar Mon Sep 24 22:40:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Sep 2007 23:40:31 -0300 Subject: Regular Expressions: Can't quite figure this problem out References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> Message-ID: En Mon, 24 Sep 2007 23:17:59 -0300, Robert Dailey escribi?: > On 9/24/07, Gabriel Genellina wrote: >> >> Yes: forget about regular expressions. ElementTree does that for free: > > That's not an option. Ok, keep fighting with REs - good luck! -- Gabriel Genellina From pyth0nc0d3r at gmail.com Tue Sep 18 17:01:39 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Tue, 18 Sep 2007 16:01:39 -0500 Subject: How would I go about checking if a authentication login actually exists. Message-ID: Okay, I've written this script to check if a password works right, but how do I know if an authentication actually exists? -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: main2.py URL: From Sean.Sugrue at analog.com Fri Sep 28 10:57:56 2007 From: Sean.Sugrue at analog.com (Sugrue, Sean) Date: Fri, 28 Sep 2007 10:57:56 -0400 Subject: OCBC connection Message-ID: <8FDC0F9BE1F91D44BE964AA54AAA67B629B33F88@wilmexm3.ad.analog.com> I'm trying to make an odbc connection to postgresql which is on a server using python. Does anyone have a code snippet to make a basic connection with a select query? Sean From DouhetSukd at gmail.com Fri Sep 14 11:47:23 2007 From: DouhetSukd at gmail.com (DouhetSukd at gmail.com) Date: Fri, 14 Sep 2007 08:47:23 -0700 Subject: Just bought Python in a Nutshell In-Reply-To: References: Message-ID: <1189784843.896396.108960@g4g2000hsf.googlegroups.com> I respectfully disagree with Shawn, in this case. Don't skim Nutshell, unless you know very little Python, and even then it is really the wrong book. It is rather dry reading and provides very little of the usual user-friendly introductions to language features by solving simple problems. Doesn't sound like that much of an endorsement, does it? Well, in fact, it is pretty much my most used Python book (out of 7 or 8 others). If you read Alex's posts in this newsgroup, you'll see that he is one of the most pragmatic and rigorous posters who usually contributes code that elegantly and simply solves the issue at hand with the minimum amount of clutter. What Python in a Nutshell is really good at is showing you exactly what Python is capable of doing, feature by feature, in a thoroughly Pythonic way for the feature. With code and exact implication. For example, I know Python well but I am kinda lacking in metaclass comprehension. If I were to write some non-trivial metaclasses I would surely have his 3 or 4 pages open on my desk as I write code and skim through other internet postings. Those 3-4 pages have kinda made my brain shrivel every time I've looked at them, but they are the clearest overview I've seen of what is probably one of the hardest Python features to understand. For normal, easy-to-understand Python, Nutshell really dissects the languages with new insight. The information is dense, because each word has its place and there very little filler. That's why skimming it does not work for me, I just don't have the requisite sustained attention span. So, although I read almost all other computer books like Shawn does, I don't think it applies in this particular case. When you have a particular aspect of Python in mind, use Nutshell. Read up on 'look before you leap' in it if you really want a sample of how it is written. Cheers From attn.steven.kuo at gmail.com Thu Sep 6 10:22:51 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 06 Sep 2007 07:22:51 -0700 Subject: startswith( prefix[, start[, end]]) Query In-Reply-To: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> References: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> Message-ID: <1189088571.239870.5020@d55g2000hsg.googlegroups.com> On Sep 6, 7:09 am, cj... at bath.ac.uk wrote: > Hi > > startswith( prefix[, start[, end]]) States: > > Return True if string starts with the prefix, otherwise return False. > prefix can also be a tuple of suffixes to look for. However when I try > and add a tuple of suffixes I get the following error: > > Type Error: expected a character buffer object > > For example: > > file = f.readlines() > for line in file: > if line.startswith(("abc","df")) > CODE > > It would generate the above error > (snipped) You see to be using an older version of Python. For me it works as advertised with 2.5.1, but runs into the problem you described with 2.4.4: Python 2.5.1c1 (r251c1:54692, Apr 17 2007, 21:12:16) [GCC 4.0.0 (Apple Computer, Inc. build 5026)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> line = "foobar" >>> if line.startswith(("foo", "bar")): print line ... foobar >>> if line.startswith(("foo", "bar")): ... print line ... foobar VS. Python 2.4.4 (#1, Oct 18 2006, 10:34:39) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> line = "foobar" >>> if line.startswith(("foo", "bar")): print line ... Traceback (most recent call last): File "", line 1, in ? TypeError: expected a character buffer object -- Hope this helps, Steven From steve at holdenweb.com Mon Sep 24 14:27:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Sep 2007 14:27:35 -0400 Subject: calling the function of one class from another class In-Reply-To: <3a4a8f930709220328h1ae25d10jd772e265cd298bcd@mail.gmail.com> References: <33dffc910709220024l74b14267v93564df10f5af9a6@mail.gmail.com> <3a4a8f930709220328h1ae25d10jd772e265cd298bcd@mail.gmail.com> Message-ID: Furkan Kuru wrote: > > > On 9/22/07, *Mridula Ramesh* > wrote: > > hi. > > i currently have code structured like this: > > classA(): > def __init__(): > .............. > .............. > > def fnc1(): > .................... > .................... > > > classB(): > def __init__(): > ........................ > ........................ > classA.fnc1() #this is where i get an error > > > TypeError: unbound method fnc1() must be called with classA instance > as first argument (got nothing instead) > > when i do fnc1(classA) i get: > > NameError: global name 'fnc1' is not defined > > am i violating some programming rule by trying to call fnc1 in > classB? i am only now learning OO alongside python, so i'm not sure! > also, can someone please tell me where to go for more articles on > the classes and functions and calling them from other places? > > thanks a lot! > > mridula. > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > you should create an instance of ClassA: > > a = ClassA() > a.fnc1() > Unfortunately this won't work either, as calling the method on an instance will automatically provide the instance as the first argument to the method call, but the method is defined to take no arguments. > or if you want a static function you should declare the method as static > > classA(): > def __init__(): > .............. > .............. > @staticmethod > def fnc1(): > .................... > .................... Although most often if you want a static function you should just define ... a function! The OP should read through the tutorial, or at least those sections dealing with function and class definitions. It appears (s)he may be trying to write Java in Python. That's never a satisfactory experience. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From thn at mail.utexas.edu Wed Sep 5 13:56:29 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: Wed, 05 Sep 2007 10:56:29 -0700 Subject: Looping through File Question In-Reply-To: <1188997229.977198.23100@22g2000hsm.googlegroups.com> References: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> <1188992047.858695.174790@r34g2000hsd.googlegroups.com> <1188995195.932117.111440@k79g2000hse.googlegroups.com> <1188997229.977198.23100@22g2000hsm.googlegroups.com> Message-ID: <1189014989.636557.265700@k79g2000hse.googlegroups.com> > > > On Sep 5, 8:58 pm, planetmatt wrote: > > > > > I am a Python beginner. I am trying to loop through a CSV file which > > > > I can do. What I want to change though is for the loop to start at > > > > row 2 in the file thus excluding column headers. The DictReader object automatically does this for you: >>> data = """Name,age,job ... Tom,21,programmer ... Sara,22,chef ... Molly,23,doctor""" >>> from csv import DictReader >>> myStuff = DictReader(data.split('\n')) >>> for line in myStuff: ... print line ... {'job': 'programmer', 'age': '21', 'Name': 'Tom'} {'job': 'chef', 'age': '22', 'Name': 'Sara'} {'job': 'doctor', 'age': '23', 'Name': 'Molly'} HTH, Tom From yosuke at ccwf.cc.utexas.edu Mon Sep 3 14:00:08 2007 From: yosuke at ccwf.cc.utexas.edu (yosuke at ccwf.cc.utexas.edu) Date: Mon, 3 Sep 2007 18:00:08 +0000 (UTC) Subject: trap setting attribute when the attribute is dict Message-ID: Hello all, I have a question which might be simple or need some work around. I want to do something like this. My class/instance has a dict as a property. I want the instance to catch the change in the dict (change in some values, addition/deletion of key/value etc) to be recognized by the class instance. How can I do this? Any suggestions are very well appreciated. Here is an example of what I want my class to behave: class test(object): def __init__(self): self._d = {} self._changed = False def getd(self): print 'called getd' return self._d # dont know what to do next def setd(self,val): print 'called setd', key, val self._d[key] = val self._changed = True d = property(getd,setd,None,None) def getc(self): return self._changed changed = property(getc,None,None,None) if __name__ == '__main__': obj = test() print 'obj.changed = ', obj.changed print # I want obj to know that its propety d being changed here print "t.d['a'] = 1" obj.d['a'] = 1 print # I want the "changed" property to be True print 'obj.changed = ', obj.changed -- yosuke kimura Center for Energy and Environmental Resources The Univ. of Texas at Austin, USA From jeremy+complangpython at jeremysanders.net Wed Sep 12 08:17:55 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Wed, 12 Sep 2007 13:17:55 +0100 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> Message-ID: Charles Fox wrote: > I've just started playing around with Python, as a possible > replacement for a mix of C++, Matlab and Lisp. The language looks > lovely and clean with one huge exception: I do a lot of numerical > modeling, so I deal with objects (like neurons) described > mathematically in papers, by equations like I thought it was horrible when I started, but now when looking at somebody else's C++ code I find it very hard to work out whether something is a global, a member or a local variable, unless they use some sort of naming convention. If you alias self as "s", it's only two more characters per variable access, which is the same as the C++ "m_" naming convention. -- Jeremy Sanders http://www.jeremysanders.net/ From kyosohma at gmail.com Fri Sep 7 09:42:20 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 07 Sep 2007 13:42:20 -0000 Subject: wxPython unexpected exit In-Reply-To: <1189152617.169438.296630@d55g2000hsg.googlegroups.com> References: <1189152617.169438.296630@d55g2000hsg.googlegroups.com> Message-ID: <1189172540.784080.231440@22g2000hsm.googlegroups.com> On Sep 7, 3:10 am, Jimmy wrote: > Hi, wxPython is cool and easy to use, But I ran into a problem > recently when I try to write a GUI. > The thing is I want to periodically update the content of StatixText > object, so after create them, I pack them into a list...the problem > comes when I later try to extract them from the list! I don't know > why? > my code is as following: > > import wx, socket > import thread > > class MyFrame(wx.Frame): > > firstrun = 0 > def __init__(self): > wx.Frame.__init__(self, None, -1, 'Notifier') > self.panel = wx.Panel(self, -1) > self.length = 50 > self.scale = 0.6 > self.count = 5 > self.size = wx.Frame.GetSize(self) > self.distance = self.size[1] / self.count > self.labellist = [] > self.gaugelist = [] > > def ParseAndDisplay(self, data): > print "Successful access to main Frame class" > print 'And receive data: ', data > if MyFrame.firstrun == 0: > print 'First time run' > items = 3 > for i in range(items): > self.labellist.append(wx.StaticText(self.panel, -1, data+str(i), > (150, 50+i*20), (300,30))) > MyFrame.firstrun = 1 > else: > self.labellist[0].SetLabel('AAA')//PROGRAM WILL ABORT HERE!!! > self.labellist[1].SetLabel("Guo") > self.labellist[2].SetLabel("Qiang") > > class NetUdp: > > def __init__(self): > self.port = 8081 > self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > self.s.bind(("", self.port)) > print "Listening on port", self.port > > def recvdata(self): > data, addr = self.s.recvfrom(1024) > return data > > def netThread(): > netudp = NetUdp() > while True: > data = netudp.recvdata() > frame.ParseAndDisplay(data) > > if __name__ == '__main__': > firstrun = 0 > app = wx.PySimpleApp() > frame = MyFrame() > frame.Show() > # start network thread first > id = thread.start_new_thread(netThread, ()) > # main wxpython loop begins > app.MainLoop() > > I know the code is ugly, but can anyone really save me here! If you use threads that update the GUI, you need to take a look at the following wiki page: http://wiki.wxpython.org/LongRunningTasks I've used the techniques therein and they *just work*. I'm not sure if you can set values on items in a list or not. I've tried that sort of thing and sometimes it works and sometimes it doesn't. The wxPython group is probably the best place to ask these questions anyway: http://www.wxpython.org/maillist.php Mike From michele.simionato at gmail.com Wed Sep 12 08:46:45 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 12 Sep 2007 12:46:45 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: <13efnmi4n959a59@corp.supernews.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <13efnmi4n959a59@corp.supernews.com> Message-ID: <1189601205.503841.327170@o80g2000hse.googlegroups.com> On Sep 12, 2:42 pm, Steven D'Aprano wrote: > On Wed, 12 Sep 2007 07:33:45 +0000, Mark Summerfield wrote: > In fact, I'm not sure what people mean by ordered dicts. I assume they > mean the keys are ordered, not the values. But ordered by what? Insertion > order? Modification order? Alphabetical order? Insertion order. M.S. From kay.schluehr at gmx.net Sat Sep 22 03:47:37 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 22 Sep 2007 00:47:37 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <7xlkazgpc5.fsf@ruckus.brouhaha.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> Message-ID: <1190447257.060479.141280@n39g2000hsh.googlegroups.com> On 22 Sep., 08:56, Paul Rubin wrote: > Kay Schluehr writes: > > If you feel you can transform it into another unambigous grammar > > mixing statements and expressions it's up to you. > > We got rid of the print statement for python 3.0. Why not get rid > of the rest of them too? Just use expressions for everything, as > works fine for plenty of other languages. One might create a new dynamic functional+OO programming language, where small statements like print, assert, raise etc. all become functions and statements like while, for, with etc. become anonymous closures. I think Logix had gone once in this direction but was abandoned due to severe technical problems. So one might eventually revive this project with another more sound technical base. Personally I'm not sure it's worth a large effort and whether EasyExtend is the right toolkit at hand. So it's definitely not Guido who will revive it and also not me. Maybe some PyPy guys? What are we talking about - really? From mail at timgolden.me.uk Thu Sep 27 12:06:04 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Sep 2007 17:06:04 +0100 Subject: Cross-platform time out decorator In-Reply-To: References: <1190802115.585306.250400@o80g2000hse.googlegroups.com> <1190899882.702911.44670@w3g2000hsg.googlegroups.com> <87k5qc18gf.fsf@mulj.homelinux.net> <1190907553.425261.273400@w3g2000hsg.googlegroups.com> Message-ID: <46FBD4EC.8040207@timgolden.me.uk> Steve Holden wrote: > Joel wrote: >> On Sep 27, 4:36 pm, Hrvoje Niksic wrote: >>> Joel writes: >>>> I found the solution : >>>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440569 >>>> describes a solution based on threads. I tested it and it works >>>> perfectly. >>> Note that, unlike the original alarm code, it doesn't really interrupt >>> the timed-out method, it just returns the control back to the caller, >>> using an exception to mark that a timeout occurred. The "timed out" >>> code is still merrily running in the background. I don't know if it's >>> a problem in your case, but it's an important drawback. >> There should be a method to stop the thread though? I've never >> programmed thread stuff in python and wasn't able to find how to do >> it, would you happen to know how to "kill" the timed out thread? >> > There is no way to "kill" a thread, other than set a flag and have the > thread read it to realise the main thread wants it to stop. This is more-or-less why I suggested earlier that you wouldn't find anything straightforward. The signal mechanism, as far as I know, is pretty much unique in terms of the support it gets from the OS and the language combined. Any other solution will end up papering over cracks. TJG From ziade.tarek at gmail.com Thu Sep 6 16:10:06 2007 From: ziade.tarek at gmail.com (Tarek) Date: Thu, 06 Sep 2007 20:10:06 -0000 Subject: Similarities between two modules Message-ID: <1189109406.842053.134260@r34g2000hsd.googlegroups.com> Hello, I am looking for some python library that would help me to find similarities between two modules of Python code. I am already playing with the levensthein distance but I am looking for some tool that would play with the tree code with stronger tests. Any hint ? (or even a recipe) regards Tarek Ziad? From jcd at sdf.lonestar.org Sun Sep 16 16:52:48 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Sun, 16 Sep 2007 16:52:48 -0400 Subject: Python "with" In-Reply-To: References: Message-ID: <46ED97A0.3070707@sdf.lonestar.org> Ivan Voras wrote: > Hi, > > I'm looking for a construct that's similar to (Turbo) Pascal's "with" > statement. I read about the Python's new "with" statement, but I was > dissapointed to learn that it does something different (I still don't > see how it's better than try..except..finally, but that's not my question). > > Is there something similar to what I want that's Pythonic enough? > > (If you're not familiar with Pascal, here's how it works: > > with some.big.structure.or.nested.objects.element do begin > member1 := something; > member2 := something; > end; > > which exactly translates to this equivalent: > > some.big.structure.or.nested.objects.element.member1 := something; > some.big.structure.or.nested.objects.element.member2 := something; > > i.e. it's a wrist-saver. I think a similar feature exists in C99, for > structs. > > I know it can be almost always done by using a temporary variable: > > tmp = some.big.structure.or.nested.objects.element > tmp.member1 = something > tmp.member2 = something > You can import the members directly, using: >>> from some.big.structure.or.nested.objects.element import member1, member2 which requires you to know the variable names. But if you want to do it after the import, your tmp example is the way to go. It would be less ugly if your variable is named so that it still has some connection to the purpose of the module. There are other options, too: >>> import some.big.structure.or.nested.objects.element as tmp This will still make you prefix tmp to the variables, but you don't need a separate statement devoted to rebinding the module to a new name. Personally, I don't find the shorter prefix all that ugly. For me ugliness and clarity are almost entirely synonymous when it comes to code, so maintaining the certainty about where the variables came from is a good thing. I've just started a job where I have to maintain perl code, so I keep running across things like use File::Basename; my $dir = dirname($fullpath); and I keep wondering where basename came from. Is it a builtin? Was it from File:: A prefix, no matter how short, how obscure, how undescriptive, will let you trace exactly where each name came from. Which I find deeply beautiful. All you have to do is look up the page, and it's there somewhere. You *can* do the same with Perl, but it's actually discouraged by the structure of the language. In other words, the simplest case does the wrong thing. Python does allow you to import all names from a module, unprefixed but it leads you into the same ugliness and namespace clobbering that you get with Perl, so I'm not going to tell you how to do it. I think the 'import long.name as short' syntax will help your wrists the most while still retaining the clarity of explicit module referencing. And you won't have the extraneous assignment (tmp = long.name) cluttering up your code. Cheers, Cliff From bbxx789_05ss at yahoo.com Thu Sep 27 07:18:14 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 27 Sep 2007 04:18:14 -0700 Subject: Simple threading example freezes IDLE? In-Reply-To: References: <1190218626.334442.255450@57g2000hsv.googlegroups.com> Message-ID: <1190891894.679630.202880@w3g2000hsg.googlegroups.com> On Sep 26, 5:01 pm, "Sergio Correia" wrote: > > I'm using IDLE 1.2.1, Python 2.5.1, and Tk 8.4. Does anyone has any > idea of why is this happening? > Two mainloops == bad. IDLE == 1 mainloop. your program == 1 mainloop. From mail at timgolden.me.uk Mon Sep 10 12:25:38 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 10 Sep 2007 17:25:38 +0100 Subject: shared memory pointer In-Reply-To: <1189440232.421738.283100@k79g2000hse.googlegroups.com> References: <1189436265.841415.234050@w3g2000hsg.googlegroups.com> <1189440232.421738.283100@k79g2000hse.googlegroups.com> Message-ID: <46E57002.10806@timgolden.me.uk> Tim wrote: > I reviewed the mmap function and I have a question. In the example > code below, what is the connection between the data in shared memory > and the mmap function. The fileno is zero. Why is it zero? The size > makes sense because there is 256 bytes in shared memory. The tag is > MyFileMappingObject. This tag does not have anything in common with > the shared memory. How can mmap point to any data in shared memory? > There is no coorelation. > > > pBuf = windll.kernel32.MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, > 0, 0, SHMEMSIZE) > if (pBuf == 0): > print "Could not map view of file" > raise WinError() > else: > memcpy = cdll.msvcrt.memcpy > memcpy(pBuf, szMsg, len(szMsg)) > > shmem = mmap.mmap(0, 256, "MyFileMappingObject", mmap.ACCESS_WRITE) > shmem.write("Message from Python process") Your question seems a little strange. You appear to be creating a memory mapping via ctypes and then expecting the Python mmap module to know about it. Of course it doesn't. What you do is to create two mmap mappings with the same tag name which -- under the covers -- point to the same shared memory. I just tried it ad-hoc in two interpreters and it works fine. I admit I am absolutely no expert on this area. My initial suggestion was simply because your question triggered a memory of what I'd seen elsewhere. Have a look at this thread from a few years ago to see if it clarifies: http://www.thescripts.com/forum/thread25421.html (although what it -- and your question -- clearly do clarify is a lack of clarity in the documentation!) TJG From see_website at mindprod.com.invalid Sun Sep 30 21:53:47 2007 From: see_website at mindprod.com.invalid (Roedy Green) Date: Mon, 01 Oct 2007 01:53:47 GMT Subject: which language allows you to change an argument's value? References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> Message-ID: On Sun, 30 Sep 2007 10:47:13 -0000, Summercool wrote, quoted or indirectly quoted someone who said : >and now n will be 3. I think C++ and PHP can let you do that, using >their reference (alias) mechanism. And C, Python, and Ruby probably >won't let you do that. What about Java and Perl? Seem to me you could in FORTRAN and Pascal, and maybe even Algol. It has been a while. I have come to appreciate Java's strong isolation convention. It makes it a lot easier to track down WHERE in the code a value could potentially change and keeps those places to a minimum. -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com From jstroud at mbi.ucla.edu Thu Sep 6 17:50:34 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 06 Sep 2007 14:50:34 -0700 Subject: why should I learn python In-Reply-To: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: See www.python.org. Trust us all when we say that its the best. windandwaves wrote: > Can someone tell me why I should learn python? I am a webdeveloper, > but I often see Python mentioned and I am curious to find out what I > am missing out on. > > Thank you > > Nicolaas > -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bj_666 at gmx.net Mon Sep 24 03:09:01 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Sep 2007 07:09:01 GMT Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> <1190454275.282176.90830@k79g2000hse.googlegroups.com> <46f6e9b0$0$32168$426a74cc@news.free.fr> <1190597548.214612.181140@22g2000hsm.googlegroups.com> Message-ID: <5lp64dF95s07U1@mid.uni-berlin.de> On Sun, 23 Sep 2007 18:32:28 -0700, Kay Schluehr wrote: > On 22 Sep., 02:14, Bruno Desthuilliers > wrote: >> Kay Schluehr a crit : >> (snip) >> >> > I checked out Io once and I disliked it. I expected Io's prototype OO >> > being just a more flexible variant of class based OO but Io couples a >> > prototype very closely to its offspring. When A produces B and A.f is >> > modified after production of B also B.f is modified. A controls the >> > state of B during the whole lifetime of B. I think parents shall not >> > do this, not in real life and also not in programming language >> > semantics. >> >> I may totally miss the point, but how is this different from: >> >> class A(object): >> def dothis(self): >> print "A.dothis(%s)" % self >> >> class B(A): >> pass >> >> b = B() >> >> b.dothis() >> >> def dothat(self): >> print "function dothat(%s)" % self >> >> A.dothis = dothat >> b.dothis() > > It's not a big deal because you do not use a class to propagate > mutable state unless you are using a class attribute intentionally ( i > guess you do not overuse it just to avoid object encapsulation and > make everything global ). When using a prototype as in Io you need to > protect the state of the child object yourself. Just like in Python! Here `things` are shared between all "children": class A(object): things = list() def add(self, thing): self.things.append(thing) This is what happens too when you use this Io snippet: A := Object clone do( things := list() add := method(thing, self things append(thing) ) ) If you don't want `things` to be shared you write an `init` method, in both Python and Io. Python: class B(object): def __init__(self): self.things = list() def add(self, thing): self.things.append(thing) And Io: B := Object clone do( init := method( self things := list() self ) add := method(thing, self things append(thing) ) ) The `init` is called by the default `clone` method automatically just like `__init__()` in Python. It is really much like the class/instance relationship in Python with just the line between class and instance blurred. > You can do this by overwriting the objects slots but then you end up > writing your own object constructors and the templates accordingly, also > named "classes" by some. Not having dedicated object constructors, > member variable initializations and the presumed class definition > boilerplate comes at the price of introducing them on your own. The mechanism is already there in Io, no need to invent, just use it. Ciao, Marc 'BlackJack' Rintsch From koutoo at hotmail.com Mon Sep 24 16:43:05 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Mon, 24 Sep 2007 13:43:05 -0700 Subject: Nested For and While Statements In-Reply-To: <1190664112.564911.13480@57g2000hsv.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190664112.564911.13480@57g2000hsv.googlegroups.com> Message-ID: <1190666585.281623.228920@22g2000hsm.googlegroups.com> On Sep 24, 3:01 pm, Paul McGuire wrote: > On Sep 24, 2:28 pm, kou... at hotmail.com wrote: > > > > > > > I start my code with some constants then a while statement. But I > > have some For statements towards the end within the While statement > > where I start getting some errors. I'm hoping I won't have to post my > > code, but it looks something like this: > > > Import os, string > > > while this: > > > All Code indented like it should > > > Last line in While. > > > For i in range(1) > > class = [] > > class2 = [] > > For i in range(2) > > Do this > > And this > > And that. > > > Next Line hits snag here? Where should this line > > be? > > Why are the for loops further indented than the body of the while? If > they are part of the while, "For i in range(1)" should line up with > "Last line in While." If they are not part of the while, but come > after, then "For i in range(1)" should line up with "while this:". > > Also, as James Stroud said, your for loop indexes are the same > variable. > > -- Paul- Hide quoted text - > > - Show quoted text - My actual code has different variables, but thanks for pointing that out. I'm so used to coding in VB, where indenting isn't a problem, so all this indenting is new to me how Python wants it dictated. I made the changes and still get an error at the same point after the second For statement? So: While : Code under while More under while. For (x) Part of x Last of x For(y) Part of y Still part of y last part of y. New line part of x #where does this belong? Last line under while not in For #Should go under While, right? If I want all my code to run under the while, then the While statement should be the only line of code not indented once I state it then, correct? From tdwdotnet at gmail.com Fri Sep 28 07:33:33 2007 From: tdwdotnet at gmail.com (Tim Williams) Date: Fri, 28 Sep 2007 12:33:33 +0100 Subject: recipient validation with smtplib In-Reply-To: <46FCE387.9070601@chamonix.reportlab.co.uk> References: <46FCE387.9070601@chamonix.reportlab.co.uk> Message-ID: <9afea2ac0709280433n361ce4fx2a26a05de2b1b1ae@mail.gmail.com> On 28/09/2007, Robin Becker wrote: > Is there a way to use smtplib to get recipient validation. I can use smtplib > quite happily to send emails using the locahost's sendmail, but sendmail is just > fire and forget, so some bad addresses eg idiot at www.dingo.zzz don't cause any > error in the sending application. I know some smtp setups do enforce recipient > validation, but it doesn't seem terribly easy to do this with sendmail. I > wondered if there were some way to do this in python? There is no way of validating *every* email address you send to using SMTP alone. Some servers accept every address and bounce later - as you have found out. So for the purpose of the SMTP client, or relaying server, the address is valid at sending time to those servers. Checking DNS for MX records is a possibility for removing some bad addresses, but it's not fool proof as the RFCs don't require MX records to exist for a domain to be able to receive email. If no MX records are present, one (and only one!) IP address returned from the domain's A record(s) should be tried. HTH :) From stephane.larouche at polymtl.ca Wed Sep 19 09:29:25 2007 From: stephane.larouche at polymtl.ca (=?utf-8?b?U3TDqXBoYW5l?= Larouche) Date: Wed, 19 Sep 2007 13:29:25 +0000 (UTC) Subject: lambda-funcs problem References: <1190201984.062329.182460@k79g2000hse.googlegroups.com> <06eb01c7fab5$0aa2bb50$0203a8c0@MOUSE> Message-ID: Ryan Ginstrom ginstrom.com> writes: > How about: > > >>> def make_adder(i): > def adder(x): > return x+i > return adder > > >>> funcs = [make_adder(i) for i in xrange(10)] > >>> print [func(10) for func in funcs] > [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] > >>> Or if you want a one liner: funcs = [(lambda i: lambda x: x+i)(i) for i in xrange(10)] St?phane From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Sep 20 07:54:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 20 Sep 2007 13:54:04 +0200 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <1190263363.496695.83300@57g2000hsv.googlegroups.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190263363.496695.83300@57g2000hsv.googlegroups.com> Message-ID: <46f25f49$0$31908$426a34cc@news.free.fr> TheFlyingDutchman a ?crit : (snip) > I am confused about the benefits/disadvantages of the "GIL removal". > Is it correct that the GIL is preventing CPython from having threads? > > Is it correct that the only issue with the GIL is the prevention of > being able to do multi-threading? http://docs.python.org/lib/module-thread.html http://docs.python.org/lib/module-threading.html From stargaming at gmail.com Sun Sep 30 01:21:50 2007 From: stargaming at gmail.com (Stargaming) Date: 30 Sep 2007 05:21:50 GMT Subject: New to python References: <1191126010.260942.89230@y42g2000hsy.googlegroups.com> Message-ID: <46ff326e$0$17745$9b622d9e@news.freenet.de> On Sat, 29 Sep 2007 21:20:10 -0700, Googy wrote: > I am new to python... > > The programming language i know well is C Can any one recommend me the > good ebook for beginners. I have loads of ebooks but i am not able to > decide which to start with which book. Also i am learning XML so later > on i can switch to books on Python and XML but initially which book to > read?? > > Please help... Generically, `A byte of Python`_ and `Dive into Python`_ are pretty common. ABOP has a few comments for C programmers as well, AFAIK. If you already got a few (e)books, you should perhaps just look through all of them and then, sequentially, read them. .. _A byte of Python: http://www.byteofpython.info/download/ .. _Dive into Python: http://www.diveintopython.org/ From paulgeeleher at gmail.com Sun Sep 30 11:39:35 2007 From: paulgeeleher at gmail.com (sophie_newbie) Date: Sun, 30 Sep 2007 08:39:35 -0700 Subject: Create a string array of all comments in a html file... Message-ID: <1191166775.660477.97840@o80g2000hse.googlegroups.com> Hi, I'm wondering how i'd go about extracting a string array of all comments in a HTML file, HTML comments obviously taking the format "". I'm fairly stumped on how to do this? Maybe using regular expressions? Thanks. From deets at nospam.web.de Tue Sep 11 11:00:47 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 11 Sep 2007 17:00:47 +0200 Subject: Car-ac-systems References: <1189511932.371621.112970@o80g2000hse.googlegroups.com> Message-ID: <5knosvF4ik9eU1@mid.uni-berlin.de> Steve Holden wrote: > John Timney (MVP) wrote: >> Thats all it is. It may have been a usefully intended resource once, but >> they have no controls whatsoever. Its time someone closed it down. >> > What is it about "please do not top-post" that you have difficulty > understanding? Or do "MVP"s feel that their time is so much more > valuable than anyone else's that they are free to ignore the norms? > > Furthermore, please don't do the spammer the favor of repeating the URL > in yet another post. This only leaves further trails through the search > engines for innocents to trip over. > > Are you new to the Internet, or just generally clueless? I took a look at his website - and so far, I have yet to encounter an MVP that is not clueless. And who is not rubbing the fact that he got a pin from MS into everybodies eyes. But maybe he just wants to create visibility for his own linklist... Diez From Caseyweb at gmail.com Thu Sep 27 13:21:38 2007 From: Caseyweb at gmail.com (Casey) Date: Thu, 27 Sep 2007 17:21:38 -0000 Subject: True of False In-Reply-To: References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> <1190912324.363127.26100@r29g2000hsg.googlegroups.com> Message-ID: <1190913698.660661.13000@19g2000hsx.googlegroups.com> On Sep 27, 1:12 pm, "Richard Thomas" wrote: > On 27/09/2007, Casey wrote: > > > > > On Sep 27, 12:48 pm, "Simon Brunning" > > wrote: > > > On 9/27/07, kou... at hotmail.com wrote: > > > > > I tried writing a true and false If statement and didn't get > > > > anything? I read some previous posts, but I must be missing > > > > something. I just tried something easy: > > > > > a = ["a", "b", "c", "d", "e", "f"] > > > > > if "c" in a == True: > > > > Print "Yes" > > > > > When I run this, it runs, but nothing prints. What am I doing wrong? > > > > Just use > > > > if "c" in a: > > > > and all will be well. The True object isn't the only truthy value in > > > Python - see . > > > I would recommend the OP try this: > > > run the (I)python shell and try the following: > > > >>> a = [x for x in "abcdefg"] > > >>> a > > ['a','b','c','d','e','f','g'] > > >>> "c" in a > > True > > >>> "c" in a == True > > False > > >>> ("c" in a) == True > > True > > > The reason your conditional failed is that it was interpreted as "c" > > in (a == True) which is False. > > the "==" operator binds at a higher precedence level than the "in" > > operator, just as multiplication > > binds higher than addition > > Actually it evaluates '("c" in a) and (a == True)'. You can check like so: > > import dis > a = list("abcdef") > dis.dis(lambda: "c" in a == True) > > And just follow the bytecode operations. > > -- Richard. > > > -- > >http://mail.python.org/mailman/listinfo/python-list Doh, I forgot about operator chaining here. I'm so used to just seeing a < b < c that I forget about arbitrary operator chaining and think like a C++ programmer! From kar1107 at gmail.com Tue Sep 11 19:10:42 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 11 Sep 2007 16:10:42 -0700 Subject: How to insert in a string @ a index In-Reply-To: <1189274564.462664.131240@22g2000hsm.googlegroups.com> References: <1189274564.462664.131240@22g2000hsm.googlegroups.com> Message-ID: <1189552242.225202.43380@i13g2000prf.googlegroups.com> On Sep 8, 11:02 am, lolu... at gmail.com wrote: > Hi; > > I'm trying to insert XYZ before a keyword in a string. The first and > the last occurence of hello in the string t1 (t1="hello world hello. > hello \nwhy world hello") are keywords. So after the insertion of XYZ > in this string, the result should be t1 = "XYZhello world hello. hello > \nwhy world XYZhello" > > The python doesn't supports t1[keyword_index]="XYZhello" (string > object assignment is not supported). How do I get to this problem? Any > sugguestions? Yet another solution using re >>> t1 = 'hello world hello. hello. \nwhy world hello' >>> import re >>> l1 = re.split('hello', t1) >>> l1[0] = 'XYZ' + l1[0] >>> l1[-2] += 'XYZ' >>> 'hello'.join(l1) 'XYZhello world hello. hello. \nwhy world XYZhello' >>> If there are less than two 'hello', you'll get exception and needs special handling. Karthik > > -a.m. From bignose+hates-spam at benfinney.id.au Sun Sep 23 07:57:45 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 23 Sep 2007 21:57:45 +1000 Subject: Factory function with keyword arguments References: <13fbl9ertj5es12@corp.supernews.com> <13fchhi2mnm5tc8@corp.supernews.com> Message-ID: <87zlzdppae.fsf@benfinney.id.au> Steven D'Aprano writes: > A valuable lesson... always measure before guessing whether code > will be slow or not. And after measuring, don't guess then either :-) -- \ "Science doesn?t work by vote and it doesn?t work by | `\ authority." ?Richard Dawkins, Big Mistake (The Guardian) | _o__) | Ben Finney From deets at nospam.web.de Sat Sep 15 10:49:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 15 Sep 2007 16:49:52 +0200 Subject: Can You Program? In-Reply-To: <1189865720.546424.155860@d55g2000hsg.googlegroups.com> References: <1189679878.271415.88700@w3g2000hsg.googlegroups.com> <1189865720.546424.155860@d55g2000hsg.googlegroups.com> Message-ID: <5l29p6F63jd1U1@mid.uni-berlin.de> > Hey, thanks for spamming our group. Perhaps you should try again after > you learn proper HTML coding. > Results from http://validator.w3.org/ : Failed validation, 26 Errors > > Really, really doubt that you are doing anything but trying to gather > e-mails. My 12 year old has made better sites. > > Oh, and does jobslide.com know that you are linking to images on their > site? I'll be mentioning that to them, just so you know. > > Please, put down the keyboard and step away from the computer...... > And thanks to you, the spammer got another post containing his website, increasing page-rank. Well done! Diez From gagsl-py2 at yahoo.com.ar Mon Sep 3 23:59:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Sep 2007 00:59:24 -0300 Subject: Can you use -getattr- to get a function in the current module? References: Message-ID: En Mon, 03 Sep 2007 20:13:43 -0300, Sergio Correia escribi?: > # Module spam.py > > import eggs > > print getattr(eggs, 'omelet')(100) > > That is, I just call the function omelet inside the module eggs and > evaulate it with the argument 100. > > But what if the function 'omelet' is in the module where I do the > getattr (that is, in spam.py). If I do any of this Use globals(): print globals()['omelet'](100) (Of course this only makes sense when using a variable instead of 'omelet'...) -- Gabriel Genellina From steve at holdenweb.com Fri Sep 21 10:29:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Sep 2007 10:29:21 -0400 Subject: __contains__() and overload of in : Bug or Feature ??? In-Reply-To: <1190383050.514560.232660@50g2000hsm.googlegroups.com> References: <1190383050.514560.232660@50g2000hsm.googlegroups.com> Message-ID: sebastien.lannez at gmail.com wrote: > Thanks for your quick response. > >>> I need to overload the operator in and let him >>> return an object ... It seems it is not a >>> behavior Python expect : >>> >>>>>> class A: >>> ... def __contains__(self,a): >>> ... return 'yop' >>> ... >>>>>> a=A() >>>>>> print 'toto' in a >>> True >>>>>> print a.__contains__('toto') >>> yop > >> Not sure what you're trying to achieve, > > Using Python as an algebraic parser for > symbolic mathematical equation and I need > that the 'in' operator returns an object based > on its two arguments. > >> but the semantics of the "in" operator >> make it return a boolean value. > > That is why I need to overload it. > >> The string "yop" evaluates to the boolean >> value True, as it is not empty. > > Does it means that when overloading an operator, python just > wrap the call to the method and keep control of the returned > values ??? Is there a way to bypass this wrapping ??? > Certain aspects of the interpreter's behavior have ot be hard-wired in order for it to accomplish anything. This is one of the hard-wried aspects, so unless you want to change the interpreter's implementation I'm afraid you can't change it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From BjornSteinarFjeldPettersen at gmail.com Thu Sep 20 02:45:45 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Thu, 20 Sep 2007 06:45:45 -0000 Subject: Sets in Python In-Reply-To: <13f3m15igkstq2e@corp.supernews.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <13f3m15igkstq2e@corp.supernews.com> Message-ID: <1190270745.905604.52480@w3g2000hsg.googlegroups.com> On Sep 20, 4:17 am, Steven D'Aprano wrote: [...] > Data structures don't have problems. Programmers do. That's QOTW material :-) > ... And language > designers with sense build languages that minimize the programmers > problems, not maximize them. > ... > > The choices for the language designer are: > > (1) Invent some sort of magical non-deterministic hash function which > always does the Right Thing. > > (2) Allow the hash of mutable objects to change, which means you can use > mutable objects as keys in dicts but if you change them, you can no > longer find them in the dict. They'll still be there, using up memory, > but you can't get to them. > > (3) Simply disallow mutable objects as keys. (4) Allow mutable objects as keys, but have undefined (implementation defined) behavior if keys are mutated. This would seem a natural extension of the "we're all adults" paradigm (if I name a variable _foo you should treat it as private). Unfortunately there is no visual cue in this case, and tracking down where you relied on undefined behavior is notoriously time-consuming (just ask your nearest C++ multiplatform programmer). > Alternative 3 is easy to deal with: simply don't use mutable objects as > keys. That's what Python does. Sure, the programmer sometimes needs to > work around the lack (convert the list into a tuple, or a string, or > pickle it, whatever...) which on rare occasions is hard to do, but at > least there are no mysterious, hard to track down bugs. Amen. -- bjorn From steve at holdenweb.com Thu Sep 27 08:16:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 08:16:59 -0400 Subject: comparing elements of a list with a string In-Reply-To: <1190889848.653434.178450@g4g2000hsf.googlegroups.com> References: <1190734785.439839.303030@50g2000hsm.googlegroups.com> <1190889848.653434.178450@g4g2000hsf.googlegroups.com> Message-ID: Shriphani wrote: > Hello, > Would that mean that if I wanted to append all the (date, time) tuples > to a list, I should do something like: > > for file in list_of_backup_files: > some_list.append(file) That would be one way to do it (assuming you started with some_list as an empty list). But a faster way would be to use a list comprehension and say some_list = [f for f in list_of_backup_files] > By the way I did this: > > def listAllbackups(filename): > list_of_backups = glob(home+'/Desktop/backupdir/*%s*'%filename) > for element in list_of_back: > if element.find(file) != -1: > date_components = element.split('-')[-4:-1] > date = str(date_components[0]) + ":" + str(date_components[1]) + > ":" + str(date_components[2]) > time = element.split('-')[-1] > yield (date, time) > print listAllbackups('fstab') > > > I ran it in the terminal and I got: > > > > Why does it do that and not just print out all the values of (date, > time) Because the generator object returned by the function has to be used in an iterative context to produce its values. Which is why the list comprehension produces a list! If you don't really want a generator then you could just rewrite the function to return a list in the first place. You did specifically ask "how do I use the yield statement ...". If you are going to iterate o ver the list then a generator is typically more memory-efficient (because it only produces one element at a time), and can do things that a list can't (like deal with a potentially infinite sequence of results). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From thijs.braem at gmail.com Sun Sep 16 13:11:33 2007 From: thijs.braem at gmail.com (thijs.braem at gmail.com) Date: Sun, 16 Sep 2007 17:11:33 -0000 Subject: Python Unicode to String conversion In-Reply-To: <1188631034.968347.116170@d55g2000hsg.googlegroups.com> References: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> <1188631034.968347.116170@d55g2000hsg.googlegroups.com> Message-ID: <1189962693.168033.258520@d55g2000hsg.googlegroups.com> Sorry for answering so late. Thanks a million! This code snippet helped me solve the problem. I think I will be using SQLAlchemy for these sorts of things from now on though, it seems to be taking care of these things itself, on top of being one hell of a handy ORM of course :) thijs On 1 sep, 09:17, iapain wrote: > First make sure your DB encoding is UTF-8 not the latin1 > > > The error I keep having is something like this: > > ERREUR: S?quence d'octets invalide pour le codage ?UTF8? : 0xe02063 > > then try this: > > def smart_str(s, encoding='utf-8', errors='strict'): > """ > Returns a bytestring version of 's', encoded as specified in > 'encoding'. > """ > if not isinstance(s, basestring): > try: > return str(s) > except UnicodeEncodeError: > return unicode(s).encode(encoding, errors) > elif isinstance(s, unicode): > return s.encode(encoding, errors) > elif s and encoding != 'utf-8': > return s.decode('utf-8', errors).encode(encoding, errors) > else: > return s From steve at holdenweb.com Wed Sep 5 09:42:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 05 Sep 2007 06:42:58 -0700 Subject: handling modules in packages In-Reply-To: <619B716A-C1EB-42DF-9702-E288AD04F613@mac.com> References: <619B716A-C1EB-42DF-9702-E288AD04F613@mac.com> Message-ID: Tommy Grav wrote: > Hi, > > I am working on a package that contains a number of > different modules: > > > ls pyAstro > __init__.py > constants.py > conversion.py > observation.py > orbit.py > transformation.py > > however, I find that several of the modules have the > same import statements: > > orbit.py: > > import numpy > import constants > import conversion > import observations > > observations.py: > > import numpy > import constants > import conversions > import transformations > > The modules themselves are not overly large, but it bugs > me to have to import numpy twice (or even more as the > number of modules grow). Is there a way to import numpy > once in the package (like in the __init__.py file) such that > it is accessible to all the modules? Or is the multiple imports > just something one has to live with? > > Thanks for any help or direction to webpages discussing this > topic. > > Cheers > Tommy > The simplest thing to do would be to have PyAstro.__init__.py import all the sub-modules, and define __all__ as the set of names that the package should inject into importing modules. Then you could write (for example) from PyAstro import numpy, constants, conversion, obsrvations However if you are simply worried about run-time efficiency then don't be: once a module is imported further imports essentially reduce to checking that the module is already present in the sys.modules dict, and so take almost no time at all. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From raychorn at hotmail.com Thu Sep 20 17:59:48 2007 From: raychorn at hotmail.com (Python Maniac) Date: Thu, 20 Sep 2007 14:59:48 -0700 Subject: I could use some help making this Python code run faster using only Python code. Message-ID: <1190325588.608625.259800@q3g2000prf.googlegroups.com> I am new to Python however I would like some feedback from those who know more about Python than I do at this time. def scrambleLine(line): s = '' for c in line: s += chr(ord(c) | 0x80) return s def descrambleLine(line): s = '' for c in line: s += chr(ord(c) & 0x7f) return s def scrambleFile(fname,action=1): if (path.exists(fname)): try: f = open(fname, "r") toks = fname.split('.') while (len(toks) > 2): toks.pop() fname = '.'.join(toks) if (action == 1): _fname = fname + '.scrambled' elif (action == 0): _fname = fname + '.descrambled' if (path.exists(_fname)): os.remove(_fname) ff = open(_fname, "w+") if (action == 1): for l in f: ff.write(scrambleLine(l)) elif (action == 0): for l in f: ff.write(descrambleLine(l)) except Exception, details: print 'ERROR :: (%s)' % details finally: f.close() ff.close() else: print 'WARNING :: Missing file "%s" - cannot continue.' % fname From sajmikins at gmail.com Wed Sep 26 17:02:49 2007 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 26 Sep 2007 17:02:49 -0400 Subject: Matplotlib TkAgg WindowsXP ImportError In-Reply-To: <1190827160.282738.293770@k79g2000hse.googlegroups.com> References: <1190827160.282738.293770@k79g2000hse.googlegroups.com> Message-ID: <50f98a4c0709261402j34c4ecbev327429c2b65c304f@mail.gmail.com> On 9/26/07, Simon Forman wrote: > Hello, > > I just installed Matplotlib (and NumPy) on a windows XP machine, and > I'm getting the following traceback when I try to use the TkAgg > backend. > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import matplotlib > >>> matplotlib.use('TkAgg') > >>> from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\Lib\site-packages\matplotlib\backends > \backend_tkagg.py", > line 8, in > import tkagg # Paint image to Tk photo blitter > extension > File "C:\Python25\lib\site-packages\matplotlib\backends\tkagg.py", > line 1, in > import _tkagg > ImportError: DLL load failed: The specified module could not be found. > >>> > > I found one old (2004) post > http://mail.python.org/pipermail/python-list/2004-April/258963.html > that seems to indicate that some sort version mismatch of the Tk/Tcl > libraries may be to blame. But I don't know how to diagnose that or > what to do about it. > > FWIW, I installed using matplotlib-0.90.1.win32-py2.5.exe and > numpy-1.0.3.1.win32-py2.5.exe. > > Thanks in advance for any help. > Sincerely, > ~Simon > > -- > http://mail.python.org/mailman/listinfo/python-list > Please disregard. I was missing MSVCP71.dll. Sorry for the 'noise', Sincerely, ~Simon From gagsl-py2 at yahoo.com.ar Fri Sep 7 21:25:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Sep 2007 22:25:39 -0300 Subject: Best way to do attribute docstrings? References: <1189195567.238990.54440@57g2000hsv.googlegroups.com> Message-ID: En Fri, 07 Sep 2007 17:06:07 -0300, Ken Kuhlman escribi?: > What's the best method for annotating attributes with a docstring? > I'm looking to be able to introspect my class & get the comments back > out. I don't know which is the *best* method. Perhaps you might use properties instead. Or some kind of convention, like four_legs__doc__ = "Animal has four legs" to be the docstring associate to `four_legs` attribute. > The technique I'm using is a little hoaky, but works.. basically I > create subclasses of the builtin types that I want to be able to use & > then instantiate them in my attribute assignments. This gives me an > object that I can tweak the __doc__ attribute on. An example of what > my code looks like is included below. I don't like subclassing builtins, it doesn't work in general. _("Hello") + _(" world!") is a plain str object, not your derived class. What about instance attributes? All your examples show class attributes. Your docstring appears to be attached to the attribute "value", but it should be attached to the attribute definition, or be a class attribute, or something like that, shared between all instances and somewhat permanent. Else, reassigning the attribute will lose the docstring. > # Boolean gave me extra fits that I don't understand, but this > technique works > class MyBool(int): > def __str__(self): > return `self.__int__() > 0` > def __repr__(self): > return self.__str__() Let Python do the boolean conversion: -1 is a true value, but MyBool(-1) would say False. I don't understand exactly why do you want this class, but I'd write it this way: class MyBool(int): def __str__(self): return str(bool(self)) __repr__ = __str__ > def bool_func(val): > def blah(): > return MyBool(val) > return blah > true = bool_func(True) > false = bool_func(False) And why do you need such functions? -- Gabriel Genellina From nutsbreaker3 at gmail.com Wed Sep 12 16:17:30 2007 From: nutsbreaker3 at gmail.com (nutsbreaker3 at gmail.com) Date: Wed, 12 Sep 2007 20:17:30 -0000 Subject: Free guitars Message-ID: <1189628250.389879.213120@50g2000hsm.googlegroups.com> Win a free guitar today!!!! http://freeguitars.blogspot.com/ From tec at knology.net Tue Sep 11 10:21:23 2007 From: tec at knology.net (Tim) Date: Tue, 11 Sep 2007 07:21:23 -0700 Subject: shared memory pointer In-Reply-To: References: <1189436265.841415.234050@w3g2000hsg.googlegroups.com> <1189437684.476993.130390@g4g2000hsf.googlegroups.com> Message-ID: <1189520483.489744.106960@19g2000hsx.googlegroups.com> Wow....You put some detail in this response. Thanks so much! I think I want to stay away from mmap because it uses the disk to store my memory. I am trying to stay away from that. I am building strip charts in this python project to view my data. Currently, I am using a file and I have to open the file when my simulation is complete. The simulation takes too long to execute when it has to dump all of the data to a file. The simulation is written in C++ but I want the strip charts to be written in python so I can using the free plots in matplotlib. I am trying to place the very large data block in shared memory so I don't have to wait for the data to be written to a disk. I have about 200 shared memory segments that the simulation creates. I did not know that my code would write to the hard drive because I use ctypes. Could you explain that. Even if I use mmap, how could I mmap 200 shared memory segments? The first argument to mmap is a zero. How does mmap know to map the returned object from MapViewOfFile to the tag? I have been looking into using a dll to do all of the mappings. Then, I can call the dll from my python script to access my array of floats. What do you think of this approach? I am having trouble finding good documentation of this approach. Can you help? Thanks On Sep 11, 7:58 am, Tim Golden wrote: > Tim wrote: > > I saw the mmap function in the shared memory example. I had some > > concern with my large memory size being written to the disk drive. I > > though it might slow down my application. The reason I am writting > > this new code is because the existing method using a file. I thought > > shared memory would be much faster. > > > I have tried using the memcpy and addresses, casting, etc. Is there a > > way to use memcpy with the pData returned by MapViewOfFile()? > > Tim, let's try to back up on this a moment. As I understand, you're > running under Windows and you want to use shared memory, presumably > between two processes. You know about the CreateFileMapping/MapViewOfFile > API, possibly from this example on MSDN [1] and you want to use that > technique in Windows *without* an explicit file backing. > > Am I right so far? > > I suggested the mmap module, and you seemed to pick up on it > and be trying to use both your ctypes solution *and* the mmap > module as two halves of the same mechanism. Maybe I misunderstood, > but that's what it looked like. > > Then you asked a question about getting hold of a Python object's > memory address to be able to pass it into your ctypes solution. > (Which makes sense, given the nature of that solution). > > What you seem to have missed is that your ctypes code is doing > *exactly* what the mmapmodule.c code (which is the implementation > of the mmap module) is doing for you behind the scenes. > > Here's your code (very slightly reformatted): > > > szName = c_char_p(name) > hMapObject = windll.kernel32.CreateFileMappingA( > INVALID_HANDLE_VALUE, > None, > PAGE_READONLY, > 0, > TABLE_SHMEMSIZE, > szName > ) > if (hMapObject == 0): > print "OpenKey: Could not open name file mapping object" > raise WinError() > > self.pData = windll.kernel32.MapViewOfFile( > hMapObject, > FILE_MAP_ALL_ACCESS, > 0, > 0, > TABLE_SHMEMSIZE > ) > > > > and here's the code from mmapmodule.c (also reformatted > and snipped about): > > > m_obj->map_handle = CreateFileMapping( > m_obj->file_handle, > NULL, > flProtect, > size_hi, > size_lo, > m_obj->tagname > ); > if (m_obj->map_handle != NULL) { > m_obj->data = (char *) MapViewOfFile( > m_obj->map_handle, > dwDesiredAccess, > 0, > 0, > 0 > ); > > > > I hope you can see that they're basically doing the same > thing. (given the appropriate parameters). The only > clear difference is that the final param to MapViewOfFile > is 0 in the Python code, which the MSDN docs[2] indicate > "If this parameter is 0 (zero), the mapping extends > from the specified offset to the end of the file mapping." > It's not clear from that how it applies to a non-file-backed > FileMapping, but I *assume* that the Python devs have tested > that out. > > In short, to have two Python processes talk via shared > memory (not linking to a specific file) the following > works for me: > > > import mmap > > # > # The 0 special file value can be -1 in Python 2.5 > # > shmem = mmap.mmap (0, 1000, "TJG", mmap.ACCESS_WRITE) > shmem.write ("blah blah") > > > > import mmap > > shmem = mmap.mmap (0, 1000, "TJG", mmap.ACCESS_WRITE) > print shmem.read (9) > > > Obviously, I've used dummy codes and values, but since > the .write and .read (and the other helper methods) > use strings, you can always pickle or marshal arbitrary > Python data to move it around. > > I hope all that's helpful; if nothing else, it's given > me some exercise in reading the code of the stdlib, which > can't be bad! > > TJG > > [1]http://msdn2.microsoft.com/en-us/library/aa366551.aspx > [2]http://msdn2.microsoft.com/en-us/library/aa366761.aspx From steve at REMOVE-THIS-cybersource.com.au Fri Sep 7 20:32:35 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Sep 2007 00:32:35 -0000 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <46e15959$0$16104$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <13e3rd38ijilebd@corp.supernews.com> On Fri, 07 Sep 2007 15:59:53 +0200, Wildemar Wildenburger wrote: > I just thought I'd go along with the analogy the OP created as that was > his mindset and it would make things easier to follow if I didn't try to > forcibly change that. My reaction to somebody trying to reason with the wrong analogy is to teach them the right analogy, not to tell them they got it right when they actually got it wrong. "My car won't start -- I must not have stirred the gasoline enough before baking it." "Yes, that's right. It's very important to stir the gasoline fully so that all the ingredients are fully mixed." -- Steven. From hrishys at yahoo.co.uk Wed Sep 26 04:34:43 2007 From: hrishys at yahoo.co.uk (hrishy) Date: Wed, 26 Sep 2007 09:34:43 +0100 (BST) Subject: Hello Gabriel cant help noticing you In-Reply-To: Message-ID: <338550.18683.qm@web27805.mail.ukl.yahoo.com> Hi Gabriel Well it could be a bad example when we need to do lot more things via xml but..the regex in that i have preserved it carefully thats key takeawy for a beginner like me the way the problem was dissected to arrive at what was needed regards Hrishy --- Gabriel Genellina wrote: > En Wed, 26 Sep 2007 03:35:25 -0300, hrishy > escribi???: > > > I couldnt help but to write this mail. > > > > I am not a python programmer just a shell script > coder > > and i am planning to learn some decent python and > > raise my level from a shell script junkie to a > Python > > gentleman the way you explain things and show it > in > > code is simply amazing. > > Thanks! I feel somewhat embarrassed now :"> > Glad to see you find my posts useful. > > > I particularly liked the way you explained that > > Regular expression stuff to parse that XML i am > just > > awestruck. > > Thanks again! But parsing XML is not a good example > of RE usage, so I > don't like it so much. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list ___________________________________________________________ Want ideas for reducing your carbon footprint? Visit Yahoo! For Good http://uk.promotions.yahoo.com/forgood/environment.html From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Sep 21 05:05:45 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 21 Sep 2007 11:05:45 +0200 Subject: executing list of methods (and collecting results) References: <5lgi6qF81sotU1@mid.individual.net> Message-ID: <5lhfr9F87lq0U1@mid.individual.net> gherzig at fmed.uba.ar wrote: > Haha, no, the actual methods do other kind of things. > Thanks Bj?rn!!! Okay, so I hoped. Glad to be of help. Regards, Bj?rn -- BOFH excuse #233: TCP/IP UDP alarm threshold is set too low. From bdesth.quelquechose at free.quelquepart.fr Sun Sep 9 11:15:50 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 09 Sep 2007 17:15:50 +0200 Subject: Difference between two times (working ugly code, needs polish) In-Reply-To: References: Message-ID: <46e703d9$0$3290$426a74cc@news.free.fr> Shawn Milochik a ?crit : > I have done what I wanted, but I think there must be a much better way. > > Given two timestamps in the following format, I just want to figure > out how far apart they are (in days, seconds, whatever). > > Format: > > YYYY-MM-DD_MM:SS > > Example: > 2007-09-11_16:41 > > > It seems to me that to do what I want, I need to convert a string into > a number (time.mktime()), such as this: 1189543487.0 > > Once I have that, I can just subtract one from the other and do > whatever I want. The ugly part is converting something like > 2007-09-11_16:41 to the numeric equivalent. > > Below is my code. Any suggestions? import time print time.mktime(time.strptime("2007-09-11_16:41", '%Y-%m-%d_%H:%M')) => 1189521660.0 FWIW, you may also want to have a look at the datetime module, with special attention to the timedelta class. HTH From aleax at mac.com Sun Sep 9 11:49:42 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 9 Sep 2007 08:49:42 -0700 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <13e2jdobu2kqkf1@corp.supernews.com> <13e4rno5qal6h4b@corp.supernews.com> <1189330200.935267.107970@19g2000hsx.googlegroups.com> <13e7rhtqelbcb54@corp.supernews.com> <1189346979.198156.115170@g4g2000hsf.googlegroups.com> Message-ID: <1i4602f.1n7xwdh14c2r18N%aleax@mac.com> Arnaud Delobelle wrote: ... > > >>> def lower_list(L): > > > > ... for i, x in enumerate(L): > > ... L[i] = x.lower() > > ...>>> s = ['STRING'] > > >>> lower_list(s) > > >>> print s == ['string'] > > True > > > > >>> def lower_string(s): > > > > ... s = s.lower() > > ...>>> s = "STRING" > > >>> lower_string(s) > > Let's see what happens here: when lower_string(s) is called, the 's' > which is local to lower_string is made to point to the same object as > the global s (i.e. the string object with value "STRING"). In the > body of the function, the statement s=s.lower() makes the local 's' > point to a new string object returned s.lower(). Of course this has > not effect on what object the global 's' points to. Yep, the analogy with C pointers would work fine here: void lower_string(char* s) { s = } would fail to have the intended effect in C just as its equivalent does in Python (in both Python and C, rebinding the local name s has no effect on the caller of lower_string). Add an indirection: void lower_list(item* L) { ... L[i] = } this indirection (via indexing) *does* modify the memory area (visible by the caller) to which L points. The difference between "name=something" and "name[i]=something" is so *HUGE* in C (and in Python) that anybody who doesn't grok that difference just doesn't know or understand any C (nor any Python). > What I think is a more dangerous misconception is to think that the > assignement operator (=) has the same meaning in C and python. I've seen the prevalence of that particular misconception drop dramatically over the years, as a growing fraction of the people who come to Python after some previous programming experience become more and more likely to have been exposed to *Java*, where assignment semantics are very close to Python (despite Java's unfortunate complication with "unboxed" elementary scalar types, in practice a vast majority of occurrences of "a=b" in Java have just the same semantics as they do in Python); teaching Python semantics to people with Java exposure is trivially easy (moving from "ALMOST every variable is an implicit reference -- excepting int and float ones" to "EVERY variable is an implicit reference"...). Alex From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Sep 10 07:46:39 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 10 Sep 2007 13:46:39 +0200 Subject: Python syntax wart References: <5khuq4F3ij9eU1@mid.individual.net> Message-ID: <5kkp4vF46jjuU3@mid.individual.net> Lawrence D'Oliveiro wrote: > In message <5khuq4F3ij9eU1 at mid.individual.net>, Bjoern >> What's wrong with this: >> >> for Link in GetEachRecord( > > Then you're no longer showing the syntax structure in two > dimensions. Why should I want to? :) BTW, this is the first time I read about "two dimensional syntax". What's the benefit? Regards, Bj?rn -- BOFH excuse #292: We ran out of dial tone and we're and waiting for the phone company to deliver another bottle. From wink at saville.com Wed Sep 26 07:47:32 2007 From: wink at saville.com (wink) Date: Wed, 26 Sep 2007 11:47:32 -0000 Subject: Asynchronous Messaging Message-ID: <1190807252.731074.141450@k79g2000hse.googlegroups.com> Hello, I'm getting my feet wet in Python and thought I'd try to see how well Python works for asynchronous messaging. I've been using asynchronous messaging for 5 years and find it advantageous for many things. In the scheme I use communication is not only asynchronous but it is also non- blocking and inherently serialized via a queue. This provides two benefits, a sender is never directly effected by the receiver and since the receiver handles only one message at a time it generally never has to use mutexes or semaphores. This allows for the programmer to use multiple threads without having to contend with the associated issues mutexes have in the area of deadly embraces or race conditions. Anyway, below is a link to the first pass at an implementation in Python, comments are welcome: http://www.saville.com/python/mproc.tgz Regards, Wink Saville From fabiofz at gmail.com Mon Sep 10 07:32:48 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 10 Sep 2007 08:32:48 -0300 Subject: Pydev 1.3.9 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.9 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: ----------------------------------------------------------------- * Code-analysis: detects bad indentation (wrong number of indent chars). * Code-analysis: Class may be marked with '@DynamicAttrs' so that the code-analysis doesn't give undefined variable errors. See http://www.fabioz.com/pydev/manual_adv_code_analysis.html#Passing_info_to_code_analysisfor more details. * Mark-Occurrences: Fix: a class that had a call would not be recognized sometimes. * Rename Refactoring: Fix: when different heuristics yielded the same result the text could become garbled. Release Highlights in Pydev: ---------------------------------------------- * Fixed problem when configuring jython * Patch from paulj: debbugger working with jython 2.2rc2 * Patch from Oskar Heck: debbugger can change globals * Added action to delete all .pyc / $py.class files * Added actions to add/remove the pydev configuration from a project (previously, the only way to add a nature was to open a python file within a project). * Ctrl+Shift+O: When used with a selection will consider lines ending with \ (without selection organizes imports) * Auto-add "import" string will not be added when adding a space in the case: from xxximport (just after from xxx) * Templates created with tabs (or spaces indent) are now converted to the indent being used in the editor * Hide non-pydev projects filter working * Don't show assignments/imports after if __name__ == '__main__': in outline * Code-completion: after a completion is requested, pressing '.' will apply that completion (and if it has parameters, they'll not be added). * Code-completion: when a code-completion is applied with Ctrl pressed (toggle mode), parameters are not added. * Assign to local variable/attribute handles constants correctly. * psyco changed for Null object for debug (so, no changes are required to the code if psyco is used while debugging). * Code-folding annotations won't change places. * Pydev package explorer will correctly show outline for files if the project root is set as a source folder. * Pydev package explorer: folders under the pythonpath have a package icon. * Unittest runner: handles multiple selection. What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython 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 ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Wed Sep 12 12:58:16 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 12 Sep 2007 16:58:16 GMT Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> <1189609935.347945.139000@19g2000hsx.googlegroups.com> Message-ID: On 2007-09-12, Michele Simionato wrote: >> I see the argument for making self explicit -- what would be >> wrong with just .a instead of self.a though? That's still >> explicit but much easier to read. (I think I've seen that >> somewhere else, is it C#?) > > This has been proposed many times. But self is handy because > you can give a different name to it: for instance it becomes > cls when you are inside a classmethod. The treatment of self in the function's parameter list seems to be the pitfall of any .member shortcut proposal. Most proposals don't even address that point. Does it become: class Foo: def __init__(): .bar = 40 or class Foo: def __init__(.): .bar = 40 or class Foo: def __init__(self): .bar = 40 I guess the middle one is the most consistent, but it seems ugly compared to what we have now. -- Neil Cerutti From thomas at jollans.com Fri Sep 21 16:09:28 2007 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 21 Sep 2007 22:09:28 +0200 Subject: RE Help In-Reply-To: <1190399985.324448.242610@d55g2000hsg.googlegroups.com> References: <1190399985.324448.242610@d55g2000hsg.googlegroups.com> Message-ID: <200709212209.29148.thomas@jollans.com> On Friday 21 September 2007, byte8bits at gmail.com wrote: > Not specific to Python, but it will be implemented in it... how do I > compile a RE to catch everything between two know values? Here's what > I've tried (but failed) to accomplish... the knowns here are START and > END: > > data = "asdfasgSTARTpruyerfghdfjENDhfawrgbqfgsfgsdfg" > x = re.compile('START.END', re.DOTALL) > > x.findall(data) I'm not sure finding a variable number of occurences can be done with re. How about # data = the string strings = [] for s in data.split('START')[1:]: strings.append(s.split('END')[0]) From p at ulmcnett.com Tue Sep 4 18:57:45 2007 From: p at ulmcnett.com (Paul McNett) Date: Tue, 04 Sep 2007 15:57:45 -0700 Subject: Dealing with PayPal's messy SPF records Message-ID: <46DDE2E9.70901@ulmcnett.com> I administer email for a few clients of mine, using Postfix. One of the policies that is in place is SPF-checking, and rejecting messages accordingly. This has been working well for months. However, today a user called me to complain that they weren't able to get confirmed with PayPal to set up a new account. Turns out, SPF was rejecting the email from PayPal because of "Too many DNS lookups". This was somewhat surprising as I had been expecting the problem to be with my greylisting setup. I took a look at PayPal's SPF structure and it is indeed a big mess - lots of includes, and those includes have lots of hosts and mx records, etc. I helped the user by temporarily disabling all SPF checking and then reenabling it after the user got confirmed, but I was wondering if there is an elegant way to tell postfix to "ignore the going over MAX_LOOKUPS" for ("paypal.com",). I guess this would involve modifying policyd-spf.py? I took a look at the source spf.py, and see where these values are hardcoded, complete with references to the RFC, and I don't want to modify those hardcoded values. I also don't want to disable SPF as the final layer of policy checking on my mail server. But, I have to recognize that companies like PayPal are big players, and I'm probably not going to get them to budge by complaining, so I should try to accommodate their messy setups as much as possible, as my users are nearly always right. Anyone been down this road before and can offer tips/advice? I did google for relevant strings, but didn't come up with anything that appeared to address this specific problem. -- pkm ~ http://paulmcnett.com From bignose+hates-spam at benfinney.id.au Tue Sep 18 19:22:20 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Sep 2007 09:22:20 +1000 Subject: Using pseudonyms References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46ef893c$0$21882$426a34cc@news.free.fr> <46effd63$0$16044$426a74cc@news.free.fr> Message-ID: <87odfzy2xf.fsf@benfinney.id.au> Bruno Desthuilliers writes: > For the record, I usually don't give a damn about what > name/nickname/whatever peoples use. With the caveat "... so long as they consistently use one name in a given context", I concur. -- \ "I saw a sign: 'Rest Area 25 Miles'. That's pretty big. Some | `\ people must be really tired." -- Steven Wright | _o__) | Ben Finney From kar1107 at gmail.com Mon Sep 24 18:34:44 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Mon, 24 Sep 2007 22:34:44 -0000 Subject: shutil.copy2 error In-Reply-To: <1190644477.380312.261840@d55g2000hsg.googlegroups.com> References: <1190644477.380312.261840@d55g2000hsg.googlegroups.com> Message-ID: <1190673284.509807.110830@57g2000hsv.googlegroups.com> On Sep 24, 7:34 am, Horse wrote: > I've written a python script that copies a nightly Oracle backup file > to another server. Every couple days, the script fails with this > error message: > > Error copying Q:/Oradata/GISPROD/Backups/3UISN35R_1_1 to s:/gisprod/ > backups/3UISN35R_1_1 > [Errno 22] Invalid argument > > Here's the code for the function I'm running. The path names are all > correct, and it works *most of the time*. It only fails about once or > twice a week. Anyone know where I can get more info on this "errno 22 > invalid argument"? > > def CopyNewFiles(SOURCE_DIR, DEST_DIR): > global STATUS > try: > os.chdir(SOURCE_DIR) > for x in os.listdir(SOURCE_DIR): > int_time = os.stat(x)[stat.ST_CTIME] > str_time = time.ctime(int_time) > if datetime.date.fromtimestamp(int_time + 0.00) > > YESTERDAY: > try: > DEST_FILE = os.path.join(DEST_DIR, x) > logfile.write(" Copying " + SOURCE_DIR + x + " > to " + DEST_FILE + "\n") > logfile.flush() > if not os.path.isfile(DEST_FILE): > shutil.copy2(x, DEST_FILE) I'm not sure of the error; but one possibility is that the source- directory contents may be modified by some other process, while you are looping here copying one-by-one the files. So a file 'x' could be present at the time you enter loop, but gone by the time you try the shutil.copy2. Again this is just a guess... Yet another possibility is 'x' is not a regular file (say in unix it could be a named pipe).. you can try adding a check for x (like os.path.isfile(x)) and copy only regular files. Karthik > else: > logfile.write(" File exists. Skipping. > \n") > logfile.flush() > except (IOError, os.error), why: > logfile.write("\n\nError copying " + SOURCE_DIR + > x + " to " + DEST_FILE + "\n\n") > logfile.write("\n" + str(why) + "\n") > logfile.flush() > STATUS = "FAILED" > except: > logfile.write("\n\nUnhandled error in CopyNewFiles\n\n") > logfile.write("SOURCE_DIR = " + SOURCE_DIR + "\n") > logfile.write("DEST_DIR = " + DEST_DIR + "\n") > logfile.flush() > STATUS = "FAILED" From bignose+hates-spam at benfinney.id.au Fri Sep 28 02:58:23 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 28 Sep 2007 16:58:23 +1000 Subject: Numeric command-line options vs. negative-number arguments References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <0a6dnQmBPIzuqmHbnZ2dnUVZ_vihnZ2d@comcast.com> <87ejgj4lpy.fsf_-_@benfinney.id.au> Message-ID: <87wsub2s4w.fsf@benfinney.id.au> Steven Bethard writes: > Did you try it and find it didn't work as you expected? No, I was commenting on the behaviour you described (hence why I said "That would be irritating"). > Argparse knows what your option flags look like, so if you specify > one, it knows it's an option. Argparse will only interpret it as a > negative number if you specify a negative number that doesn't match > a known option. That's also irritating, and violates the expected behaviour. It leads to *some* undefined options being flagged as errors, and others interpreted as arguments. The user shouldn't need to know the complete set of options to know which leading-hyphen arguments will be treated as options and which ones won't. The correct behaviour would be to *always* interpret an argument that has a leading hyphen as an option (unless it follows an explicit '--' option), and complain if the option is unknown. -- \ "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 zzbbaadd at aol.com Fri Sep 28 15:29:14 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 12:29:14 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <5m51l4Fbao07U2@mid.uni-berlin.de> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> Message-ID: <1191007754.740566.137510@n39g2000hsh.googlegroups.com> > > Or bind resources of these pocket protectors that otherwise would lead to > answers for people that do seek enlightment... I don't think it would be correct to characterize my posts as not seeking enlightenment. I do also happen to voice my opinion which seems appropriate since this can be characterized as a discussion group. It theoretically is possible for a discussion group to tolerate opinions that diverge from the majority. One issue I have with this group and that I encountered many years ago in the Perl group is that there is no separate group comp.lang.python.beginner where you can ask questions without getting hit with RTFM! and the like. From deets at nospam.web.de Fri Sep 28 05:49:58 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Sep 2007 11:49:58 +0200 Subject: Python 3.0 migration plans? References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> Message-ID: <5m4126FbgjabU1@mid.uni-berlin.de> TheFlyingDutchman wrote: > >> >> The fact that you compare and criticise the simple annotations like >> static or abstract with the much more powerful decorator concept shows >> that, despite being the maintainer of a >> soon-to-be-ruling-the-python-world Python 3 fork, lack understanding of >> even the most basic language features. Which isn't exactly news.[1] > > Don't you mean "lack appreciation for the non-basic language > features"? static, class and abstract > are basic language features that I appreciate. "decorators" have been > in Python for only a small part of its existence, they aren't in the > vast majority of languages (if any other language even has them) which > means people write all kinds of software without them. Or rather, most > of the software ever written didn't use decorators. Doesn't sound > basic at all. People did write all kinds of software in Assembler. And large portions of these people complained about every feature that some new language introduced. All serious languages are turing-complete. So can we put away with this non-sense argument right away, please? >> >> Maybe you should start using python more and _then_ start discussions >> about it's features, when you have good grounds and can provide viable >> alternatives? But I guess that's a wish that won't be granted.... > > static and abstract keywords would seem to be very viable > alternatives. Viable enough that several language designers used them. As I said - you don't get it. The decorators (in conjunction with the descriptor protocol - ever heard of that?) are very powerful yet lead as an artifact to simple, declarative implementations of features you like, namely static and abstract methods. And as you seem being so reluctant to let new features creep into the language, the introduction of new keywords you like? Besides, those 'several language designers' seem to think that the introduction of keywords isn't enough, but a general purpose annotation scheme seems to be viable - or how do you explain e.g. JDK 1.5 Annotations? Diez From steve at holdenweb.com Mon Sep 17 14:20:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Sep 2007 14:20:10 -0400 Subject: Try this In-Reply-To: <1190051875.433350.150820@50g2000hsm.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> <1190008502.986300.286280@22g2000hsm.googlegroups.com> <1190051875.433350.150820@50g2000hsm.googlegroups.com> Message-ID: <46EEC55A.9070602@holdenweb.com> mensanator at aol.com wrote: > On Sep 17, 6:09 am, Steve Holden wrote: >> mensana... at aol.com wrote: >>> On Sep 16, 9:27?pm, "Gabriel Genellina" >>> wrote: >>>> En Sun, 16 Sep 2007 21:58:09 -0300, mensana... at aol.com >> [...] >>>> What about the rest of the world that don't speak >>>> English or even worse, don't use the Latin alpabet? >>> When the rest of the world creates the next >>> generation of computers, THEY can chosse the >>> defaults. >> Right, because of course US companies have no desire to do business with >> the rest of the world. > > I'm merely pointing out that it is the legacy of the history of > information technology that is chauvinistic. That happens to be > the way things are, I did not say that's the way they should be. > You imply that's the way they should be by placing pre-conditions on the adoption of anything but ASCII as a default. >> I'm not given to ad hominem attacks, but this remark really seems to >> indicate that "chauvinistic cretin" might apply to you. > > _I_ didn't invent ASCII or EBCDIC. Why weren't the European > and Chinese languages considered when these were developed > 40-50 years ago? Because they were "chauvinistic cretins"? > Is that what you think? > No. In those days (sixty years ago) less was possible, and achieving anything, however limited, represented progress. Certainly it would have been nice to see the adoption of more internationally-applicable standards, but the codes that were used in the early computes had their roots in even earlier information systems like teletypes and telex machines. It was partly a matter of adapting what already existed. In these more enlightened times we can build systems for larger audiences by making them applicable to a wider range of languages and character sets. The standards and the technology already exist to do so. So, "chauvinistic" because you appear to require the users of the non-ASCII parts of Unicode to contribute something before they get systems that suit their needs, when in fact the boot is on the other foot and it behooves the manufacturers to adapt to market needs if they want to serve those markets. "Cretin" (in the sense of possessing sub-normal intelligence, as I do not know whether or not you have a thyroid deficiency) because you do not seem to be able to think of the needs of the larger community, and respond to argument with non-sequitur and evasion. Plus, you annoyed me. I should have restrained myself. Sorry. >> You'll be gald >> to know you are unlikely to hear from me again. > > Why? Because I tend to act as a gadfly? To point out that > the emperor is, in fact, naked? Because the professional > programming community doesn't like their dirty laundry > aired in public? > No, because everything you discuss appears to be discussed in the most simplistic terms, with limited perspective. So a discussion with you is about as satisfying as a discussion with a twelve year old child. >> Your perception of the development of information technology is so >> skewed you would be better off knowing nothing. > > My perception is skewed? Why then, does Unicode even exist? > To meet real needs which you appear to feel shouldn't be met until the people with those needs have built their own information technologies (or in your words "created the next generation of computers."). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From bscrivener42 at gmail.com Thu Sep 6 22:58:33 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Fri, 07 Sep 2007 02:58:33 -0000 Subject: why should I learn python In-Reply-To: <1189118200.040934.151520@57g2000hsv.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <1189117798.506367.278560@y42g2000hsy.googlegroups.com> <1189118200.040934.151520@57g2000hsv.googlegroups.com> Message-ID: <1189133913.480902.289070@57g2000hsv.googlegroups.com> On Sep 6, 5:36 pm, Andr? wrote: > Easy to read, easy to write, good libraries and, I have found, an > extremely helpful community. > > Hobbyists (like me) can work on projects written in Python on and off > (sometimes for weeks if not months without programming) and be able to > resume the work very quickly (because it's so easy to read and > understand the code). > I second these. I am not a programmer. You can get busy with other projects for weeks and come back to Python code and pick up where you left off, because it uses WORDS. Try remembering what (<>) or <*> means after being away from Perl for a month. rd From siona at chiark.greenend.org.uk Wed Sep 19 09:16:48 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 19 Sep 2007 14:16:48 +0100 (BST) Subject: Sets in Python References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> Message-ID: sapsi wrote: > Why can't lists be hashed? Several people have answered "because they're mutable" without explaining why mutability precludes hashing. So: Consider a dict (dicts have been in Python a *lot* longer than sets, and have the same restriction) which allowed lists as keys: d = {} k = [1, 2] d[k] = None Now, if I were to do: k.append(3) what would you expect: d.keys() to return? Did d magically rehash k when it was modified? Did d[k] take a copy of k, and if so, how deep was the copy (consider d[[1, k]] = None followed by a modification to k)? Leaving the hash unchanged and relying on collision detection to resolve won't work, since you may go directly for d[[1, 2, 3]] and not spot that there's already an entry for it since it's been hashed under [1, 2]. "Practicality beats purity" and the design decision was to simply sidestep these issues by disallowing mutable dict keys. And as the set implementation is based on the dict implementation, it applies to sets to. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From http Sat Sep 22 02:38:38 2007 From: http (Paul Rubin) Date: 21 Sep 2007 23:38:38 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <46f45f02$0$15350$4c368faf@roadrunner.com> Message-ID: <7xps0bgq6p.fsf@ruckus.brouhaha.com> Carl Banks writes: > Especially someone like an > engineer (in the classical sense), who isn't building versatile software > packages, won't need to resort to functional programming much. http://www.math.chalmers.se/~rjmh/Papers/whyfp.html From fakeaddress at nowhere.org Tue Sep 11 00:12:20 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 11 Sep 2007 04:12:20 GMT Subject: Modul (%) in python not like in C? In-Reply-To: <13ec37dri08s7a3@corp.supernews.com> References: <13ec37dri08s7a3@corp.supernews.com> Message-ID: Scott David Daniels wrote: > C, which was designed as a "high level assembly language," does not > tightly define the results of / and % for negative numbers. Instead > it defines the result for positive over positive, and constrains the > result for the others. Not true. Here it is again: When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.(87) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a. [...] 87) This is often called ??truncation toward zero??. [International Standard ISO/IEC 9899:1999, Section 6.5.5 Multiplicative operators, Paragraph 6 and footnote 87] -- --Bryan From gagsl-py2 at yahoo.com.ar Mon Sep 3 03:17:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Sep 2007 04:17:29 -0300 Subject: How does super() work? References: Message-ID: En Fri, 31 Aug 2007 17:58:24 -0300, Lamonte Harris escribi?: > I've searched Google, and other search engines to try to find out how > super() works. Can someone explain in short detail how super() works? I > may and may not need to know this information, but it is good to know. See http://www.python.org/download/releases/2.2.3/descrintro/#cooperation -- Gabriel Genellina From zentraders at gmail.com Thu Sep 6 19:48:31 2007 From: zentraders at gmail.com (Zentrader) Date: Thu, 06 Sep 2007 16:48:31 -0700 Subject: Using wild character In-Reply-To: <5k9pjoF2mrncU1@mid.uni-berlin.de> References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> <1189058095.671230.262190@o80g2000hse.googlegroups.com> <5k9pjoF2mrncU1@mid.uni-berlin.de> Message-ID: <1189122511.231602.217710@w3g2000hsg.googlegroups.com> On Sep 6, 12:47 am, Marc 'BlackJack' Rintsch wrote: > On Wed, 05 Sep 2007 22:54:55 -0700, TheFlyingDutchman wrote: > > To do a "*string" wildcard filter use the endswith() function instead > > of startswith() and to do a *string* type wildcard filter use > > the find() function > -1. > > Maybe better the ``in`` operator for the '*string*' type. `str.find()` > will go away in the future. > > Ciao, > Marc 'BlackJack' Rintsch string.find serves a useful purpose in that it returns the starting location of the string found, or -1 if not found, so if you wanted to slice "abdecf" on"c", string.find will tell you where that is. From bignose+hates-spam at benfinney.id.au Tue Sep 25 00:41:55 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 25 Sep 2007 14:41:55 +1000 Subject: Support for Vim (was: vim - what's a smarttab?) References: <1190624225.926815.149720@50g2000hsm.googlegroups.com> <1190693749.202770.227890@57g2000hsv.googlegroups.com> Message-ID: <87ejgnnyp8.fsf_-_@benfinney.id.au> 7stud writes: > Thanks! I spent an hour hunting around on google with no > success. :( > > Another question if you don't mind Rather than have comp.lang.python turn into a support forum for questions about specific editors, I'll point you to the Vim site: which has many resources for assistance: -- \ "True greatness is measured by how much freedom you give to | `\ others, not by how much you can coerce others to do what you | _o__) want." --Larry Wall | Ben Finney From tismer at stackless.com Thu Sep 20 22:57:44 2007 From: tismer at stackless.com (Christian Tismer) Date: Fri, 21 Sep 2007 04:57:44 +0200 Subject: Can't import Stackless in Pythonwin In-Reply-To: <1171118831.573543.231200@m58g2000cwm.googlegroups.com> References: <1171039856.077320.163610@s48g2000cws.googlegroups.com> <1171118831.573543.231200@m58g2000cwm.googlegroups.com> Message-ID: <46F33328.7000405@stackless.com> archaegeo at gmail.com wrote: ... > But for pythonwin i get >>>> import sys >>>> print sys.version > 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] >>>> print sys.executable > C:\Python25\Lib\site-packages\pythonwinPythonwin.exe > > So does this mean stackless is not usable with pythonwin? Your python.dll needs to live in your \system32 directory (or in the current directory if you are running stackless temporarily). If things are set up properly, you will be able to import stackless from PythonWin. Be aware of Stackless not being very stable on PythonWin, cause it creates a new interpreter state after every input. It works to some extent, but I did not test this for a longer time. Also, it is quite likely that the debugger gets confused by tasklet switching. It seems to work pretty stable with wxpython and Boa constructor. wxpython has a few problems, too, but they are easy to work around. Contact me privately or on the stackless list if you need support. > Also, is pythonwin needed for the win32 extensions and mfc? yes. cheers - chris -- Christian Tismer :^) tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From afriere at yahoo.co.uk Mon Sep 3 21:29:07 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 03 Sep 2007 18:29:07 -0700 Subject: Python is overtaking Perl In-Reply-To: <20070904024908.b8aca60c.sulsa@gazeta.pl> References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> <20070904024908.b8aca60c.sulsa@gazeta.pl> Message-ID: <1188869347.102325.119830@w3g2000hsg.googlegroups.com> On Sep 4, 10:49 am, Sulsa wrote: > On Tue, 04 Sep 2007 00:32:23 -0000 > > Ben wrote: > > Here are the statistics from Google Trends: > > >http://benyang22a.blogspot.com/2007/09/perl-vs-python.html > > This chart is showing that amount of python programers is smaller every > year :( How do you figure that? Isn't the chart showing the frequency of those particular terms combined as a fraction of the total search volume on Google? From arkanes at gmail.com Tue Sep 4 16:49:20 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 4 Sep 2007 15:49:20 -0500 Subject: Undeterministic strxfrm? In-Reply-To: References: Message-ID: <4866bea60709041349x5716d8b2l19796e490a048656@mail.gmail.com> On 9/4/07, Tuomas wrote: > Gabriel Genellina wrote: > > En Tue, 04 Sep 2007 07:34:54 -0300, Tuomas > > escribi?: > > > >> Python 2.4.3 (#3, Jun 4 2006, 09:19:30) > >> [GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2 > >> Type "help", "copyright", "credits" or "license" for more information. > >> >>> import locale > >> >>> def key(s): > >> ... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8') > >> ... return locale.strxfrm(s.encode('utf8')) > >> ... > >> >>> first=key(u'maupassant guy') > >> >>> first==key(u'maupassant guy') > >> False > >> >>> first > >> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 > >> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79' > >> > >> >>> key(u'maupassant guy') > >> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 > >> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5' > >> > >> >>> > >> > >> May be this is enough for a sort order but I need to be able to catch > >> equals too. Any hints/explanations? > > > > > > I can't use your same locale, but with my own locale settings, I get > > consistent results: > > > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > > (Intel)] on > > win32 > > Type "help", "copyright", "credits" or "license" for more information. > > py> import locale > > py> locale.setlocale(locale.LC_COLLATE, 'Spanish_Argentina') > > 'Spanish_Argentina.1252' > > py> def key(s): > > ... return locale.strxfrm(s.encode('utf8')) > > ... > > Because I am writing a multi language application I need to plase the > locale setting inside the key function. Actually I am implementing > binary search in a locally sorted list of strings and should be able to > count on stable results of strxfrm despite possibly visiting another > locale at meantime. Could repeated calls to setlocale cause some problems? > > > py> first=key(u'maupassant guy') > > py> print repr(first) > > '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02 > > > > \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01' > > py> print repr(key(u'maupassant guy')) > > '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02 > > > > \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01' > > py> print first==key(u'maupassant guy') > > True > > > > Same thing with Python 2.4.4 > > > > I get the same unstability with my locale 'fi_FI.utf8' too, so I am > wondering if the source of the problem is the clib or the Python wrapper > around it. Looking at the python source, the only possible error case I can see is that the wrapper assumes the string returned by strxfrm will be null terminated. It's not 100% clear from the documentation I have that the string is guaranteed to be null terminated, although it's implied, so this is a remotely possible case. You might try calling the clib directly. From bignose+hates-spam at benfinney.id.au Mon Sep 24 05:01:53 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 24 Sep 2007 19:01:53 +1000 Subject: Passing parameters at the command line (New Python User) References: <1190621098.582906.49760@r29g2000hsg.googlegroups.com> Message-ID: <87d4w8phby.fsf@benfinney.id.au> cjt22 at bath.ac.uk writes: > I have never used Python to pass in arguments at the command line so > any help would be much appreciated. Your 'main()' approach is good. I'd rather have the function require an 'argv' parameter, and have the default set only in the 'if __name__ == "__main__":' block, since that fits my ideas better about the defaults. def main(argv): parse_commandline(argv) do_cool_stuff() if __name__ == "__main__": from sys import argv main(argv) I also tend to catch SystemExit in the function, so the exit code can be returned instead of raised; but that's outside the scope of this thread. For anything more advanced than unconditionally grabbing arguments in sequence from the command line, you should investigate the 'optparse' module from the standard library. -- \ "Holy knit one purl two, Batman!" -- Robin | `\ | _o__) | Ben Finney From stef.mientki at gmail.com Sun Sep 23 11:28:38 2007 From: stef.mientki at gmail.com (stef mientki) Date: Sun, 23 Sep 2007 17:28:38 +0200 Subject: building a GUI In-Reply-To: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> Message-ID: <46F68626.6010907@gmail.com> yadin wrote: > if i were up to make a GUI chich are the advantages of choosing python > over matlab or java? > > As MatLab has a very lousy GUI, any other language would be an advantage ;-) The best is Delphi, second is VB, then comes SciLab, Python, etc I don't know where Java fits in. But as Wildemar said, your question is much to broad. cheers, Stef From sjmachin at lexicon.net Sun Sep 16 19:21:53 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 16 Sep 2007 16:21:53 -0700 Subject: Try this In-Reply-To: <1189983233.709832.124290@19g2000hsx.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> Message-ID: <1189984913.956999.163100@n39g2000hsh.googlegroups.com> On Sep 17, 8:53 am, "mensana... at aol.com" wrote: > On Sep 16, 5:28?pm, John Machin wrote: > > > > > On Sep 17, 7:54 am, "mensana... at aol.com" wrote: > > > > On Sep 16, 2:22?pm, Steve Holden wrote: > > > > > mensana... at aol.com wrote: > > > > > On Sep 16, 1:10?pm, Dennis Lee Bieber wrote: > > > > >> On Sun, 16 Sep 2007 01:46:34 -0700, GeorgeRXZ > > > > >> declaimed the following in comp.lang.python: > > > > > >>> Then Open the Notepad and type the following sentence, and save the > > > > >>> file and close the notepad. Now reopen the file and you will find out > > > > >>> that, Notepad is not able to save the following text line. > > > > >>> Well you are speed > > > > >>> This occurs not only with above sentence but any sentence that has > > > > >>> 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) > > > > >> I tried. I also opened the saved file in SciTE... > > > > >> And the text WAS there... > > > > > >> It is Notepad that can not properly render what it, > > > > >> itself, saved. > > > > > > C:\Documents and Settings\mensanator\My Documents>type huh.txt > > > > > Well you are speed > > > > > > Yes, file was saved correctly. > > > > > But reopening it shows 9 unprintable characters. > > > > > If I copy those to a new file (huh1.txt): > > > > > > C:\Documents and Settings\mensanator\My Documents>type huh1.txt > > > > > ????????? > > > > > > But wait...the new file is 20 characters, not 9. > > > > > > 09/16/2007 01:44 PM 18 huh.txt > > > > > 09/16/2007 01:54 PM 20 huh1.txt > > > > > > C:\Documents and Settings\mensanator\My Documents>dump huh.txt > > > > > huh.txt: > > > > > 00000000 5765 6c6c 2079 6f75 2061 7265 2073 7065 Well you are spe > > > > > 00000010 6564 ed > > > > > > Here's what it's actually doing: > > > > > > C:\Documents and Settings\mensanator\My Documents>dump huh1.txt > > > > > huh1.txt: > > > > > 00000000 fffe 5765 6c6c 2079 6f75 2061 7265 2073 .~Well you are s > > > > > 00000010 7065 6564 peed > > > > > One word: Unicode. > > > > > The "open" and "save" dialogs allow you to specify an encoding. > > > > And the encoding specified was ANSI. > > > > > If you > > > > specify Unicode the you will get what you see above. > > > > And if you specify ANSI _before_ you click the file name, > > > the specification switches to Unicode and has to then > > > be manually switched back to ANSI. > > > > > If you specify ANSI > > > > you will get the text you entered. > > > > It's still a bug in the "open" dialog. > > > It's more like a bug/feature in its encoding detector. > > It is NOT a feature. If I save something as ANSI, > there is no excuse for it not to re-open in ANSI. It doesn't know that you or anybody else saved it as "ANSI". All it is seeing is a string of bytes. If you are silly enough to type in ???????????????????????? [that's "\xef\xbb\xbf" repeated a few times] and save it as "ANSI", it has every excuse to open it as something else :-) > > > I can get it to > > switch to Unicode only if there's an even number of characters AND the > > line is NOT terminated by CRLF -- add/remove one alpha character, or > > hit the enter key at the end of the line, and it won't detect it as > > Unicode when you open it again. > > > You only get the BOM (0xfffe) if you are silly enough to save it while > > it's open in Unicode mode. > > That was a test. I wasn't so stupid as to save > to the original file, but to make a copy. > > > > > > > By the way, this has precisely what to do with Python? > > > > I've been known to use Notepad to create Python > > > source code. > > > Your source code would have to be trivially short to trigger the > > strange behaviour. > > Makes you wonder what other edge cases aren't > handled properly. > > Makes you wonder why Microsoft doesn't employ > professional programmers. I'm eagerly awaiting publication of your professional specification for correctly detecting the encoding of an arbitrary stream of bytes :-) From ogbash at gmail.com Mon Sep 24 12:05:17 2007 From: ogbash at gmail.com (Oleg Batrashev) Date: Mon, 24 Sep 2007 16:05:17 -0000 Subject: building a GUI In-Reply-To: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> Message-ID: <1190649917.680777.101540@w3g2000hsg.googlegroups.com> On Sep 23, 5:21 pm, yadin wrote: > if i were up to make a GUI chich are the advantages of choosing python > over matlab or java? Haven't seen any free visual layout program for swing, swing is somewhat messy - unnecessary complex layout classes. Compile - run cycle without visual layouting is pain. Swing look is unnatural, native looks are buggy. glade + pygtk works well for me (in linux). Oleg From bdesth.quelquechose at free.quelquepart.fr Wed Sep 19 15:25:38 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 21:25:38 +0200 Subject: cannot create my own dict In-Reply-To: References: Message-ID: <46f177d9$0$12915$426a34cc@news.free.fr> Steve Holden a ?crit : > A.T.Hofkamp wrote: > (snip) >> So if copying all methods of a native dictionary is not enough, what >> should I >> do to make my class work as a dictionary WITHOUT deriving from dict >> (which will >> obviously work). >> > You have to overwrite the "__new__" method to return an object of your > new type. ??? This applies to subclasses of immutable types, but I don't see the point here. The problem is - as Peter pointed out - that __magic__ methods are not looked up in instances when using new-style classes. From nutsbreaker3 at gmail.com Tue Sep 18 14:47:06 2007 From: nutsbreaker3 at gmail.com (nutsbreaker3 at gmail.com) Date: Tue, 18 Sep 2007 11:47:06 -0700 Subject: World's best guitars ever!!!! Message-ID: <1190141226.315436.325350@w3g2000hsg.googlegroups.com> http://freeguitars.blogspot.com/ From kyosohma at gmail.com Wed Sep 12 12:05:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 12 Sep 2007 16:05:54 -0000 Subject: is it possible to use different font within one wxpython static text widget? In-Reply-To: References: Message-ID: <1189613154.244069.15590@o80g2000hse.googlegroups.com> On Sep 12, 10:26 am, "hyena" wrote: > problem is as title, bear me if this too silly or too naive. > > I use wx.statictext widget to show some information in GUI, there are some > numbers in the text to be emphasized in bigger other color. For example, in > sentence "the travel speed of this car is 40 km /hour", I would like "40" to > be bigger and in red color. I know I can use several statictext to get this > effect. But i am quite relucktant to do so since I am quite unfamiliar with > manageing the layout of widgets. > > Is there a convinient way to have this done? Thanks for any .input Without knowing what kind of interface you're making, I can only shoot in the dark. From your question, I would think that the FancyText widget would suffice. Other widgets that would be harder to use would be the StyledTextCtrl and the HtmlWindow (which I use for About dialogs). Check out the wxPython Demo for sample code on each of these widgets and sizers. Also see the Wiki for tips and tricks on using Sizers. There's a new SizedControl that's supposed to simplify creating layouts, although I haven't used it. And there's also XRC too. Mike From laurent.pointal at wanadoo.fr Wed Sep 19 16:39:28 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Wed, 19 Sep 2007 22:39:28 +0200 Subject: lxml and identification of elements in source Message-ID: <46f18900$0$5083$ba4acef3@news.orange.fr> Hello, I use lxml to parse a document, modify some elements in the tree, run xinclude on it (thanks to Stefan Behnel for the pointer), and finally use the data to feed my sax-aware tool. To report warnings/errors to the user (not related to XML itself, but to things like missing source for a cross-reference by example), is there a way to get the source-file and line/column of an element ? [note: these informations are available when lxml parse the source, but are they kept anywhere in the document tree ?] Thanks. Laurent. From apardon at forel.vub.ac.be Tue Sep 4 02:28:54 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Sep 2007 06:28:54 GMT Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> Message-ID: On 2007-09-03, Paul Rubin wrote: > Antoon Pardon writes: >> If I understand correctly that you are using urandom as a random >> generator I wouldn't trust too much on this performance. Urandom >> uses the systemwide entropy-pool. If other programs need this pool >> too, your performance can drop spectaculary. > > No the idea is that once there's enough entropy in the pool to make > one encryption key (say 128 bits), the output of /dev/urandom is > computationally indistinguishable from random output no matter how > much data you read from it. If you were talking about /dev/random I would agree. But this is what the man page on my system says about /dev/urandom A read from the /dev/urandom device will not block waiting for more entropy. As a result, if there is not sufficient entropy in the entropy pool, the returned values are theoretically vulnerable to a cryptographic attack on the algorithms used by the driver. Knowledge of how to do this is not available in the current non-classified literature, but it is the- oretically possible that such an attack may exist. If this is a concern in your application, use /dev/random instead. And reading from /dev/random can block if there is not enough entropy. -- Antoon Pardon From BjornSteinarFjeldPettersen at gmail.com Wed Sep 26 00:17:44 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Wed, 26 Sep 2007 04:17:44 -0000 Subject: %s shortcut? In-Reply-To: <1190775317.062210.234400@g4g2000hsf.googlegroups.com> References: <1190775317.062210.234400@g4g2000hsf.googlegroups.com> Message-ID: <1190780264.426322.237690@g4g2000hsf.googlegroups.com> On Sep 26, 4:55 am, james_027 wrote: > hi i have something like this > > cursor.execute(""" > select c.name, > (select from ap_invoice i where Month(i.date) = 1 and > Year(i.date) = %s and i.customer_id = c.id and i.status != 'CAN') jan, > (select from ap_invoice i where Month(i.date) = 2 and > Year(i.date) = %s and i.customer_id = c.id and i.status != 'CAN') feb, > (select from ap_invoice i where Month(i.date) = 3 and > Year(i.date) = %s and i.customer_id = c.id and i.status != 'CAN') mar > from ap_customer c > order by %s""", > [year, order_by]) > > what I could like to happen is ... since the first three %s points to > the same year variable, how do I let python know it without doing > [year ,year, year, order_by] ... This should be 12 I just cut it down > > Thanks > james You could do [year]*12 + [order_by] like so: >>> [1970] * 12 + ['foo'] [1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, 'foo'] >>> I don't know which database you're using, but the above doesn't look like SQL'92... -- bjorn From sjmachin at lexicon.net Tue Sep 18 17:31:52 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Sep 2007 14:31:52 -0700 Subject: How do you limit the # of lines Read? In-Reply-To: <1190149187.799482.151320@19g2000hsx.googlegroups.com> References: <1190149187.799482.151320@19g2000hsx.googlegroups.com> Message-ID: <1190151112.134222.208470@r29g2000hsg.googlegroups.com> On Sep 19, 6:59 am, kou... at hotmail.com wrote: > I am working on a loop for my code and was wondering if there is a way > to limit the number of lines read through? I'd hate to cut the test > file in order to run the code in the testing phase. Can you add a > value in the parenthesis of the readline() function? > > t = string.readline() # Limit this somehow? *STRING*.readline() ???? From rrr at ronadam.com Fri Sep 21 18:44:39 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 21 Sep 2007 17:44:39 -0500 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190412475.772358.109810@n39g2000hsh.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> Message-ID: <46F44957.6060700@ronadam.com> Cristian wrote: > My hope is to subtly reinforce the notion that functions are data > and can be passed around. The current function declaration doesn't > help with this. Creating a function and assigning it to a name is > exactly what Python does, why not have it come out in the syntax? It's > not necessary, yes, but I think it would be helpful for teaching > purposes. I think key may be to discuss names and name binding with your friend. How a name is not the object it self, like a variable is in other languages. For example show him how an object can have more than one name. And discus how names can be bound to nearly anything, including classes and functions. > Again, it's not necessary as much as it's more intuitive and obvious > what's going on. This helps a beginner sort out the process from the > syntax without taking it on faith. They can see the class declaration > and see "I'm defining just another attribute to this class only this > time it happens to be method". > > There is nothing functionally lacking in Python. I'm just curious if > there's anything Python can do syntax-wise to help a person better > grasp programming ideas and Python's inner workings. You could also discus factory functions with him. Once he gets that a function can return another function, then it won't be so much of a leap for a function to take a function as an argument. Of course he'll figure out all this sooner or later anyway. You can't be an engineer without a fair amount of brain cells committed to processing abstract concepts. Cheers, Ron From R.W.Thomas.02 at cantab.net Thu Sep 27 13:12:59 2007 From: R.W.Thomas.02 at cantab.net (Richard Thomas) Date: Thu, 27 Sep 2007 18:12:59 +0100 Subject: True of False In-Reply-To: <1190912324.363127.26100@r29g2000hsg.googlegroups.com> References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> <1190912324.363127.26100@r29g2000hsg.googlegroups.com> Message-ID: <1b54228d0709271012h5658aef8rce2fbf40e6231a59@mail.gmail.com> On 27/09/2007, Casey wrote: > On Sep 27, 12:48 pm, "Simon Brunning" > wrote: > > On 9/27/07, kou... at hotmail.com wrote: > > > > > I tried writing a true and false If statement and didn't get > > > anything? I read some previous posts, but I must be missing > > > something. I just tried something easy: > > > > > a = ["a", "b", "c", "d", "e", "f"] > > > > > if "c" in a == True: > > > Print "Yes" > > > > > When I run this, it runs, but nothing prints. What am I doing wrong? > > > > Just use > > > > if "c" in a: > > > > and all will be well. The True object isn't the only truthy value in > > Python - see . > > I would recommend the OP try this: > > run the (I)python shell and try the following: > > >>> a = [x for x in "abcdefg"] > >>> a > ['a','b','c','d','e','f','g'] > >>> "c" in a > True > >>> "c" in a == True > False > >>> ("c" in a) == True > True > > The reason your conditional failed is that it was interpreted as "c" > in (a == True) which is False. > the "==" operator binds at a higher precedence level than the "in" > operator, just as multiplication > binds higher than addition > Actually it evaluates '("c" in a) and (a == True)'. You can check like so: import dis a = list("abcdef") dis.dis(lambda: "c" in a == True) And just follow the bytecode operations. -- Richard. > -- > http://mail.python.org/mailman/listinfo/python-list > From msmanu78 at yahoo.com Mon Sep 3 07:35:44 2007 From: msmanu78 at yahoo.com (HR Head) Date: Mon, 03 Sep 2007 11:35:44 -0000 Subject: Urgently Required SAP CO-COPA Functional Lead Message-ID: <1188819344.552205.214360@d55g2000hsg.googlegroups.com> We urgently require following skill set for singapore client SAP CO-COPA Functional Lead: Person with a strong Costing background. Should have hands on SAP "COPA" experience Minimum two implementations in Controling based Profitability Analysis (COPA) and Product Costing (COPC) in the SAP COPA skill set. Project Asset and Project costing Must have 5+ years of SAP experience Should be capable of handling Blueprinting and be a good Communicator. O Base location: Al Khobar, KSA ( near Dhaharan) As the spec suggest, we are looking at predominantly a Costing person. He should have at least 2 implementation experience on costing preferably Project Asset, + Profitability Analysis and Product costing. A muslim candidate would be ideal, but this is not mandatory. Pakistani / Indonesian and Malay apart from Indians will be a good bet. O Duration: 15 months O Rate: US$ 7500 per month (housing included) + medical insurance + Air travel Please feel free to refer your friends for same cv's to be send to isoft_staff at yahoo.com From skulka3 at gmail.com Thu Sep 27 12:29:16 2007 From: skulka3 at gmail.com (skulka3 at gmail.com) Date: Thu, 27 Sep 2007 16:29:16 -0000 Subject: Implement file download using python Message-ID: <1190910556.681518.277220@o80g2000hse.googlegroups.com> Hello, I want to implement file downloads inside an authenticated web page, such that when a user clicks a link, the server side python code connects to a ftp server, downloads a relevant file and then streams the file to the browser for the user to open it with the appropriate application. In this case it will either be a pdf or a tiff file. This function is quite similar to something like writing raw bytes to a ServletOutputStream in java to be rendered directly to the user. It would be nice if someone can provide guidance, examples on how such a task may be accomplished using python. Thanks, Salil . From miki.tebeka at gmail.com Sun Sep 9 02:21:05 2007 From: miki.tebeka at gmail.com (Miki) Date: Sun, 09 Sep 2007 06:21:05 -0000 Subject: debugging program that uses ctypes In-Reply-To: <1189178285.647177.216320@g4g2000hsf.googlegroups.com> References: <1189178285.647177.216320@g4g2000hsf.googlegroups.com> Message-ID: <1189318865.787351.310680@r34g2000hsd.googlegroups.com> Hello Marco, > hi all, I have a python program that calls a dll through ctypes > (py2.5). In some (reproducible) > conditions the program crashes with an error in ctypes module. > How can I trace down the problem? I have created a debug build of > python but I also use pyodbc > and dateutil libraries in my program and I don't know how to make them > visible to python_d.exe > Am I using the right approach? If you are the one compiling the called module, you can add `__asm int 3` somewhere in the code. When this is reached, the windows debugger will pop up on the line. HTH, -- Miki http://pythonwise.blogspot.com From michele.simionato at gmail.com Wed Sep 19 09:41:34 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 19 Sep 2007 13:41:34 -0000 Subject: super() doesn't get superclass In-Reply-To: References: <8764281uea.fsf@benfinney.id.au><876427zhzq.fsf@benfinney.id.au> <13f196qktorgc88@corp.supernews.com> <873axbxl2f.fsf@benfinney.id.au> Message-ID: <1190209294.584372.173410@o80g2000hse.googlegroups.com> On Sep 19, 3:22 pm, Sion Arrowsmith wrote: > Ben Finney wrote: > > > If a function is named 'super' and operates on > >classes, it's a pretty strong implication that it's about > >superclasses. > > But it doesn't (under normal circumstances) operate on classes. > It operates on an *instance*. And what you get back is a (proxy > to) a superclass/ancestor of the *instance*. > > (And in the super(A, B) case, you get a superclass/ancestor of > *B*. As has just been said somewhere very near here, what is > misleading is the prominence of A, which isn't really the most > important class involved.) > Happily A (and B too) will become invisible in Python 3000. Michele Simionato From bdesth.quelquechose at free.quelquepart.fr Sun Sep 16 15:12:04 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 16 Sep 2007 21:12:04 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <1189807123.163995.104180@g4g2000hsf.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189807123.163995.104180@g4g2000hsf.googlegroups.com> Message-ID: <46ed8034$0$19495$426a74cc@news.free.fr> John Roth a ?crit : > On Sep 12, 11:35 am, TheFlyingDutchman wrote: > >>On Sep 12, 4:40 am, Bjoern Schliessmann wrote: >> >>>Ivan Voras wrote: >>> >>>>What does "self" have to do with an object model? It's an >>>>function/method argument that might as well be hidden in the >>>>compiler without ever touching the role it has (if not, why?). I >>>>agree that it's needless noise in a language. >> >>>If this was needless, why do C++ and Java have the "this" pointer? >> >>"this" in C++ and Java is not shown in the parameter list, which was >>what he was >>complaining about. He wants >> >>class MyClass: >> def SomeFunction(someParameter): >> self.someParameter = someParameter >> >>not >> >>class MyClass: >> def SomeFunction(self, someParameter): >> self.someParameter = someParameter >> >>The confusing way about the current Python method when you first >>encounter it is >> why is "self" being passed in when you write the function but not >>when you call it. If the compiler is smart enough to know that >> >> a = MyClass() >> a.SomeFunction(12) >> >>SomeFunction() has a "self" implicitly added to the parameter list, it >>seems that it should be smart enough to know that a function defined >>in a class has a "self" implicitly added to the parameter list. > > > Pretty close. This is one of the things that's always puzzled me about > the discussion. Making self and cls keyword pseudo-constants that get > the current instance and class from the stack frame (or raise an > exception) would eliminate them from the method header. I suppose that by header, you mean prototype or signature. But anyway, it's not a *method* signature, it's a *function* signature - and the compiler persists to have nothing to do with all this... > It would ALSO eliminate a whole level of indirection in method > invocation and get rid of the instancemethod, classmethod and > staticmethod wrapper classes. This would be a significant > simplification. If it had been done earlier, it would have eliminated > most of the justification for method attributes (those silly @ > things), "those silly @ things" has *nothing* to do with methods nor with attributes. It's just syntactic sugar for HOFs. Period. > thus showing that unneeded complexity breeds more unneeded > complexity. John, there are plenty of other OOPls around that don't requires neither explicit use of the instance/class reference nor mention of it in the function . If after having read this whole thread and all relevant documentation, you still don't understand why Python works that way and why most of us are *totally* happy with the way it works, I strongly suggest that you switch to another language. Not that I have nothing personal against you, but it should be quite clear that this part of Python is not going to change - FWIW, as Alex pointed out, I doubt even GvR could impose such a change now. From arnau at ehas.org Wed Sep 5 12:30:27 2007 From: arnau at ehas.org (Arnau Sanchez) Date: Wed, 05 Sep 2007 18:30:27 +0200 Subject: Text processing and file creation In-Reply-To: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> Message-ID: <46DED9A3.7070006@ehas.org> malibuster at gmail.com escribi?: > I have a text source file of about 20.000 lines. >>From this file, I like to write the first 5 lines to a new file. Close > that file, grab the next 5 lines write these to a new file... grabbing > 5 lines and creating new files until processing of all 20.000 lines is > done. > Is there an efficient way to do this in Python? Perhaps you could provide some code to see how you approached it? From steve at holdenweb.com Thu Sep 27 21:17:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 21:17:30 -0400 Subject: Python 3.0 migration plans? In-Reply-To: References: Message-ID: James Stroud wrote: > Steve Holden wrote: >> I wondered if a straw poll could get some idea of readers' thoughts >> about when they will be migrating to 3.0 on, so I used the new widget on >> Blogger to add a poll for that. >> >> I'd appreciate if if you would go to >> >> http://holdenweb.blogspot.com/ >> >> and register your vote on your intended migration timescale. >> >> Thanks! > > I'm going to abstain voting until 'public beta + about 1 year' is a choice. > Richard Jones wrote: > I'll use the "no plans" response for my actual "no simple answer" real > response. > > So what we need is a poll on what the questions should be. I *love* c.l.py. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From steven.bethard at gmail.com Sun Sep 2 22:40:35 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 02 Sep 2007 20:40:35 -0600 Subject: reload(sys) In-Reply-To: <1188662049.337034.58220@w3g2000hsg.googlegroups.com> References: <1188521143.421431.119100@l22g2000prc.googlegroups.com> <1188564816.430863.219560@w3g2000hsg.googlegroups.com> <1188662049.337034.58220@w3g2000hsg.googlegroups.com> Message-ID: S?nmez Kartal wrote: > I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as > "f.write(str(xml))". At execution of that line, it gives error with > description, configure your default encoding... > [and later] > > I get this when it happens: "Decoding Error: You must configure > default encoding" which comes from in the code excerpt in > xmlbuilder.py (http://rafb.net/p/9rURi822.html) Can you show the code where you populate the XMLBuilder? I'm guessing you're doing something like:: import xmlbuilder builder = xmlbuilder.XMLBuilder() builder.foo = dict(bar='? and ?') str(builder) That breaks because the string '? and ?' is not properly encoded. Have you declared an encoding in your source file? PEP 263 shows you how: http://www.python.org/dev/peps/pep-0263/ Note that with Python 2.5 the code above gives a SyntaxError without a proper encoding. You should also probably be prefixing your string literals containing weird characters with "u" to make them unicode. Doing both of these in the code above made it work for me. STeVe From nickel_and_dime_2death at yahoo.com Fri Sep 7 13:39:42 2007 From: nickel_and_dime_2death at yahoo.com (nickel_and_dime_2death at yahoo.com) Date: Fri, 07 Sep 2007 10:39:42 -0700 Subject: Example script -- Group Project Task Scheduler Message-ID: <1189186782.187744.28740@57g2000hsv.googlegroups.com> Hello, trying to get UpToSpeed with a cross-platform application that would mimic capabilities like Microsoft Project. Playing around with code is what works for me. Searching is a mangled process, i.e. I've banged around terms like: "project", "scheduler", "class scheduler", "student calendar" ... and on and on. Python descriptions / howtos / tutorials / documentations have used most of the search terms I can think of define Python's nuts and bolts. Web research of my quest is not getting me to any examples I want to see. Really, lang.java: class scheduler brings up my "ms project" mimic concept for java code. I want to try Python and pythonic coding. I want code that would list job tasks in a work-week grid and ultimately drag a block of text to a new location within that week scheduler if changes were needed. I anticipate XML for my database, which is what lead me to Python. Thanks, if somebody out there can offer pointer(s) to an example(s). From bignose+hates-spam at benfinney.id.au Tue Sep 18 04:19:41 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 18 Sep 2007 18:19:41 +1000 Subject: super, apply, or __init__ when subclassing? References: <1190100791.740269.62880@k79g2000hse.googlegroups.com> Message-ID: <87abrkz8pu.fsf@benfinney.id.au> "exhuma.twn" writes: > This is something that keeps confusing me. If you read examples of > code on the web, you keep on seeing these three calls (super, apply > and __init__) to reference the super-class. This looks to me as it is > somehow personal preference. But this would conflict with the "There > one way to do it" mind-set. > > So, knowing that in python there is one thing to do something, these > three different calls must *do* domething different. But what exactly > *is* the difference? > > ------------ Exampel 1: ----------------------------- > > class B(A): > def __init__(self, *args): > A.__init__(self, args) > > ------------ Exampel 2: ----------------------------- > > class B(A): > def __init__(self, *args): > apply( A.__init__, (self,) + args) > > ------------ Exampel 3: ----------------------------- > > class B(A): > def __init__(self, *args): > super(A,self).__init__(*args) Note that your examples 1 and 3 aren't different *calls*. They are different ways of *getting at* the same class: either name it explicitly (as in example 1) or use 'super' to get it for you. Also, example 3 should instead call 'super(B, self).__init__'. If you're going to go to the bother of actually *specifying* the class 'A', it's silly to call 'super' to get at it *again*. The broader picture: I think you're right that this is ridiculously difficult in Python. The community elders would have us use 'super' to get at our inherited '__init__', but that doesn't work very well so most people use your example 1. -- \ "The most merciful thing in the world... is the inability of | `\ the human mind to correlate all its contents." -- Howard | _o__) Philips Lovecraft | Ben Finney From __peter__ at web.de Wed Sep 19 08:16:09 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2007 14:16:09 +0200 Subject: UTF-8 characters in doctest References: <1190202459.229197.297350@n39g2000hsh.googlegroups.com> Message-ID: Bzyczek wrote: > So my question is: Is it possible to run doctests with UTF-8 > characters? And if your answer will be YES, tell me please how... Use raw strings in combination with explicit decoding and a little try-and-error. E. g. this little gem passes ;) # -*- coding: utf8 -*- r""" >>> f("???".decode("utf8")) (u'\xe4\xf6\xfc',) """ def f(s): return (s,) if __name__ == "__main__": import doctest doctest.testmod() Peter From luismgz at gmail.com Sun Sep 23 21:01:39 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 24 Sep 2007 01:01:39 -0000 Subject: TRying to import files from my folder not pythons lib folder In-Reply-To: References: <1190395964.541835.114350@50g2000hsm.googlegroups.com> <1190396569.732154.234270@r29g2000hsg.googlegroups.com> Message-ID: <1190595699.093793.100960@w3g2000hsg.googlegroups.com> Steve Holden wrote: > kyosohma at gmail.com wrote: > > On Sep 21, 12:32 pm, "tedpot... at gmail.com" > > wrote: > >> Hi, > >> > >> I'm trying to create my own lib of functions, but it seems like I can > >> only import them if they are in pythons lib folder. > >> > >> Example > >> I have a folder called > >> K:\mypython > >> > >> Now in the interactive python shell I type > >> Import k:\mypython\listall > >> And get a error on : > >> > >> If I store listall.py in pythons lib folder and type > >> Limport listall > >> > >> It works fins. > >> > >> Can I create my own library of functions and store them in a separate > >> dir???? > >> > >> Also I try to creat a folder in pythomns lib folder and that did not > >> work > >> > >> Help > >> -Ted > > > > One workaround is to do to this: > > > > > > > > import sys > > sys.path.append(r'K:\mypython') > > import listall > > > > > > > > You can also add your path to the .pth file, but I've never done that, > > so I can't tell you how. > > > > Hope that helps! > > > > Mike > > > The easiest way, particularly for testing, is to set the PYTHONPATH > variable. It should be a colon-separated list of directories on Unices, > and a semi-colon separated list on Windows. Those directories will be > added to sys.path. > > See http://docs.python.org/tut/node8.html for yet more. > > regards > Steve > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline This is exactly what I did, but I have a new problem now: After seting PYTHONPATH I'm no longer able to start IDLE from the start menu. It seems the system cannot find the file. But if I eliminate PYTHONPATH, everything works as it used to. I set PYTHONPATH because I wanted to import any existing file in my desktop without having to use sys.path.append... It works when using the command line but strangely, something get messed up with IDLE. Any hint? Luis From horpner at yahoo.com Wed Sep 12 11:25:13 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 12 Sep 2007 15:25:13 GMT Subject: Enum class with ToString functionality References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <87bqca9hrw.fsf@benfinney.id.au> <1189472591.797327.189180@w3g2000hsg.googlegroups.com> <13ee5hmhmgr3d14@corp.supernews.com> Message-ID: On 2007-09-11, Steven D'Aprano wrote: > Perhaps Ben should have followed the usual practice of > commercial, closed- source software developers and started > counting his version numbers at one instead of zero, miss a few > releases, use randomly large increments occasionally, and ended > up with a current version number of 2.7.1 for the exact same > level of functionality. > > Or he could have called it "Enum XP" (for "eXtra Programming" > perhaps) or "Enum 2007". The next minor release could be "Enum > 2008", and the next major update could be called "Enum > Professional Capowie!!!". I like the (priviledged) code names adopted by the Linux community for special versions, e.g., Enum 2.7.1 (Flapjacks). This would really tie the Enum-using community together, and make messages about it much cuter. -- Neil Cerutti From jstroud at mbi.ucla.edu Fri Sep 14 16:38:05 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 14 Sep 2007 13:38:05 -0700 Subject: why does Configparser change names to lowercase ? In-Reply-To: References: Message-ID: stef mientki wrote: > hello, > > Why does Configparser change names to lowercase ? Because it is an annoying module and should be tossed for something better? Try this instead (and never look back): http://www.voidspace.org.uk/python/configobj.html > As Python is case sensitive (which btw I don't like at all ;-) > but now when really need the casesensitivity, > because it handles about names which should be recognized by human, > it changes everything to lowercase ???? So you are saying the case sensitivity is a good thing--or maybe you are still running Mac System 7 on your CSIIsi marveling at the wonders of HFS? James From wizzardx at gmail.com Wed Sep 19 16:11:08 2007 From: wizzardx at gmail.com (David) Date: Wed, 19 Sep 2007 22:11:08 +0200 Subject: Removing objects in a list via a wild card In-Reply-To: <8a6b8e350709191151n31b72bbvc3090031232d5fc8@mail.gmail.com> References: <8a6b8e350709191151n31b72bbvc3090031232d5fc8@mail.gmail.com> Message-ID: <18c1e6480709191311k663606a1peabbeffde2e5c705@mail.gmail.com> On 9/19/07, James Matthews wrote: > Hi List > > I have a list of files from my current directory: > > import os > > files = os.listdir(os.getcwd()) > > Now this list also includes some files that i don't want like my python > files... How would i remove them You can use regular expressions: import re files=[file for file in os.listdir(os.getcwd()) if not re.match('^.+\.((py)|(pyc))$', file)] You can also use fnmatch: from fnmatch import fnmatch files = [file for file in os.listdir(os.getcwd()) if not fnmatch(file, '*.py') and not fnmatch(file, '*.pyc')] From gagsl-py2 at yahoo.com.ar Fri Sep 14 00:53:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Sep 2007 01:53:03 -0300 Subject: PIL DPI trouble References: Message-ID: En Thu, 13 Sep 2007 23:50:39 -0300, Gary Bloom escribi?: > I notice that the PIL has trouble playing with the DPI of other programs > and image standards: when I create a file with Paint Shop Pro or > Photoshop, the PIL routines can't properly recognize the DPI. Do you mean that PIL doesn't read the DPI attribute from the file, or shows a different value than expected? > And when I create an image file (via the save method) of PIL, setting > the DPI, those same two programs can't read the DPI as set by them. Is > there a workaround for this? Using which file format? DPI is just an indication, a reference value. Changing it won't modify the image size in pixels, quality or resolution. Maybe you could post some sample code showing what you attempt to do. -- Gabriel Genellina From max at alcyone.com Sat Sep 1 23:51:05 2007 From: max at alcyone.com (Erik Max Francis) Date: Sat, 01 Sep 2007 20:51:05 -0700 Subject: How best to dynamically define methods (and functions)? In-Reply-To: References: Message-ID: Kenneth McDonald wrote: > I can see an obvious but hacky way to define a Python function at > runtime. I can't see any obvious way to add a method to a class at > runtime (though I'm sure one could do just about anything by digging > into the metaclass stuff, which I will do if needed). But pointers to > cleaner or easier existing ways to do this would be most appreciated. > > In case it's of interest in the context of the question, I need to > define a largish set of functions (and similar methods) that define a > XML-type markup language. Most of these functions will just be of the form > > def fun(...): > return Node('fun', ...) > > so it'd definitely be nice to just create most of them automatically, > and only do the special cases by hand. Something like:: method = ['fun', ...] for method in methods: setattr(MyClass, method, lambda *x: Node(method, *x)) The first argument here will be the implicit self, if you don't want that, strip off the first argument (or use lambda self, *x: ...). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis I like young girls. Their stories are shorter. -- Thomas McGuane From nszabolcs at gmail.com Sat Sep 15 13:15:13 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: Sat, 15 Sep 2007 17:15:13 -0000 Subject: c interfacing in 2.5 In-Reply-To: <5l1qjvF60829U1@mid.uni-berlin.de> References: <5l1qjvF60829U1@mid.uni-berlin.de> Message-ID: <1189876513.594129.136030@g4g2000hsf.googlegroups.com> Diez B. Roggisch wrote: > ctypes is for C. Where it is great to use. if you need simple wrappers then swig and ctypes are both good since they can generate it for you pyrex is also good for wrapping and for writing c extension code > If you need C++-wrapping, I recommend SIP. i recommend py++ for wrapping c++ From robert.rawlins at thinkbluemedia.co.uk Mon Sep 24 07:40:07 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 24 Sep 2007 12:40:07 +0100 Subject: Almost There - os.kill() In-Reply-To: <002601c7fe9d$52ffb9c0$f8ff2d40$@rawlins@thinkbluemedia.co.uk> References: <002601c7fe9d$52ffb9c0$f8ff2d40$@rawlins@thinkbluemedia.co.uk> Message-ID: <003201c7fe9f$a88ff3d0$f9afdb70$@rawlins@thinkbluemedia.co.uk> Woops, Spoke too soon, just wrapped them in int() and it works a charm :-D Rob From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Rawlins - Think Blue Sent: 24 September 2007 12:23 To: python-list at python.org Subject: Almost There - os.kill() Hello Guys, Finally got around to sitting down to tidy up this script this morning but I'm having a small syntax problem with os.kill() to kill a process on my system. Here is the code: def killApplication(): pid = file('/var/lock/MyApplication.lock').read().strip() logging.info('Killing Application Process: %s' % pid) os.kill(pid, 15) logging.info('Application %s Killed' % pid) As you can see if rips the PID from the lock file, which works fine as I get log data which says 'Killing Application Process: 3079' exactly as I would expect it too. However when I run this script I get the following error: Traceback (most recent call last): File "/pblue/new/Alive.py", line 50, in ? main() File "/pblue/new/Alive.py", line 47, in main doCheck() File "/pblue/new/Alive.py", line 43, in doCheck killApplication() File "/pblue/new/Alive.py", line 28, in killApplication os.kill(pid, 15) TypeError: an integer is required Which would suggest its passing those arguments in as the wrong data types to the kill command. What is the best way to convert these? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From zentraders at gmail.com Sun Sep 2 14:33:50 2007 From: zentraders at gmail.com (Zentrader) Date: Sun, 02 Sep 2007 11:33:50 -0700 Subject: Pivy problem and some other stuff In-Reply-To: <5k09ioF1j43jU1@mid.uni-berlin.de> References: <1188501707.593319.23330@m37g2000prh.googlegroups.com> <5jom54Fh543U2@mid.uni-berlin.de> <13df1kmak87mbb@corp.supernews.com> <1188743700.872880.21960@o80g2000hse.googlegroups.com> <5k09ioF1j43jU1@mid.uni-berlin.de> Message-ID: <1188758030.280527.40150@g4g2000hsf.googlegroups.com> > What meaningless error message are you talking about!? > > Ciao, > Marc 'BlackJack' Rintsch My mistake. It appears that this is no longer the case. And my apologies. It was probably in version 2.3 or earlier that this was a problem. Given the way that the Python community constantly improves the language, I should have checked first, but "shoulds" don't count. From kyosohma at gmail.com Thu Sep 13 10:08:14 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 13 Sep 2007 07:08:14 -0700 Subject: wx.ToplevelWindow.SetIcon: Native MS Windows error dialog pops up in wxPython app, no exception raised, no stack trace In-Reply-To: References: <1189689558.938858.43970@g4g2000hsf.googlegroups.com> Message-ID: <1189692494.658078.247350@22g2000hsm.googlegroups.com> On Sep 13, 8:41 am, Laszlo Nagy wrote: > > See main.py of the Demo, line 1129. img2py is in the following default > > location: > > C:\Python24\Lib\site-packages\wx-2.8-msw-unicode\wxPython\tools > > > Without seeing how you create the image, it's hard to troubleshoot, > > but I would guess that you have an absolute path that you're using in > > your script that is different than what the exe is looking for. > > I actually do have a wx.Icon instance loaded from a file. This problem > is not about loading a file into a wx.Icon instance. This why I'm > suprised about the message ("cannot load image file"). I already have > both the icon and the top level window in memory. If I comment out the > > self.SetIcon(icon) > > line in my code then there is no error message (and no icon on the > frame). The SetIcon method will call the Windows API at the end, and it > has nothing to do with files. It accepts a window handle and a pointer > to an icon resource. I cannot think about anything that would need to > read from a file while setting the icon of the frame. Moreover, the > icon is showing on the frame, looks like there is no error, so why am I > getting a message? It is not a python Exception, it pops out from > nowhere. :-) I suspect it will be an internal error in wxWidgets or > wxPython. But their mailing list is not working. :-( > > Thanks anyway. > > Laszlo I'm told the mailing list is now up. Sorry I wasn't more helpful. Mike From nick at craig-wood.com Thu Sep 20 05:30:16 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 20 Sep 2007 04:30:16 -0500 Subject: [Tutor] Finding prime numbers References: <1190218927.7991.25.camel@apprentice-laptop> <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> <1190219929.7991.28.camel@apprentice-laptop> Message-ID: Shawn Milochik wrote: > Any improvements anyone? >>> import gmpy >>> for x in range(3,1000,2): ... if gmpy.is_prime(x): ... print x,"is prime" ... 3 is prime 5 is prime 7 is prime [...] >>> gmpy.is_prime(2**607-1) 1 >>> gmpy.is_prime(2**608-1) 0 Cheating perhaps! Note is_prime will be a probabalistic test for large numbers... -- Nick Craig-Wood -- http://www.craig-wood.com/nick From zzbbaadd at aol.com Fri Sep 28 14:44:06 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 11:44:06 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <1190993122.979034.305060@50g2000hsm.googlegroups.com> <1190997769.002795.59450@57g2000hsv.googlegroups.com> <5m4qc2Fbbk19U1@mid.uni-berlin.de> <1191000394.828693.285210@k79g2000hse.googlegroups.com> <1191002679.569709.16870@22g2000hsm.googlegroups.com> Message-ID: <1191005046.213630.13340@57g2000hsv.googlegroups.com> On Sep 28, 11:21 am, "Francesco Guerrieri" wrote: > On 9/28/07, TheFlyingDutchman wrote: > > > On Sep 28, 10:57 am, Steve Holden wrote: > > > This is like listening to a four-year-old torment its parents with > > > incessant questions. Do you *have* to ask every question that pops into > > > your mind? > > > In this case I asked it as part of the original question and it was > > ignored. I have programmed in C and C++ and a little Pascal many years > > ago. I don't remember anything about Higher Order Functions and would > > like to see exactly how you do it and to verify the contention. > > You could just google for it. Just in case your connection to google > or other similar search engines has been disabled for some reason, > here are some links. > > Try for instance > > http://okmij.org/ftp/c++-digest/Lambda-CPP-more.html#Ex3 > > or > > http://www.cc.gatech.edu/~yannis/fc++/ > > or > > http://www.boost.org/libs/mpl/doc/tutorial/higher-order.html > Correct me if I am wrong, but none of those examples showed something in C++ similar to a decorator in Python - that is, unique syntax in the language for implementing a Higher Order Function. One thing I will say about those examples is that they make Python decorators look sweet! From steve at holdenweb.com Tue Sep 11 18:09:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 18:09:52 -0400 Subject: Difference between two times (working ugly code, needs polish) In-Reply-To: <2dc0c81b0709111420r453ac15av6c7aa19473785080@mail.gmail.com> References: <13ee01cfc7f4be2@corp.supernews.com> <2dc0c81b0709111420r453ac15av6c7aa19473785080@mail.gmail.com> Message-ID: Shawn Milochik wrote: > On 9/11/07, Grant Edwards wrote: >> On 2007-09-11, Shawn Milochik wrote: >> >>> I have done what I wanted, but I think there must be a much better way. >> See the strptime() function in either the time or the datetime >> modules: >> >> http://docs.python.org/lib/module-time.html >> http://docs.python.org/lib/module-datetime.html >> > > > Grant: > > Thanks, this works, and is much shorter. Any further improvements, anyone? > > def isOld(lastUpdate, runTimeStamp): > > oneDay = 60 * 60 * 24 > > lastUpdate = time.mktime(time.strptime(lastUpdate, "%Y-%m-%d_%H:%M")) > runTimeStamp = time.mktime(time.strptime(runTimeStamp, "%Y-%m-%d_%H:%M")) > > return (runTimeStamp - lastUpdate) / oneDay I suppose really oneDay should be a global (i.e. outside the function definition). Apart from that it would be hard to improve on: obvious, easy to read, in short - pythonic. Are you concerned about daylight savings? That could certainly introduce a whole new level of complexity into the problem. Let's hope not ... -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From python at hope.cz Wed Sep 26 01:10:24 2007 From: python at hope.cz (Johny) Date: Tue, 25 Sep 2007 22:10:24 -0700 Subject: HTTPS request In-Reply-To: References: <1190730718.341771.215970@19g2000hsx.googlegroups.com> Message-ID: <1190783424.545615.297540@o80g2000hse.googlegroups.com> On Sep 25, 6:17 pm, Larry Bates wrote: > Johny wrote: > > If I need to log in to a site using https protocol must I use > > certification file and key file? > > The class HTTPSConnection syntax is > > class HTTPSConnection( host[, port, key_file, cert_file]) > > > and I do not know if it is nescessary or not. > > Thanks for help. > > L. > > Depends on what the server requires. You can do basic authenticate to a https: > site if it supports it. > > -Larry Hello Larry, Thanks for your reply. I had to register on this site, so I have Login and Password. I can log in to the site through normal process on the server(by filling in the login form). But I can not login to the site from my Python program. I use the same procedure as I do for other webservers that require login information. The only difference is that the server, this time, is HTTPS server. So I do not know if I must use a SSL certificate or not and if I can use HTTP 1.0 or I must use HTTP 1.1 protocol. Any idea? Thanks L. From gregpinero at gmail.com Wed Sep 5 22:50:01 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Thu, 06 Sep 2007 02:50:01 -0000 Subject: Give List to Format String - How To In-Reply-To: <1189046828.313284.235210@o80g2000hse.googlegroups.com> References: <1189046828.313284.235210@o80g2000hse.googlegroups.com> Message-ID: <1189047001.963262.276790@w3g2000hsg.googlegroups.com> On Sep 5, 10:47 pm, "gregpin... at gmail.com" wrote: > I might just be being dumb tonight, but why doesn't this work: > > >>> '%s aaa %s aa %s' % ['test' for i in range(3)] > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: not enough arguments for format string > Ah it just needs a tuple. I posted too soon I guess. >>> '%s aaa %s aa %s' % tuple(['test' for i in range(3)]) 'test aaa test aa test' -Greg From gnn at neville-neil.com Mon Sep 24 06:30:50 2007 From: gnn at neville-neil.com (George V. Neville-Neil) Date: Mon, 24 Sep 2007 11:30:50 +0100 Subject: Properties and Objects... In-Reply-To: References: Message-ID: At Sun, 23 Sep 2007 19:01:04 -0300, Gabriel Genellina wrote: > > En Sat, 22 Sep 2007 15:06:38 -0300, George V. Neville-Neil > escribi?: > > > I have been trying to switch this over to using properties, which seem > > at first glance to be cleaner, but which I am having a lot of problems > > with. In particular I want to add a property to an object, not a > > class. The field list in a class is actually relatively static but I > > wind up with ugly code like: > > > > class ethernet(pcs.Packet): > > """Ethernet""" > > __layout__ = pcs.Layout() > > _map = ethernet_map.map > > src = pcs.StringField("src", 48) > > dst = pcs.StringField("dst", 48) > > type = pcs.Field("type", 16) > > > > def __init__(self, bytes = None, timestamp = None): > > """initialize an ethernet packet""" > > > > src = pcs.StringField("src", 48) > > dst = pcs.StringField("dst", 48) > > type = pcs.Field("type", 16) > > > > pcs.Packet.__init__(self, [dst, src, type], bytes = bytes) > > self.description = inspect.getdoc(self) > > You don't have to repeat the fields: > > pcs.Packet.__init__(self, [self.dst, self.src, self.type], bytes > = bytes) > Actually that calls the __get__ method of the descriptor, which is not what I want, I need a list of the objects in the layout. > does the same thing. > And you can remove self.description=... and use (at the class level): > description = __doc__ > or: > description = property(lambda self: self.__doc__) > to automatically enable subclases to share the definition Ah, that's very cool, thanks. > One could say that the field order is important so I'd finally write it as: > > class ethernet(pcs.Packet): > """Ethernet""" > __layout__ = pcs.Layout() > _map = ethernet_map.map > src = pcs.StringField("src", 48) > dst = pcs.StringField("dst", 48) > type = pcs.Field("type", 16) > _fields = [dst, src, type] > description = property(lambda self: self.__doc__) > > def __init__(self, bytes = None, timestamp = None): > """initialize an ethernet packet""" > > pcs.Packet.__init__(self, self._fields, bytes = bytes) > > > and assigning the properties at class time means that it's hard to > > have variations, packets with the same name but with slightly varying > > field lists. > > This is the part I don't understand. Can't you define a new class, in case > you want a different field list? Using the above class: > > class ethernet_modified(ethernet): > """Modified ethernet class""" > added_field = pcs.StringField("whatever", 16) > _fields = [dst, src, type, added_field] > > And it doesn't even requiere an __init__ method > Yes, I could and probably should define different objects. > > So, is there a way to assign a property to an object, like this: > > > > def __init__(.... > > self.src = property() > > > > or something like that? > > I'd use different classes for different kind of objects. > > > And, failing that, is there a clean way to modify the class in it's > > __init__() method so I don't have to call the Field objects twice, > > once for the property effect and once to put into the list in the base > > Packet class? > > I think my example above does what you want. Other than the fact that I need the list of Field objects in the layout, and not the values, yes. Of course that's the hard part. Thanks, George From david.barr456 at btinternet.com Thu Sep 6 15:18:24 2007 From: david.barr456 at btinternet.com (David Barr) Date: Thu, 06 Sep 2007 20:18:24 +0100 Subject: Beginners Query - Simple counter problem In-Reply-To: <13e0g0id9rlmg71@corp.supernews.com> References: <13e0g0id9rlmg71@corp.supernews.com> Message-ID: Scott David Daniels wrote: > David Barr wrote: >> I am brand new to Python (this is my second day), and the only >> experience I have with programming was with VBA. Anyway, I'm posting >> this to see if anyone would be kind enough to help me with this (I >> suspect, very easy to solve) query. >> >> The following code is in a file which I am running through the >> interpreter with the execfile command, yet it yeilds no results. I >> appreciate I am obviously doing something really stupid here, but I >> can't find it. Any help appreciated. >> >> >> def d6(i): >> roll = 0 >> count = 0 >> while count <= i: >> roll = roll + random.randint(1,6) >> count += 1 >> >> return roll >> >> print d6(3) > A) your direct answer: by using <=, you are rolling 4 dice, not 3. > B) Much more pythonic: > > import random > > def d6(count): > result = 0 > for die in range(count): > result += random.randint(1, 6) > return result > > -Scott David Daniels > Scott.Daniels at Acm.Org I was surprised by the speed and number of posts. Thanks for the solutions provided! >>> def roll(times=1, sides=6): ... return random.randint(times, times*sides) Although this would probably be quicker than the other approaches, I'm not using the dice to generate numbers per say, I actually want to emulate the rolling of dice, bell-curve (normal distribution) as well as the range. Thanks again, I already like what (very) little I can do in Python and it seems to have a great community too. Cheers, Dave. From alexandre.badez at gmail.com Tue Sep 25 08:08:02 2007 From: alexandre.badez at gmail.com (Alexandre Badez) Date: Tue, 25 Sep 2007 12:08:02 -0000 Subject: Raw string printing Message-ID: <1190722082.406690.222540@57g2000hsv.googlegroups.com> Hy ! I would like to do something like: s = r"a\tb\n" print s # result with a\tb\n print unraw(s) # <= this is the "magic" function I'm searching for # result with a b n Does any of you know how to do it properly ? From BjornSteinarFjeldPettersen at gmail.com Wed Sep 12 06:28:22 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Wed, 12 Sep 2007 10:28:22 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> Message-ID: <1189592902.742636.3910@22g2000hsm.googlegroups.com> On Sep 12, 9:33 am, Mark Summerfield wrote: > I feel that Python lacks one useful data structure: an ordered > dictionary. > > I find such data structures v. useful in C++. I know that in Python > the sort function is v. fast, but often I prefer never to sort but > simply to use an ordered data structure in the first place. > (I'm aware that for ordered lists I can use the bisect module, but I > want an ordered key-value data structure.) [...] > Do other Python programmers feel this lack? Is this worth a PEP? I usually make a distinction between a sorted dict, where iteration (and potentially positional indexing) happens in sorted key order; and an ordered dict where items maintain insertion order. I use the latter all the time, and e.g. Django's model metaclass does some minor magic to overcome the fact that field-order is lost by the time your metaclass gets control, since the attributes are passed as a regular dict. -- bjorn From steve at holdenweb.com Sat Sep 1 03:04:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Sep 2007 03:04:06 -0400 Subject: Automation and scheduling of FrontPage publishing using Python In-Reply-To: References: <1188517723.279932.299400@x40g2000prg.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In message , Steve > Holden wrote: > >> Lawrence D'Oliveiro wrote: >> >>> In message <1188517723.279932.299400 at x40g2000prg.googlegroups.com>, >>> andrew.arobert at gmail.com wrote: >>> >>>> We have numerous web sites which are currently being manually >>>> published via Front Page. >>>> >>>> Doing one or two sites on an ad-hoc basis was not too bad but we are >>>> now over 20 or thirty at set times during a business day. >>> Let me open the bidding by suggesting that you stop using FrontPage. >> But that would mean reprogramming the functionality they now implement >> using FrontPage extensions. Any help with that? > > If they were using FrontPage extensions, they deserve everything they get. While possibly justifiable, given that FrontPage has had holes you could drive a London double-decker but through since time immemorial, it isn't a terribly helpful observation. And they clearly *are* using FrontPage extensions, since the OP states that rsync and RoboCopy leave "the front page extensions and navigation/etc [...] broken". Not everyone reads the literature even well enough to know about well-known problems like FrontPage. Whether such ignorance deserves to be punished by such open-ended retribution is arguable, and I think I'd come down on the "no" side. The only mistake they made was trusting the vendor to provide secure solutions ... [Andrew: sorry to drag you into this discussion - I don't know whether you were aware of FrontPage's security issues or not. If not, you should certainly think about reading up on them]. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From mail at timgolden.me.uk Thu Sep 6 11:57:29 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 06 Sep 2007 16:57:29 +0100 Subject: Finding specific date ranges In-Reply-To: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> Message-ID: <46E02369.6020504@timgolden.me.uk> kyosohma at gmail.com wrote: > Hi, > > I am working on a timesheet application in which I need to to find the > first pay period in a month that is entirely contained in that month > to calculate vacation time. Below are some example date ranges: > > > December 31, 2006 January 13, 2007 # doesn't earn > January 14, 2007 January 27, 2007 # does earn > January 28, 2007 February 10, 2007 # doesn't > February 11, 2007 February 24, 2007 # does > > > So far, the best approach I've come up with is to create a list of > tuples that contain the pay period date ranges for the year and > iterate through the tuples looking for the first occurrence of the > month names matching. Then I'd add that date range to a separate list > and somehow ignore any other matches in that month. This seems like a > hack. Does anyone have a better idea? Well, I can come up with a solution which basically reflects the way I'd do it in SQL (since this kind of thing is my bread-and-butter there) but I'm not convinced it's really any better than your proposal. However, for the purposes of illustration: import calendar import datetime YEAR = 2007 months = [ (datetime.date (YEAR, n, 1), datetime.date (YEAR, n, calendar.monthrange (YEAR, n)[1])) for n in range (1, 13) ] periods = [ (datetime.date(2006, 12, 31), datetime.date(2007, 1, 13)), (datetime.date(2007, 1, 14), datetime.date(2007, 1, 27)), (datetime.date(2007, 1, 28), datetime.date(2007, 2, 10)), (datetime.date(2007, 2, 11), datetime.date(2007, 2, 24)) ] for m in months: candidate_periods = [p for p in periods if m[0] <= p[0] and p[1] <= m[1]] if candidate_periods: print m[0], "=>", min (candidate_periods) else: print m[0], "=>", "no period matches" TJG From liangxuliang79 at gmail.com Thu Sep 6 09:28:50 2007 From: liangxuliang79 at gmail.com (liang xuliang) Date: Thu, 6 Sep 2007 21:28:50 +0800 Subject: ??????urllib post???????????? In-Reply-To: <20070906024041.GA6599@gmail.com> References: <1188993813.330662.174660@w3g2000hsg.googlegroups.com> <20070906024041.GA6599@gmail.com> Message-ID: Can you speak clearly ? I don't know how to do that . Thanks Liang Xuliang 2007/9/6, O.R.Senthil Kumaran : > > If possible, please post your query in ASCII. > > -- > Senthil > > > * liangxuliang79 at gmail.com [2007-09-05 > 05:03:33]: > > > ????www.mmmppp333.com??????????http://ishare.iask.sina.com.cn/cgi-bin/ > > fileid.cgi?fileid=844050 > > ??????post fileid=844050???????? > > > > > ????post????????????fileid=844050??????server??????????header??header????local????location???? > > > ??????????????????????????????????????????????mp3????????????????????????????local????????????mp3?????????????????????????????????? > > ?????????????????????????????? > > > > > ??????????????python??urllib????????urllib???????????????????????local????????????????local????????mp3???????? > > ????????????????mp3.?? > > > > ??post????????/download.php?? > post????????fileid=844050???????????????????????????????????????????????????? > > ????????????????????web?????????????????????? > > -- > > http://mail.python.org/mailman/listinfo/python-list > -- > O.R.Senthil Kumaran > http://uthcode.sarovar.org > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rzantow at gmail.com Sun Sep 2 09:36:45 2007 From: rzantow at gmail.com (rzed) Date: Sun, 02 Sep 2007 13:36:45 +0000 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> Message-ID: jwrweatherley at gmail.com wrote in news:1188733902.513512.87510 at r34g2000hsd.googlegroups.com: > The puzzle is: p is the perimeter of a right angle triangle with > integral length sides, {a,b,c}. which value of p < 1000, is the > number of solutions {a,b,c} maximised? > > Here's my python code: > > #!/usr/local/bin/python > > solutions = [0] * 1001 > p = 0 > > for a in xrange(1, 1000): > for b in xrange(1, 1000 - a): > for c in xrange(1, 1000 - a - b): > p = a + b + c > if p < 1000: > if a ** 2 + b ** 2 == c ** 2: > solutions[p] += 1 > Once p >= 1000, it ain't goin' back. If you break out of the innermost loop here after that happens, you'll save a bunch of time. > max = 0 > maxIndex = 0 > index = 0 > for solution in solutions: > if solution > max: > max = solution > maxIndex = index > index += 1 > > print maxIndex > > > It takes 2 minutes and twelve seconds on a 2.4GHz Core2Duo > MacBook Pro. > [...] > The resulting executable takes 0.24 seconds to run. I'm not > expecting a scripting language to run faster than native code, > but I was surprised at how much slower it was in this case. Any > ideas as to what is causing python so much trouble in the above > code? > From l.oluyede at gmail.com Mon Sep 3 05:06:11 2007 From: l.oluyede at gmail.com (Lawrence Oluyede) Date: Mon, 03 Sep 2007 09:06:11 -0000 Subject: TypeError: 'module object is not callable' In-Reply-To: <1188809299.316203.85930@22g2000hsm.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> Message-ID: <1188810371.354170.298510@w3g2000hsg.googlegroups.com> On Sep 3, 10:48 am, christophert... at hotmail.com wrote: > Hi > > I am new to Python and have recieved this error message when trying to > instantiate an object from a class from another file within the same > directory and wondered what I have done wrong. > > I have a Step.py class: > class Step(object) > def __init__(self, sName): > "Initialise a new Step instance" > self.sName = sName > self.depSteps = [] > self.remDepSteps = [] > self.isCompleted = 0 > > Then I have created a new file within the same directory called > main.py: > > import Step > a = Step("magn") > > The following however generates the error > Traceback (most recent call last): > File "main.py", line 3, in ? > a = Step("magn") > TypeError: 'module' object is not callable This is because when you issue "import Step" you're actually importing the "Step" _module_, not the "Step" class inside the module. You can do this in at least two ways: ------ import Step a = Step.Step("magn") # access the Step class inside Step module ------ or ------ from Step import Step # insert in the current namespace the Step class a = Step("magn") ------ > > If anyone could help point me in the right direction, how to fix this > problem it would be much appreciated. > Chris HTH From marvinware2005 at gmail.com Sat Sep 29 16:32:15 2007 From: marvinware2005 at gmail.com (marvinla) Date: Sat, 29 Sep 2007 13:32:15 -0700 Subject: How to unload a module after I've imported it. In-Reply-To: <1191096194.002683.16240@50g2000hsm.googlegroups.com> References: <1191096194.002683.16240@50g2000hsm.googlegroups.com> Message-ID: <1191097935.819936.148950@50g2000hsm.googlegroups.com> Have you tried a del? >> import socket >> dir() ['__builtins__', '__doc__', '__name__', 'socket'] >> del socket >> dir() ['__builtins__', '__doc__', '__name__'] See you! From rvp74 at ua.fm Sun Sep 16 12:42:37 2007 From: rvp74 at ua.fm (Vadim Radionov) Date: Sun, 16 Sep 2007 19:42:37 +0300 Subject: generate list of partially accumulated values In-Reply-To: <1189936564.932553.148800@50g2000hsm.googlegroups.com> References: <1189936564.932553.148800@50g2000hsm.googlegroups.com> Message-ID: cesco ?????: > Hi, > > I have the following list: > l = [1, 2, 3, 4] > and I'd like to obtain a list like the following: > l_partial_sum = [1, 3, 6, 10] (that is [1, 1+2, 1+2+3, 1+2+3+4]) >>> def iscan(f, seq, acc=0): ... for i in seq: ... acc = f(acc,i) ... yield acc ... >>> list(iscan(operator.add, xrange(1,5))) [1, 3, 6, 10] >>> From bjourne at gmail.com Mon Sep 17 00:44:14 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 17 Sep 2007 06:44:14 +0200 Subject: Needless copying in iterations? In-Reply-To: <13epv3fnb6bak15@corp.supernews.com> References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> <13epv3fnb6bak15@corp.supernews.com> Message-ID: <740c3aec0709162144g21cb44b2i53b1bebff8a42c9d@mail.gmail.com> On 9/16/07, Steven D'Aprano wrote: > Maybe I'm being unfair, but it seems to me that the attitude is similar: > 'there's no point optimizing the common case of printing (say) ints > stored in a list, Just In Case the programmer wants the incredibly rare > case of setting sys.stdout to some wacky object that modifies the list > he's iterating over. It could happen.' Indeed, there is no point in optimizing printing of lists as IO is orders of magnitudes slower than Python. But psyco probably would make a best effort attempt. -- mvh Bj?rn From kay.schluehr at gmx.net Wed Sep 5 16:31:14 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 05 Sep 2007 13:31:14 -0700 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? In-Reply-To: References: <46DEFD2E.5050205@sbcglobal.net> Message-ID: <1189024274.627827.285050@o80g2000hse.googlegroups.com> On Sep 5, 9:59 pm, Ferenczi Viktor wrote: > Class decorators allows clean implementation of properties. > Detailed description:http://www.python.org/dev/peps/pep-3129/ > Lets use a hypothetic library providing properties, for example: > > from property_support import hasProperties, Property > > @hasProperties > class Sphere(object): > def setRadius(self, value): > ... some setter implementation ... > radius=Property(default=1.0, set=setRadius, type=(int, float)) > color=Property(default='black', allowNone=True) > > This is a cleaner syntax if you need automatic default setter/getter > implementations with type checking, default values, etc. I really distaste this "etc." in your description. In the end you promote endless lists of command line parameters to configure every possible function. I also doubt that the solution is more clean but arbitray instead. My own guess why properties are not promoted with more emphasis is that they lead to cargo cult programming i.e. everyone starts to use property syntax even when usual attributes are sufficient. So the syntax might even be intentionally ugly. From freesoftwareweb at gmail.com Tue Sep 18 15:02:20 2007 From: freesoftwareweb at gmail.com (freesoftwareweb at gmail.com) Date: Tue, 18 Sep 2007 12:02:20 -0700 Subject: Free software!!!! Message-ID: <1190142140.116407.25240@n39g2000hsh.googlegroups.com> http://freesoftwareupgrades.blogspot.com/ From spam.noam at gmail.com Mon Sep 17 19:14:56 2007 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: Mon, 17 Sep 2007 23:14:56 -0000 Subject: How can I know how much to read from a subprocess Message-ID: <1190070896.332844.23080@22g2000hsm.googlegroups.com> Hello, I want to write a terminal program in pygtk. It will run a subprocess, display everything it writes in its standard output and standard error, and let the user write text into its standard input. The question is, how can I know if the process wrote something to its output, and how much it wrote? I can't just call read(), since it will block my process. Thanks, Noam From toby at tobiah.org Thu Sep 20 16:12:08 2007 From: toby at tobiah.org (Tobiah) Date: Thu, 20 Sep 2007 13:12:08 -0700 Subject: Python Regex Question In-Reply-To: <1190316811.760038.145850@50g2000hsm.googlegroups.com> References: <1190316811.760038.145850@50g2000hsm.googlegroups.com> Message-ID: <46f2c7e8$0$21956$88260bb3@free.teranews.com> joemystery123 at gmail.com wrote: > I need to extract the number on each > i.e 49.950 from the following: > >  49.950  > > The actual number between:  49.950  can be any number of > digits before decimal and after decimal. > >  ######.####  > > How can I just extract the real/integer number using regex? > '[0-9]*\.[0-9]*' -- Posted via a free Usenet account from http://www.teranews.com From wizzardx at gmail.com Sat Sep 8 17:25:17 2007 From: wizzardx at gmail.com (David) Date: Sat, 8 Sep 2007 23:25:17 +0200 Subject: Parsing nested constructs In-Reply-To: <46e308d3$0$9153$426a74cc@news.free.fr> References: <46e308d3$0$9153$426a74cc@news.free.fr> Message-ID: <18c1e6480709081425v162d7fa4r8e91d66d3fb7dc@mail.gmail.com> On 9/8/07, tool69 wrote: > Hi, > > I need to parse some source with nested parenthesis, like this : > If this is exactly how your data looks, then how about a loop which searches for "{item" and the following "}"? You can use the "find" string method for that. Otherwise, if the items don't look exactly like "{item", but the formatting is otherwise exactly the same as above, then look for lines that have both "{" and "}" on them, then get the string between them. Otherwise, if { and } and the item aren't always on the same line, then go through the string character by character, keep track of when you encounter "{" and "}". When you encounter a "}" and there was a "{" before (ie, not a "}"), then get the string between the "{" and the "}" From steve at REMOVE-THIS-cybersource.com.au Mon Sep 10 19:02:52 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 10 Sep 2007 23:02:52 -0000 Subject: How do I read and write to the same CSV file References: <1189434466.001109.313060@d55g2000hsg.googlegroups.com> <13ean2c2ip6i153@corp.supernews.com> Message-ID: <13ebj8skp1fracf@corp.supernews.com> On Mon, 10 Sep 2007 15:01:32 +0000, Steven D'Aprano wrote: > But if you insist... you might be able to use cf_stream.seek() to move > to the current position in the file, then write the bytes you want. How > do you find the current position? Black magic or voodoo might help. Well, that'll learn me to post at ungodly hours of the morning. Getting the _current_ position is easy, what I meant to write was CORRECT position. Twice. How embarrassment. -- Steven. From Michael.J.Fromberger at Clothing.Dartmouth.EDU Mon Sep 24 09:08:43 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Mon, 24 Sep 2007 09:08:43 -0400 Subject: sorting a list numbers stored as strings References: <1190632366.863711.100680@y42g2000hsy.googlegroups.com> Message-ID: In article <1190632366.863711.100680 at y42g2000hsy.googlegroups.com>, aine_canby at yahoo.com wrote: > hi, > > I have the following list - > > ["1", "11", "2", "22"] > > how do I sort it like this - > > ["1", "2", "11", "22"] > > thanks, > > aine Try: lst.sort(key = lambda s: int(s)) Assuming, of course, that "lst" is your original list; this will sort it in place. Also, you should probably read about the "sorted" function here: Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From tjreedy at udel.edu Wed Sep 5 15:43:38 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Sep 2007 15:43:38 -0400 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? References: <46DEFD2E.5050205@sbcglobal.net> Message-ID: "Kenneth McDonald" wrote in message news:46DEFD2E.5050205 at sbcglobal.net... | The reading I've done so far on Python 3 (alpha announcement, meta-PEP, | some other PEPs) is generally encouraging, but there doesn't seem to be | much on cleaning up the syntax, I believe that the syntax changes in 3.0.a0 are pretty much what will be in 3.0. | Finally, another thing I've perhaps missed, but I can't see anything in | what I've gone through, about correcting of of what I see to be one of | Python's most long-standing really serious flaws, which is the lack of | an official standard documentation markup syntax for writing | documentation in code. This isn't even a matter of getting something | developed, it's simply a matter of Guido and the Powers That Be | bestowing their benediction on one of the several adequate or better | documentation toolsets out there, so that more of us (slowly) start | using it. Eventually this will result in work on the toolset itself, | more people will be willing to use it, and there'll be a nice virtuous | circle. Except for the core language, Guido generally avoids trying to pick and impose winners (as opposed to recognizing winners). So, as far as I know, he never 'pronounced' on PEP 287. On the other hand, its author volunteered as a PEP editor and posted PEP12. And for 2.6, the doc sources have been converted, I understand, from Latex to .rst due to work led by (and mostly done by?) G. Brandl (who is still working on the toolset). So consider that a 'benediction' if you wish. tjr From mickey at disney.com Wed Sep 12 16:31:23 2007 From: mickey at disney.com (Wiseman) Date: Wed, 12 Sep 2007 16:31:23 -0400 Subject: Python Problem References: <5kpj30F4s6gmU1@mid.uni-berlin.de> Message-ID: Marc, Thank you. I followed the instructions in given at pyenchant.sourceforge.net and got the application to work. ((;-)) Meir PS: My challenge now is to port the application to Redhat. I already know that Redhat is missing the pyenchant package - I hope the same installation process will solve the problem. It also missing "threading" and this will be the story for another day. I'll appreciate any hint from anyone who've already solved such a problem M ---------------------------------------------------------------- On 12 Sep 2007 07:33:52 GMT, Marc 'BlackJack' Rintsch wrote: >On Wed, 12 Sep 2007 09:09:02 +0200, A.T.Hofkamp wrote: > >> On 2007-09-11, Wiseman wrote: >>> >>> Hi, >>> >>> OK - it works in WindowsXP. >>> I installed "enchant" on my SuSE 10.0 (using YAST). >>> The enchant Suse package looks like a general Linux package, not a >>> Python specific. >> >> You'd seem to be right judging by this web-page: >> http://www.novell.com/products/linuxpackages/suselinux/enchant.html >> >> As you can see, there is no file installed at a path with "python" in it. >> >>> What am I missing? >> >> Python bindings to the library perhaps? >> You may be more lucky with an enchant-dev package (if it exists). I am however >> not a Suse user and not an echant user (well, not from my Python code at least). > >PyEnchant seems to be an independent project: > > http://pyenchant.sourceforge.net/ > >So there is either an extra package for SuSE or the OP has to build it >himself. > >Ciao, > Marc 'BlackJack' Rintsch From xkenneth at gmail.com Fri Sep 28 13:36:54 2007 From: xkenneth at gmail.com (xkenneth) Date: Fri, 28 Sep 2007 17:36:54 -0000 Subject: Can I overload the compare (cmp()) function for a Lists ([]) index function? In-Reply-To: <1191000652.430036.288400@y42g2000hsy.googlegroups.com> References: <1191000652.430036.288400@y42g2000hsy.googlegroups.com> Message-ID: <1191001014.951696.285800@50g2000hsm.googlegroups.com> On Sep 28, 12:30 pm, xkenneth wrote: > Looking to do something similair. I'm working with alot of timestamps > and if they're within a couple seconds I need them to be indexed and > removed from a list. > Is there any possible way to index with a custom cmp() function? > > I assume it would be something like... > > list.index(something,mycmp) > > Thanks! or can i just say.... list.index.__cmp__ = mycmp and do it that way? I just want to make sure I'm not doing anything evil. From gslindstrom at gmail.com Sat Sep 1 20:52:51 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sat, 1 Sep 2007 19:52:51 -0500 Subject: PyCon 2008 - Call for Tutorial Topics Message-ID: Hello All, We are still soliciting ideas for tutorials to put on at PyCon in Chicago next spring. PyCon is all about our community; under the direction of the PSF, planned, organized and run by volunteers just like you. We are asking for topics that you want to see covered on the tutorial day (the day preceding the "official" conference). There is an additional charge for these classes but they are taught by instructors who really know their topics. The following ideas have been requested (nothing has been scheduled, yet): - Testing strategies - Intermediate Python - Database - How to "think" in Python 3000 - Using Cheeseshop - SOAP/.Net (Iron Python?) - Programming Contest We need more ideas before we start putting things together. What do *you* want to see? This is your chance to learn from the experts (or, maybe, *you* would like to present a class). Let me know what class would entice you to attend the tutorials. Greg Lindstrom Tutorial Coordinator, PyCon 2008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at 23342.om Thu Sep 13 01:20:36 2007 From: nospam at 23342.om (Amit N) Date: Thu, 13 Sep 2007 01:20:36 -0400 Subject: Parallel/Multiprocessing script design question Message-ID: Hi guys, I tend to ramble, and I am afraid none of you busy experts will bother reading my long post, so I will try to summarize it first: 1. I have a script that processes ~10GB of data daily, and runs for a long time that I need to parallelize on a multicpu/multicore system. I am trying to decide on a module/toolkit that would help me create a multiprocessing solution but there are so many of them that I can't decide what to use. I am looking for a cross platform solution. Although right now it has to work in windows first, so many of the fork based modules are out. I am hoping people with experience using any of these would chime in with tips. The main thing I would look for in a toolkit is maturity and no extra dependencies. Plus a wide user community is always good. POSH/parallelpython/mpi4py/pyPar/Kamaelia/Twisted I am so confused :( 2. The processing involves multiple steps that each input file has to go through. I am trying to decide between a batch mode design and a pipelined design for concurrency. In the batched design, all files will be processed on one processing step(in parallel) before the next step is started. In a pipelined design, each file will be taken through all steps to the end. So multiple files will be in parallel pipelines at the same time. I can't decide which is better. I guess I am asking for experienced eyes to take a look at the alternatives, for things that I, making my very first concurrent design, won't see. DETAILS: I have been trying to choose a design for this project but am striken by my usual case of analysis paralysis. I had decided to learn Python about 3 weeks ago specifically for this project, as it needed parsing and text processing, not realizing that I would need concurrency. I am having the same trouble in deciding which parser generator to use, but I will ask about parsing in a separate thread to keep this focused. It was slow, so I tried to run a multithreaded version, naively expecting a 2x speedup. I barely got a 5% improvement and only then learned about the GIL. I guess I still haven't got too much time invested in this, so I can still switch to another language. I am not sure which other scripting languages have real multithreading? Perl? But I had chosen Python over Perl for readability and maintainability and am not ready to give that up yet. I know about stackless/Ironpython/Jython but I want to stick to CPython. So I am going to try to figure this out. Even after deciding to go for a SMP solution, I still don't know which toolkit to use. The subprocess module should allow spawning new processes, but I am not sure how to get status/error codes back from those? I guess this is why people made those parallel processing modules that might help by taking care of these things. I think my application is fairly simple and should be easy to SMP. THE TASK: About 800+ 10-15MB files are generated daily that need to be processed. The processing consists of different steps that the files must go through: -Uncompress -FilterA -FilterB -Parse -Possibly compress parsed files for archival All files have to be run through each of the two filters. The two filters are independent of each other and produce output files that need separate parsers. So they can in fact run in parallel, and so can the subsequent parsers. Furthermore, multiple files can be running in parallel inside each step. Eg. 4 files being uncompressed at the same time. I am using the python library for uncompressing and will be doing the parsing in Python too. But the two filters are external console programs that I spawn in the system shell with subprocess.call(). I guess I can forget about communicating with those? The first method that came to mind was to finish each step on all files before going to the next. So all files are uncompressed first, using multiple processes in parallel. Then all files are filtered in parallel, etc. I guess I would need some sort of queuing system here, to submit files to the CPUs properly? The other way could be to have each individual file run through all the steps and have multiple such "pipelines" running simultaneously in parallel. It feels like this method will lose cache performance because all the code for all the steps will be loaded at the same time, but I am not sure if I should be worrying about that. This will have the advantage of "Fast First-Out" which means that something waiting for the results of processing won't have to wait till the very end. They can start receiving data incrementally from the start(kind of streaming?). Pipelined mode may also help to rerun an individual file quickly in case it had an error. So whats the better method? EVALUATIONS: POSH - Doesn't seem mature, was supposed to be proof of concept only. People have reported Bugs/Problems using it. POSIX Only. delegate/forkmap/pprocess - fork based, POSIX only ParallelPython - Seems to meet all criteria, and is cross platform. I will be trying this one first. remoteD - Claims to be platform independent, but I don't think so. Code shows os.fork only. Last updated 2004 v0.8 processing - Is in beta V0.33 but looks promising and is cross platform. Emulates processes as threads. http://www.python.org/pypi/processing MPI based modules(probably overkill for my application): pyPar - Mature, cross platform. Has a dependency on Numeric Python + needs a C compiler. pyMpi - POSIX only . Alpha status. From lawrence livermore labs. It modifies the interpreter itself to make it multi-noded. mpi4py - ? another MPI implementation. LINKS & DISCUSSIONS http://wiki.python.org/moin/ParallelProcessing http://blog.ianbicking.org/gil-of-doom.html http://www.usenix.org/events/hotos03/tech/full_papers/vonbehren/vonbehren_html/index.html http://groups.google.com/group/comp.lang.python/browse_thread/thread/1f5d927d34f8f323/ http://groups.google.com/group/comp.lang.python/browse_frm/thread/332083cdc8bc44b/ http://groups.google.com/group/comp.lang.python/browse_frm/thread/13da24f2d6dc24a9/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/f822ec289f30b26a/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/902dbddfc31b8891 http://groups.google.com/group/comp.lang.python/browse_thread/thread/d8fa9ad770c17c70/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Sep 7 07:10:46 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 07 Sep 2007 13:10:46 +0200 Subject: So what exactly is a complex number? References: <451mq4-les.ln1@ozzie.tundraware.com> <5k86hqF2if1hU1@mid.individual.net> Message-ID: <5kcptmF32f64U1@mid.individual.net> Grzegorz S?odkowicz wrote: > Interesting. It appears that we are ran into a mathematical > cultural difference. Were I come from vectors *are* defined as > having four properties that I enumerated. After some research I > found that English sources (Wikipedia) indeed give the definition > you supplied. Indeed, interesting. > However, given the following problem: (assuming 2-d Cartesian > coordinate system and gravity acting 'downwards') "There are 3 > point masses: 2 kg at (0, 0), 1 kg at (5, 4) and 4 kg at (2, 2). > The acting forces are given as vectors: [2, 2] [1, 1]. Find the > trajectories of all point masses." how would you propose to solve > it without knowing where the forces are applied? I didn't say that you must not know the point of application, but I said that it was not a property of the vector itself. It is true, however, that in physical calculations you should not "mix" many types of vectors (like force) that are, in the experiment, applied to different points of application. > Again, I think we were given different definitions. Mine states > that direction is 'the line on which the vector lies', sense is > the 'arrow' and magnitude is the 'length' (thus non-negative). The > definition is separate from mathematical description (which can be > '[1 1] applied at (0, 0)' or 'sqrt(2) at 45 deg applied at (0, 0)' > or any other that is unambiguous). Oh, I thought we were talking about quite mathematical vectors? In physics, I learned that a vector is only what transforms like a vector. >> Represent the direction as one number? Only in a one-dimensional >> space. > > No. In one-dimensional 'space' direction is a ? quantity (a > 'sense'). In 2-d it can be given as an angle. Indeed, you're right. So, those vectors have different properties depending on the used coordinate system? I myself prefer the concise definition ... Regards, Bj?rn -- BOFH excuse #128: Power Company having EMP problems with their reactor From wolf_tracks at invalid.com Thu Sep 20 13:04:20 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 20 Sep 2007 17:04:20 GMT Subject: An Editor that Skips to the End of a Def In-Reply-To: <87odfxjn16.fsf@rudin.co.uk> References: <87odfxjn16.fsf@rudin.co.uk> Message-ID: Thanks, but no thanks. The learning curve is way too steep. Paul Rudin wrote: > "W. Watson" writes: > >> Is there an editor that allows one to position to put the cursor and >> then by pushing some button goes to the end of the def? > > C-M-e in emacs/python-mode. -- Wayne Watson (Nevada City, CA) Web Page: From rainwatching at gmail.com Sat Sep 1 11:51:37 2007 From: rainwatching at gmail.com (=?iso-8859-1?q?S=F6nmez_Kartal?=) Date: Sat, 01 Sep 2007 15:51:37 -0000 Subject: reload(sys) In-Reply-To: <5jql4rFh543U4@mid.uni-berlin.de> References: <1188521143.421431.119100@l22g2000prc.googlegroups.com> <1188564816.430863.219560@w3g2000hsg.googlegroups.com> <5jql4rFh543U4@mid.uni-berlin.de> Message-ID: <1188661897.795595.165590@k79g2000hse.googlegroups.com> On 31 A ustos, 16:58, Marc 'BlackJack' Rintsch wrote: > On Fri, 31 Aug 2007 12:53:36 +0000, S?nmez Kartal wrote: > > On 31 A ustos, 04:24, Steven Bethard wrote: > >> Snmez Kartal wrote: > >> > I've had an encoding issue and solved it by > >> > "sys.setdefaultencoding('utf-8')"... > > >> > My first try wasn't successful since setdefaultencoding is not named > >> > when I imported sys module. After, I import sys module, I needed to > >> > write "reload(sys)" also. > > >> > I wonder why we need to call "reload(sys)" to get setdefaultencoding > >> > named? > > >> sys.setdefaultencoding is purposely deleted from the sys module after > >> it's loaded because you really shouldn't be using it. The reload() call > >> restores the deleted attribute. > > >> If you'd like a less brittle solution to your encoding issue, explain > >> what the issue was, and people here can probably help you find a better > >> solution. > > > I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as > > "f.write(str(xml))". At execution of that line, it gives error with > > description, configure your default encoding... > > This doesn't help us that much. What is `f` here and what is `xml`? > > > This is the part of xmlbuilder.py which raises the error. > > > try: > > if self.pretty: > > # tabs are evil, so we will use two spaces > > outstr = self._dom.toprettyxml(" > > ",encoding=self.encoding) > > else: > > outstr = self._dom.toxml(encoding=self.encoding) > > except UnicodeDecodeError: > > sys.stderr.write('Decoding Error: You must configure > > default encoding\n') > > sys.exit() > > So there is an attribute `self.encoding` on that object. Is it set? What > encoding is it? And do you put byte strings with values outside ASCII > into your XML or unicode strings? > > Ciao, > Marc 'BlackJack' Rintsch I should have said that 'f' is a file object and xml is a XMLBuilder object. Sorry. :-) self.encoding is 'utf-8' by default. I have only ? and ? characters in the XML file and a space character which Emacs shows as colored '_'. I have replaced those but didn't work! Here is the full code of xmlbuilder.py: http://rafb.net/p/9rURi822.html I don't wanna bother you but if you see there is something not practical then I'll keep writing about this. :-) From horpner at yahoo.com Thu Sep 27 09:24:54 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 27 Sep 2007 13:24:54 GMT Subject: What is a good way of having several versions of a python module installed in parallell? References: <5ls95aF9pq3gU1@mid.uni-berlin.de> Message-ID: On 2007-09-25, Joel Hedlund wrote: > First of all, thanks for all the input - it's appreciated. > >> Otherwise, three words: >> >> test driven development > > Do you also do this for all the little stuff, the small hacks > you just whip together to get a particular task done? My > impression is that doing proper unittests adds a lot of time to > development, and I'm thinking that this may be a low return > investment for the small programs. For documentating and testing small hacks, try the doctest module. It integrates with Python's unit testing modules, so if you need to "graduate", it is simple to do so. -- Neil Cerutti From paddy3118 at googlemail.com Fri Sep 7 03:01:08 2007 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 07 Sep 2007 07:01:08 -0000 Subject: Text processing and file creation In-Reply-To: <1189133439.559915.233350@19g2000hsx.googlegroups.com> References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> <1189024097.175349.221210@w3g2000hsg.googlegroups.com> <1189027060.889829.282510@r34g2000hsd.googlegroups.com> <1189133439.559915.233350@19g2000hsx.googlegroups.com> Message-ID: <1189148468.577147.133510@22g2000hsm.googlegroups.com> On Sep 7, 3:50 am, George Sakkis wrote: > On Sep 5, 5:17 pm, "malibus... at gmail.com" > wrote: > If this was a code golf challenge, I'd choose the Unix split solution and be both maintainable as well as concise :-) - Paddy. From __peter__ at web.de Fri Sep 21 04:41:42 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Sep 2007 10:41:42 +0200 Subject: Tapping into the access of an int instance References: Message-ID: Tor Erik S?nvisen wrote: > Does anyone know how to interrupt the lookup of an integer value? I > know I need to subclass int, since builtin types can't be altered > directly... > > Below is how far I've come... What I want is to tap into the access of > instance i's value 1... > >>>> class Int(int): > def __init__(self, *a, **k): > super(Int, self).__init__(self, *a, **k) > > >>>> i = Int(1) >>>> i > 1 You may be looking for __new__() which is invoked before an object is created. This is particular useful for immutables like int. >>> lookup = {} >>> class Int(int): ... def __new__(cls, value, *more): ... if not more: ... try: ... return lookup[value] ... except KeyError: ... pass ... return int.__new__(cls, value, *more) ... >>> lookup["answer"] = Int(42) >>> Int("answer") 42 >>> type(_) Peter From fred.sells at adventistcare.org Fri Sep 14 10:40:27 2007 From: fred.sells at adventistcare.org (Sells, Fred) Date: Fri, 14 Sep 2007 10:40:27 -0400 Subject: How to Start In-Reply-To: Message-ID: <0A53725C4A497848A7B3A0874B2598313D389C@acesxch01.ADVENTISTCORP.NET> I like eclipse+pydev; although I did pay my dues learning the basics of eclipse. F9 saves file and runs it. If you're an emacs dude, emacs + python mode is pretty good. ctrl-c ctrl-c runs the active buffer. Of course if you don't already know emacs, avoid it like the plague. > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of Michael R. Copeland > Sent: Thursday, September 13, 2007 6:00 PM > To: python-list at python.org > Subject: How to Start > > > I've decided that Python is a language/environment I'd > like to learn > (I've been a professional programmer for 45+ years), but I > really don't > know where and how to start! I have a number of books - and > am buying > some more - but because of the bewildering number of after-market > packages, environments, and add-ons, I am really quite > perplexed about > starting. 8<{{ > Yes, I could fire up the interactive mode and play with some > statements...but I consider that sort of thing for > programming neophytes > or experimenting with specific issues. First, I want to develop a > simple Windows application, and because of the plethora of > "stuff" the > Python world offers, I don't know where to begin. > For example, what basic, easy-to-use interface might I > start with to > build a simple text file parsing and analysis program? That is, I'd > like to start with a simple Windows shell that prompts for a > file name, > processes it, and then displays some result. > I am certainly impressed with the apparent experience and > openness of > the regular players here, but the discussions here (and in > c.l.p.announce) truly presume knowledge and experience with Python I > don't yet have. Yes, for even a very experienced programmer, > entering > the Python world is very daunting - but I want to get started. > Please advise. TIA > -- > http://mail.python.org/mailman/listinfo/python-list > From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 18 04:16:02 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 10:16:02 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@1 <46ee2d9d$0$26213$426a74cc@news.free.fr> Message-ID: <46ef893c$0$21882$426a34cc@news.free.fr> Aahz a ?crit : > In article <46ee2d9d$0$26213$426a74cc at news.free.fr>, > Bruno Desthuilliers wrote: >> But what, given that I'm an AOL user still thinking it's kewl to hide >> behind a pseudo, what else would you expect ? > > What exactly is a "pseudo", pray tell? Sorry : a pseudonym (a nickname). From zentraders at gmail.com Fri Sep 14 10:49:11 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 14 Sep 2007 07:49:11 -0700 Subject: subclass of integers In-Reply-To: <1189780201.692192.291010@k79g2000hse.googlegroups.com> References: <1189780201.692192.291010@k79g2000hse.googlegroups.com> Message-ID: <1189781351.120047.281620@d55g2000hsg.googlegroups.com> I would do something along the lines of the following, although it only tests for integers and not floats, so would return 'None' for a float. class Nint(int): def __add__(self, x, y): if isinstance(x, int) and isinstance(y, int): return x+y return None if __name__=='__main__': N=Nint() print N.__add__( 1, 2 ) print N.__add__( 1, None ) From paddy3118 at googlemail.com Mon Sep 17 17:21:27 2007 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 17 Sep 2007 14:21:27 -0700 Subject: How to assign a function to another function In-Reply-To: References: <87d4whnsnd.fsf@rudin.co.uk> Message-ID: <1190064087.028773.6910@o80g2000hse.googlegroups.com> On Sep 17, 6:11 pm, Stefano Esposito wrote: > On Mon, 17 Sep 2007 17:49:58 +0100 > > > > Paul Rudin wrote: > > Stefano Esposito writes: > > > > Hi all > > > > what i'm trying to do is this: > > > >>>>def foo (): > > > ... return None > > > ... > > >>>>def bar (): > > > ... print "called bar" > > > ... > > >>>>def assigner (): > > > ... foo = bar > > > ... > > >>>>assigner() > > >>>>foo() > > > called bar > > > > This piece of code is not working and even trying with... > > > > ... How can I achieve my goal? > > > By adding the line: > > global foo > > at the beginning of the body of assigner. > > This worked, thanks a lot :) > > -- > Stefano Esposito I got this explained to me awhile back and blogged on it here: http://paddy3118.blogspot.com/2006/07/python-functions-assignments-and-scope.html - Paddy. From steve at holdenweb.com Tue Sep 11 08:32:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 08:32:37 -0400 Subject: newbie: stani's python editor if-else In-Reply-To: <1189484688.520933.25000@22g2000hsm.googlegroups.com> References: <1189484688.520933.25000@22g2000hsm.googlegroups.com> Message-ID: madzientist wrote: > hi, > > two quick questions: > > a) i am using SPE (latest version) and for some reason, when i type, > say > > if 1==2: > print "not equal" > else: > print "equal" > > the else is at the same indentation level as the preceding print > statement, and i get a syntax error > > why doesn't spe automatically put the else at the level of the if > statement ? what am i dong wrong ? once i manually change the > indentation, the code snippet runs perfectly. > > b) if this is not the group for such elementary questions, please do > let me know. > > thanks !!!! > > suresh > The point here is that SPE isn't analyzing your source in sufficient detail to recognize the need to "outdent" the else statement. Clearly there could be any number of statements at the same indent level as the first print statement. For the record this is not a behavior restricted to SPE, but also occurs in Wing IDE, PythonWin and Scite, for starters. Technically you are correct in the example you give: an IDE could decide to remove one level of indentation, but of course there's always the "dangling else" problem: if one "if" statement is nested inside another one, which indentation level would be appropriate for an "else"? Generally speaking, only the programmer can know, and so generally you are left to enforce these issues for yourself. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bignose+hates-spam at benfinney.id.au Mon Sep 10 20:18:11 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 11 Sep 2007 10:18:11 +1000 Subject: Enum class with ToString functionality References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> Message-ID: <87bqca9hrw.fsf@benfinney.id.au> bg_ie at yahoo.com writes: > But it would be much nicer if I had a function to covert to string > as part of the TestOutcomes class. How would I implement this? Others have given ad hoc implementations that may do what you want. I'd like to know if the Cheeseshop package 'enum' is useful to you. Any constructive feedback would be appreciated. -- \ "Remorse: Regret that one waited so long to do it." -- Henry | `\ L. Mencken | _o__) | Ben Finney From dborne at gmail.com Fri Sep 21 10:13:51 2007 From: dborne at gmail.com (Dave Borne) Date: Fri, 21 Sep 2007 09:13:51 -0500 Subject: SHOCK: WHY None? In-Reply-To: <1190383137.015553.235870@o80g2000hse.googlegroups.com> References: <1190383137.015553.235870@o80g2000hse.googlegroups.com> Message-ID: <6e42ec490709210713t61334cfbk10496206601c9d2f@mail.gmail.com> > else: > f(i+1,sm+a[i]) Maybe because you are ignoring the return value of the when you recurse... try this else: return f(i+1, sm+a[i]) -Dave From arnodel at googlemail.com Sun Sep 9 05:30:00 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 09 Sep 2007 02:30:00 -0700 Subject: unexpected behavior: did i create a pointer? In-Reply-To: <13e4rno5qal6h4b@corp.supernews.com> References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <13e2jdobu2kqkf1@corp.supernews.com> <13e4rno5qal6h4b@corp.supernews.com> Message-ID: <1189330200.935267.107970@19g2000hsx.googlegroups.com> On Sep 8, 10:44 am, Steven D'Aprano wrote: [...] > Ways that Python objects are like pointers: > > (1) ... um... > > Oh yeah, if you bind the _same_ object to two different names, _and_ the > object is mutable (but not if it is immutable), mutating the object via > one name will have the same effect on the object -- the same object, > naturally -- bound to the other name. Well one of the main uses of pointers in C is as things that *point to* objects. And AFAIK that's exactly what a name is in Python. In fact I think to say that a name points to (or refers to) an object is less misleading that to say it is bound to. Binding implies some sort of symmetry but when I write: a = "Am I bound?" The name a knows it's refering to the string object, whereas the string has no idea who refers to it (well an implementation might want to store this information, but it is inaccessible). > You know, maybe because I came to Python with no C experience, I never > had trouble with the "unexpected behaviour" that so confused the original > poster. It's just obvious. The funny thing is that if the OP had thought of both 'a' and 'copyOfA' as C-like pointers then he wouldn't have been confused :) -- Arnaud From arnodel at googlemail.com Thu Sep 6 13:55:06 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 06 Sep 2007 10:55:06 -0700 Subject: Help setting default class attributes In-Reply-To: <1189099594.432512.278950@22g2000hsm.googlegroups.com> References: <1189099594.432512.278950@22g2000hsm.googlegroups.com> Message-ID: <1189101306.620588.89140@r29g2000hsg.googlegroups.com> On Sep 6, 6:26 pm, rh0dium wrote: > Hi all, > > I have the following piece of code and I wanted to set the default > attributes based on a dictionary. What I am looking for is a way to > take PIPODEFAULTS and assign each one as an attribute for the class > pipo. Can someone show me how to do this by iterating over the > PIPODEFAULTS and assign them. What I would expect to be able to do is > call the class and modify them. Use the setattr(...) function. > example: > a = pipo() > print a.caseSensitivity > "preserve" > > a.caseSensitivity = "lower" > print a.caseSensitivity > "lower" > > Lastly - here is my code: > > class pipo: > > PIPODEFAULTS={ "caseSensitivity" : "preserve","cellMapTable" : > "","checkPolygon" : "nil","compression" : "none", > "convertDot" : "ignore","convertPathToPoly" : > "nil","convertToGeo" : "nil","dumpPcellInfo" : "nil", > "snapToGrid" : "nil","techFileChoice" : > "nil","units": "micron","useParentXYforText" : "nil","viewName" : > "layout", > } > > def __init__(self, *args, **kwargs): > """This simply will run a PIPO stream out > """ > # Setup Logging > self.pipoargs=self.setdefaults() > def setdefaults(self): > for x in self.PIPODEFAULTS: > self.log.debug("Setting %s to %s" % (x, > self.PIPODEFAULTS[x])) def setdefaults(self): for key, val in self.PIPODEFAULTS.iteritems(): setattr(self, key, val) OR (but I prefer the one above) def setdefaults(self): self.__dict__.update(self.PIPODEFAULTS) -- Arnaud From kyosohma at gmail.com Thu Sep 27 09:27:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 27 Sep 2007 13:27:54 -0000 Subject: Cross-platform time out decorator In-Reply-To: <1190802115.585306.250400@o80g2000hse.googlegroups.com> References: <1190802115.585306.250400@o80g2000hse.googlegroups.com> Message-ID: <1190899674.049695.103430@22g2000hsm.googlegroups.com> On Sep 26, 5:21 am, Joel wrote: > I've been using this nice timing out decorator :http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871. The > problem is that since it relies on sigalarm, it doesn't work under > windows. Would anyone know how to do a cross-platform version? > > Thanks a lot! > > joel You might be able to use the timeit module. http://docs.python.org/lib/module-timeit.html Some people like to use hotshot: http://www.onlamp.com/pub/a/python/2005/12/15/profiling.html I doubt this is what you're looking for, but maybe it'll give you a push in the right direction. Mike From zzbbaadd at aol.com Thu Sep 13 18:19:27 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 13 Sep 2007 15:19:27 -0700 Subject: How to Start In-Reply-To: References: Message-ID: <1189721967.547833.185650@57g2000hsv.googlegroups.com> On Sep 13, 2:59 pm, mrc2... at cox.net (Michael R. Copeland) wrote: > I've decided that Python is a language/environment I'd like to learn > (I've been a professional programmer for 45+ years), but I really don't > know where and how to start! I have a number of books - and am buying > some more - but because of the bewildering number of after-market > packages, environments, and add-ons, I am really quite perplexed about > starting. 8<{{ > Yes, I could fire up the interactive mode and play with some > statements...but I consider that sort of thing for programming neophytes > or experimenting with specific issues. First, I want to develop a > simple Windows application, and because of the plethora of "stuff" the > Python world offers, I don't know where to begin. > For example, what basic, easy-to-use interface might I start with to > build a simple text file parsing and analysis program? That is, I'd > like to start with a simple Windows shell that prompts for a file name, > processes it, and then displays some result. > I am certainly impressed with the apparent experience and openness of > the regular players here, but the discussions here (and in > c.l.p.announce) truly presume knowledge and experience with Python I > don't yet have. Yes, for even a very experienced programmer, entering > the Python world is very daunting - but I want to get started. > Please advise. TIA I like Wing IDE ( http://www.wingware.com ) . They have a free version and Personal and Professional versions. The free version description says: "Wing IDE 101 Wing IDE 101 is a free basic edition of Wing IDE that was originally designed with the University of Toronto Computer Science Department for teaching entry level computer science courses. It is not open source but is free for use by educators, students, and hobbyists. Note that Wing IDE 101 omits auto-completion and most other code intelligence features in the other Wing IDE products. This was by design, so that students are more conscious of the details of the language and modules they are learning about." From steve at holdenweb.com Mon Sep 24 22:30:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Sep 2007 22:30:31 -0400 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> Message-ID: Robert Dailey wrote: > > > On 9/24/07, *Gabriel Genellina* > wrote: > > Yes: forget about regular expressions. ElementTree does that for free: > > > That's not an option. > Even though it's built into Python 2.5? That's a strange requirement. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From stefan.behnel-n05pAM at web.de Wed Sep 12 08:17:28 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 12 Sep 2007 14:17:28 +0200 Subject: Generating HTML In-Reply-To: References: Message-ID: <46E7D8D8.8060402@web.de> Sebastian Bassi wrote: > What are people using these days to generate HTML? I still use > HTMLgen, but I want to know if there are new options. I don't > want/need a web-framework a la Zope, just want to produce valid HTML > from Python. There's also lxml.html, which has straight forward support for generating HTML and comes with a lot of nice goodies for HTML handling: http://codespeak.net/lxml/dev/lxmlhtml.html#creating-html-with-the-e-factory Note that this requires lxml 2.0, which is currently in alpha status. Stefan From arnodel at googlemail.com Mon Sep 3 14:47:16 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 03 Sep 2007 11:47:16 -0700 Subject: trap setting attribute when the attribute is dict In-Reply-To: References: Message-ID: <1188845236.417709.307160@50g2000hsm.googlegroups.com> On Sep 3, 7:00 pm, wrote: > Hello all, > > I have a question which might be simple or need some work around. > > I want to do something like this. My class/instance has a dict as a > property. I want the instance to catch the change in the dict (change > in some values, addition/deletion of key/value etc) to be recognized by > the class instance. > > How can I do this? Any suggestions are very well appreciated. > > Here is an example of what I want my class to behave: > > class test(object): > def __init__(self): > self._d = {} > self._changed = False > def getd(self): > print 'called getd' > return self._d > # dont know what to do next > def setd(self,val): > print 'called setd', key, val > self._d[key] = val Where does the 'key' come from? Perhaps you need to look further into how properties work. > self._changed = True > d = property(getd,setd,None,None) > > def getc(self): > return self._changed > changed = property(getc,None,None,None) > > if __name__ == '__main__': > obj = test() > print 'obj.changed = ', obj.changed > print > > # I want obj to know that its propety d being changed here > print "t.d['a'] = 1" > obj.d['a'] = 1 > print > > # I want the "changed" property to be True > print 'obj.changed = ', obj.changed > You can't do that with plain dicts, and I'm not sure it is often a good idea. However you could create a class that behaves like a dict but calls a function each time an item is set, e.g. (made up terminology): >>> class TriggerDict(object): ... def __init__(self, trigger, val=None): ... self.trigger = trigger ... self.dict_ = val or {} ... def __setitem__(self, key, val): ... self.trigger(self, key, val) ... self.dict_[key] = val ... def __getitem__(self, key): ... return self.dict_[key] ... >>> def trigger(d, k, v): ... print '%s => %s' % (k, v) ... >>> td = TriggerDict(trigger) >>> td['spanish'] = 'inquisition' # see side effect below. spanish => inquisition >>> td['spanish'] 'inquisition' >>> Obviously your trigger function would set the _changed attribute of the test object instead. And again it is probably not a good idea unless you know exactly what you are doing. If it was me, I'd try to rethink my design instead. HTH -- Arnaud From cscheit at lstm.uni-erlangen.de Tue Sep 18 08:06:22 2007 From: cscheit at lstm.uni-erlangen.de (Christoph Scheit) Date: Tue, 18 Sep 2007 14:06:22 +0200 Subject: Memory Problem Message-ID: <200709181406.22771.cscheit@lstm.uni-erlangen.de> Hi, I have a short script/prog in order to read out binary files from a numerical simulation. This binary files still need some post-processing, which is summing up results from different cpu's, filtering out non-valid entrys and bringing the data in some special order. Reading the binary data in using the struct-module works fine - I read one chunk of data into a tuple, this tupel I append to a list. At the end of reading, I return the list. Then the data is added to a table, which I use for the actual Post-Processing. The table is actually a Class with several "Columns", each column internally being represented by array. Now adding all the data from the simulation results to the table makes the memory usage exploding. So I would like to know, where exactly the memory is vasted. Here the code to add the data of one file (I have to add the data of various files to the same table in total) # create reader breader = BDBReader("", "", "#") # read data bData = breader.readDB(dbFileList[0]) # create table dTab = DBTable(breader.headings, breader.converters, [1,2]) addRows(bData, dTab) Before I add a new entry to the table, I check if there is already an entry like this. To do so, I store keys for all the entries with row-number in a dictionary. What about the memory consumption of the dictionary? Here the code for adding a new row to the table: # check if data already exists if (self.keyDict.has_key(key)): rowIdx = self.keyDict[key] for i in self.mutableCols: self.cols[i][rowIdx] += rowData[i] return # key is still available - insert row to table self.keyDict[key] = self.nRows # insert data to the columns for i in range(0, self.nCols): self.cols[i].add(rowData[i]) # add row i and increment number of rows self.rows.append(DBRow(self, self.nRows)) self.nRows += 1 Maybe somebody can help me. If you need, I can give more implementation details. Thanks in advance, Christoph -- ============================ M.Sc. Christoph Scheit Institute of Fluid Mechanics FAU Erlangen-Nuremberg Cauerstrasse 4 D-91058 Erlangen Phone: +49 9131 85 29508 ============================ From gherron at islandtraining.com Thu Sep 6 14:32:51 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 06 Sep 2007 11:32:51 -0700 Subject: Getting original working directory In-Reply-To: <12.1809-14479-787046656-1189102077@seznam.cz> References: <12.1809-14479-787046656-1189102077@seznam.cz> Message-ID: <46E047D3.8070007@islandtraining.com> rave247 rave247 wrote: > "......the *original* directory location *after* os.chdir() is performed......" os.getcwd() is not helping much as it returns the location that was set up in os.chdir() call > That requirement is just to absurd to be taken at face value. Are you saying you *CAN'T* call getcwd and save the value before you call chdir, and that you *MUST* recover the original working directory *AFTER* you change it. I don't believe it... and won't waste my time trying to solve such a silly problem until you demonstrate that you can't do it any other way. Gary Herron > Thanks > > > >> ------------ P?vodn? zpr?va ------------ >> Od: Gabriel Genellina >> P?edm?t: Re: Getting original working directory >> Datum: 06.9.2007 17:35:51 >> ---------------------------------------- >> On 6 sep, 12:19, rave247 rave247 wrote: >> >> >>> I' am unable to solve this problem. I've got python program, it is installed >>> >> in standard location. I run this program from some location X (note that I just >> type relative "myscript", leaving operating system to look up script itself >> using PATH variable) and this program somewhere in the code calls os.chdir() to >> change it is current working directory and I would need in python code to get >> the *original* directory location *after* os.chdir() is performed. This means >> the location X from which script was performed - it is the location I am in >> after script is finished. >> >> Use os.getcwd() >> http://docs.python.org/lib/os-file-dir.html >> >> -- >> Gabriel Genellina >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> From mail at timgolden.me.uk Fri Sep 21 03:43:50 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 21 Sep 2007 08:43:50 +0100 Subject: looking for ocbc example In-Reply-To: References: Message-ID: <46F37636.7030105@timgolden.me.uk> Carl K wrote: > It seems there are 2 odbc modules - pyOdbc and mxOdbc - anyone know the difference? In short, pyodbc is open source; mxOdbc requires a commercial license. pyodbc is a newcomer, but appears to work for everything I've thrown at it (which is not much). mxOdbc has been around longer, and is sure to be a more mature product. It may offer more features & functionality. Unless you've got specific requirements (for example, commercial and/or bleeding-edge support) I suggest you start with pyodbc. You should be able to switch quite easily to mxODBC if that seems necessary later. TJG From mail at timgolden.me.uk Sun Sep 2 04:41:01 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 02 Sep 2007 09:41:01 +0100 Subject: Windows Media Player Playlist In-Reply-To: References: Message-ID: <46DA771D.40701@timgolden.me.uk> Lamonte Harris wrote: > Is it possible to use python to get the current playlist of the current > playing songs from Windows Media Player or Windows Player Classic? I don't know what the answer is (not least because I never use Windows Media Player) but a good guideline for this sort of question is: can it be done *without* python? The chances are that someone, somewhere, has tried to do this before and has found an answer using VBScript or C# or whatever. If you look around the internet and find such an answer, then people on this list can hopefully help you translate that into Python. TJG From bdesth.quelquechose at free.quelquepart.fr Mon Sep 17 05:41:34 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 17 Sep 2007 11:41:34 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <1190053757.091035.221570@22g2000hsm.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1190013827.107324.111820@w3g2000hsg.googlegroups.com> <1190053757.091035.221570@22g2000hsm.googlegroups.com> Message-ID: <46eee56b$0$15423$426a74cc@news.free.fr> TheFlyingDutchman a ?crit : > On Sep 17, 4:02 am, Steve Holden wrote: (snip) > I made a complaint about a small design choice. It's by no mean a "small" design choice. > I also made it in the > past tense at least once ("should have done it") and explicitly > expressed that I knew it wasn't going to happen. Python was created > based on a language that was designed to make it easy to use by > beginners. Most beginners still find Python easy to use AFAICT. At least, I know a lot of *non* programmers using it. > Doing so made it a clean and clear language. My preference > is for everything to be as clean and clear as possible. Mine too, and that's why I like Python the way it is : syntactic sugar for the common cases, *and* and easy way to play with lower levels when necessary. (snip) > Jury-rigging new features is going to make the elite happy but very > likely will be viewed differently by us average programmers. "us" ? Who is "us" ? >>change other aspects of the language, such as the ability to graft >>functions into instances and classes as methods. > > Those are elite-type features that make code harder to understand by > average programmers and probably the elite as well. Good news, there's a language designed exactly for "average programmers" that find these kind of features - as well as anything as complex as operator overloading, metaclasses, descriptors, higher order functions, multiple inheritance, lazy evaluation, and anything dynamic - way too "elite". It's named Java. The only drawback is that instead of "elite features", you'll have to resort to mumbo-jumbo overcomplexified "design patterns" and write ten times more code to solve the simplest things. To make a long story short: if you don't understand some "advanced" Python's features, then just don't use them. But have mercy and let us "elite programmers" (lol...) use more of Python's power. From kf9150 at gmail.com Sat Sep 29 02:17:06 2007 From: kf9150 at gmail.com (kf9150 at gmail.com) Date: Sat, 29 Sep 2007 06:17:06 -0000 Subject: your opinion on book "Foundations of Python Network Programming"? In-Reply-To: References: <1191016773.834049.8940@19g2000hsx.googlegroups.com> Message-ID: <1191046626.355400.203160@50g2000hsm.googlegroups.com> On Sep 28, 12:38 pm, "sean tierney" wrote: > I just read it (though I bought it half a year ago...don't judge :). > > Author recommends Python 2.3 and above...and as far as I know the > examples are good. And if anything IS outdated -- you'll be able to > do some quick research to get you to where you need to be...and he > does mention code several areas of change/addition/modification. (ie > urllib and urllib2). He uses a couple of 3rd party projects too. > > I really liked the book. I think Goerzen did a good job. He > addresses the code in the context of the problem the code is meant to > solve, which I found helpful. That said, it's not a substitute for > actually reading the code. > > ...if you haven't read the most recent edition of Programming Python > by Mark Lutz (O'Reilly), I'd recommend that first. Programming Python > covers (some) networking and everything else. More bang for the $$. > > Sean Sean, thanks for your review and recommendation of the book Programming Python. atm, i'm looking for a book that has detailed coverage on networking. so "Foundations of ..." seems to be a good choice for me. From carsten at uniqsys.com Mon Sep 24 06:35:34 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Sep 2007 06:35:34 -0400 Subject: python variable assignement In-Reply-To: <1190628822.472242.272900@19g2000hsx.googlegroups.com> References: <1190628822.472242.272900@19g2000hsx.googlegroups.com> Message-ID: <1190630134.3385.14.camel@dot.uniqsys.com> On Mon, 2007-09-24 at 10:13 +0000, mihai wrote: > I work at an application witch has embeded python. > > We have an python type X. > > # a != b > > a = b # at this point both variables have the same value Not quite. At this point, 'a' and 'b' are names in the local namespace that refer to the same object. > b = select_other() Now 'b' becomes a reference to the object returned by select_other(). Presumably that's a different object than the one it referred to before. 'a' still refers to the same object it referred to before. > # steel the same values but both have the new value of b No, the code you showed us wouldn't behave this way. > What might be the cause for this behavior? What behavior? > The type of a and b > variable is the same, > and is defined using PyTypeObject structure. That doesn't matter. (Variable) Names don't have types. Objects have types, and a name can refer to an object of any type. See http://effbot.org/zone/python-objects.htm . > I hope I was explicit. Unfortunately, you weren't. If the above explanations didn't help you, please explain what you want to achieve, show us your actual code and what you expect it to do, and tell us what it's doing instead. -- Carsten Haese http://informixdb.sourceforge.net From carsten at uniqsys.com Fri Sep 21 14:23:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 21 Sep 2007 14:23:20 -0400 Subject: Parameterize formatting string In-Reply-To: <18c1e6480709211116v1c830409q306605e414102272@mail.gmail.com> References: <1190397297.236691.137220@19g2000hsx.googlegroups.com> <18c1e6480709211116v1c830409q306605e414102272@mail.gmail.com> Message-ID: <1190399000.3393.38.camel@dot.uniqsys.com> On Fri, 2007-09-21 at 20:16 +0200, David wrote: > Or, more ugly: > > "%%%di" % a % 12 Or, less ugly: "%*i" % (a,12) -- Carsten Haese http://informixdb.sourceforge.net From ldo at geek-central.gen.new_zealand Fri Sep 7 04:13:23 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 07 Sep 2007 20:13:23 +1200 Subject: library to launch program in linux References: <1189103678.484278.321650@r34g2000hsd.googlegroups.com> <13e0itfgm0ida1c@corp.supernews.com> Message-ID: In message , Laszlo Nagy wrote: > Grant Edwards wrote: > >> On 2007-09-06, idzwan.nizam at gmail.com wrote: >> >>> I'm a new user. What library should I use so that I can launch >>> program in linux using python? >>> >> >> subprocess >> > Hmm, there are some others... subprocess subsumes them all. From richardjones at optushome.com.au Thu Sep 27 20:40:20 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Fri, 28 Sep 2007 10:40:20 +1000 Subject: Python 3.0 migration plans? References: Message-ID: <46fc4d74$0$1027$afc38c87@news.optusnet.com.au> Steve Holden wrote: > I wondered if a straw poll could get some idea of readers' thoughts > about when they will be migrating to 3.0 on, so I used the new widget on > Blogger to add a poll for that. > > I'd appreciate if if you would go to > > http://holdenweb.blogspot.com/ > > and register your vote on your intended migration timescale. I'll use the "no plans" response for my actual "no simple answer" real response. Richard From steve at REMOVE-THIS-cybersource.com.au Wed Sep 19 23:13:51 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Sep 2007 03:13:51 -0000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <87k5qn5cwi.fsf@mulj.homelinux.net> <87y7f2w0xj.fsf@benfinney.id.au> Message-ID: <13f3pbfh7to7k4b@corp.supernews.com> On Thu, 20 Sep 2007 12:00:40 +1000, Ben Finney wrote: > In its latter form, it is worthless to me when I'm looking for "get > superclass of A", but its name and parameters and documentation all lead > me very strongly to believe otherwise. Why are you looking for the superclass of A? If it is specifically for the purpose of inheritance, then surely "which class(es) is/are the superclass(es)" is an implementation detail that you shouldn't care about? In other words, in principle you want to do something like the following: class MyClass(*base_classes): def method(self, *args): print args return inherit_from_base_classes(self, 'method')(*args) # could also be written as: self.__inherit__('method', *args) # or even: self.__inherit__().method(*args) # or similar. The details of the inheritance are not important, so long as it calls the right method of the right base-classes in the right order. You shouldn't need to know what that order is (except to the extent you've defined the base classes). If that's what you want, then you don't need the class itself. You want *something like* super(), even though the existing implementation of super is sadly confusing and hard to use. BUT I think, as far as I can tell, that super() does actually do the right thing, *if* you can work out just what arguments to give it, and provided all the base classes *and their bases classes* themselves also call super(). If you actually want the super-class(es) themselves, heaven knows why, then you can use MyClass.__base__ and MyClass.__bases__, although you have to intuit this from communing with the cosmos, because dir(MyClass) doesn't show them. -- Steven. From Shawn at Milochik.com Wed Sep 5 12:18:34 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 5 Sep 2007 12:18:34 -0400 Subject: PythonAlley.com In-Reply-To: <20070905153913.GD3437@gmail.com> References: <2dc0c81b0709050727q7e56e99dnf8918e7d143d53a@mail.gmail.com> <20070905153913.GD3437@gmail.com> Message-ID: <2dc0c81b0709050918n4466f630pdb6d57b219f36d73@mail.gmail.com> On 9/5/07, O.R.Senthil Kumaran wrote: > * Shawn Milochik [2007-09-05 10:27:08]: > > I bought the domain PythonAlley.com (and PerlAlley.com and > > > > Does anyone have any ideas as to what a wonderful use for > > PythonAlley.com would be? I'd really like to do something with at > > If "you" don't have an idea, most likely others wont have as well. :) > > -- > O.R.Senthil Kumaran > http://uthcode.sarovar.org > Faulty logic. Otherwise, you would have to agree that you don't know what you want for lunch if I don't know. From antroy at gmail.com Fri Sep 21 07:56:54 2007 From: antroy at gmail.com (Ant) Date: Fri, 21 Sep 2007 04:56:54 -0700 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <874phou1pa.fsf@benfinney.id.au> Message-ID: <1190375814.425991.87490@r29g2000hsg.googlegroups.com> On Sep 21, 4:47 am, "W. Watson" wrote: > How about in the case of MS Win? Both emacs and vim have GUI versions that run on Windows. -- Ant... From trekker182 at gmail.com Thu Sep 27 12:36:58 2007 From: trekker182 at gmail.com (Shawn Minisall) Date: Thu, 27 Sep 2007 12:36:58 -0400 Subject: ValueError: too many values to unpack,>>> Message-ID: <46FBDC2A.30701@gmail.com> I am trying to read a few lines of a file with multiple values, the rest are single and are reading in fine. With the multiple value lines, python says this "ValueError: too many values to unpack" I've googled it and it says that happens when you have too few or too many strings that don't match with the variables in number your trying to assign them too. Below are the lines in reading in: line 3 - 19.18 29.15 78.75 212.10 line 4 - 100 20 410.29 And this is the code I'm using: #read withdrawls from file on line3 line = infile.readline() #split withdrawls up withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") #read deposits from file on line4 line = infile.readline() #split deposits up deposit1, deposit2, deposit3 = string.split(line, "\t") I have 4 strings to match line 3 and 3 to match the 3 on line 4...any thoughts? thx From pablo at decode.com.ar Wed Sep 26 13:00:09 2007 From: pablo at decode.com.ar (Pablo Ziliani) Date: Wed, 26 Sep 2007 14:00:09 -0300 Subject: regex with specific list of string In-Reply-To: <1190822055.3397.52.camel@dot.uniqsys.com> References: <1190821357.753909.178210@50g2000hsm.googlegroups.com> <1190822055.3397.52.camel@dot.uniqsys.com> Message-ID: <46FA9019.90402@decode.com.ar> Carsten Haese wrote: > On Wed, 2007-09-26 at 15:42 +0000, james_027 wrote: > >> hi, >> >> how do I regex that could check on any of the value that match any one >> of these ... 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', >> 'sep', 'oct', 'nov', 'dec' >> > > Why regex? You can simply check if the given value is contained in the > set of allowed values: > > >>>> s = set(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', >>>> > 'sep', 'oct', 'nov', 'dec']) > >>>> 'jan' in s Also, check calendar for a locale aware (vs hardcoded) version: >>> import calendar >>> [calendar.month_abbr[i].lower() for i in range(1,13)] ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] If you still want to use regexes, you can do something like: >>> import re >>> pattern = '(?:%s)' % '|'.join(calendar.month_abbr[1:13]) >>> pattern '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)' >>> re.search(pattern, "we are in september", re.IGNORECASE) <_sre.SRE_Match object at 0xb7ced640> >>> re.search(pattern, "we are in september", re.IGNORECASE).group() 'sep' If you want to make sure that the month name begins a word, use the following pattern instead: >>> pattern = r'(?:\b%s)' % r'|\b'.join(calendar.month_abbr[1:13]) >>> pattern '(?:\\bJan|\\bFeb|\\bMar|\\bApr|\\bMay|\\bJun|\\bJul|\\bAug|\\bSep|\\bOct|\\bNov|\\bDec)' If in doubt, Google for "regular expressions in python" or go to http://docs.python.org/lib/module-re.html Regards, Pablo From steve at REMOVE-THIS-cybersource.com.au Mon Sep 10 11:01:32 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 10 Sep 2007 15:01:32 -0000 Subject: How do I read and write to the same CSV file References: <1189434466.001109.313060@d55g2000hsg.googlegroups.com> Message-ID: <13ean2c2ip6i153@corp.supernews.com> On Mon, 10 Sep 2007 07:27:46 -0700, Chris wrote: > I want to update one field in a row for a csv file. So far my code looks > something like this > > cf_stream = open("\\config.csv","r+") > csv_file = csv.DictReader(cf_stream, ['Algorithm','LastModified']) > > and then I know I can do something like this > > for row in csv_file > name = row["Algorithm"] > date = row["LastModified"] > > now what I want is something like this > > if date == 0: > date = os.getmtime() > # now this is where I want to write into the row of the same csv > file but only updating that one field > > How can I do this? With difficulty unless the bytes you are writing to are exactly the same length as the bytes that were there before. In my opinion, unless you're writing a file with fixed-length fields, and maybe not even then, give up the dream of writing directly in place. Unless your file is HUGE, the chances are that trying to modify it in place is not only harder work but also slower. But if you insist... you might be able to use cf_stream.seek() to move to the current position in the file, then write the bytes you want. How do you find the current position? Black magic or voodoo might help. Otherwise you might count every character of every line up to the field you want. Don't forget delimiters, quote marks and newlines. Good luck. -- Steven. From python at cx.hu Wed Sep 5 19:19:28 2007 From: python at cx.hu (Ferenczi Viktor) Date: Thu, 6 Sep 2007 01:19:28 +0200 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? In-Reply-To: <87tzq898e2.fsf@wilson.homeunix.com> References: <46DEFD2E.5050205@sbcglobal.net> <87tzq898e2.fsf@wilson.homeunix.com> Message-ID: <200709060119.28607.python@cx.hu> Hello, > > from property_support import hasProperties, Property > > > > @hasProperties > > class Sphere(object): > > def setRadius(self, value): > > ... some setter implementation ... > > radius=Property(default=1.0, set=setRadius, type=(int, float)) > > color=Property(default='black', allowNone=True) > > > > This is a cleaner syntax if you need automatic default > > setter/getter implementations with type checking, default values, > > etc. > > Well, I think @hasProperties is very ugly. Such things always look > like a dirty trick. The programmer wonders why the language cannot > detect by itself that there are properties in this class. If you do not include the @hasProperties class decorator, then radius=Property(...) means that radius is a class attribute with a Property instance as it's value, nothing special. If you also include the class decorator, then it takes an additional meaning. In this case the decorator should remove the Property instance from the class and turn it into a real property. This is not magic. This is a possible use case of the new class decorator feature. Properties are very useful, since ordinary attribute access can be transparently replaced with properties if the developer needs to add code when it's set or needs to calculate it's value whenever it is read. As an additional benefit this could allow developers to implement change events for properties that allows any number of observers to monitor property changes. This could be very useful in GUI programming, for example. Regards, Viktor From rodney.maxwell at gmail.com Sat Sep 15 11:44:36 2007 From: rodney.maxwell at gmail.com (Rodney Maxwell) Date: Sat, 15 Sep 2007 15:44:36 -0000 Subject: Extended slicing and Ellipsis - where are they used? In-Reply-To: References: <1189699345.436400.233460@g4g2000hsf.googlegroups.com> Message-ID: <1189871076.796975.321460@19g2000hsx.googlegroups.com> On Sep 13, 5:50 pm, James Stroud wrote: > Rodney Maxwell wrote: > > The following are apparently legal Python syntactically: > > L[1:3, 8:10] > > L[1, ..., 5:-2] > > > But they don't seem to work on lists: > >>>> l = [0,1,2,3] > >>>> l[0:2,3] > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: list indices must be integers > >>>> l[...] > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: list indices must be integers > > > So where is this extended slicing used? > > AFAICT this syntax is not used in the standard library. However, the > mega-beauty of it is that you can make use of it in your own classes: > > py> class Bob(list): > ... def __getitem__(self, i): > ... try: > ... return [list.__getitem__(self, j) for j in i] > ... except TypeError: > ... return list.__getitem__(self, i) > ... > py> b = Bob(xrange(15, 30)) > py> b[3, 5, 7, 13] > [18, 20, 22, 28] > > James Or >>> b[0:3, 5, 9] [[15, 16, 17], 20, 24] which is what I was looking for in the first place. Thanks, Rodney From bdesth.quelquechose at free.quelquepart.fr Sat Sep 1 14:12:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 01 Sep 2007 20:12:23 +0200 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <1188743299.664137.194760@d55g2000hsg.googlegroups.com> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> Message-ID: <46daeaec$0$19889$426a74cc@news.free.fr> Ivan Wang a ?crit : > On Sep 2, 9:45 pm, jwrweather... at gmail.com wrote: > >>[snip code] >> >>Thanks for that. I realise that improving the algorithm will speed >>things up. I wanted to know why my less than perfect algorithm was so >>much slower in python than exactly the same algorithm in C. Even when >>turning off gcc's optimiser with the -O0 flag, the C version is still >> >> >> >> >>>100 times quicker.- Hide quoted text - >> >>- Show quoted text - > > Maybe Python is the slowest programming language in the world. > So there is a joke: some python hater said that "python" can only > crawl rather than run. :) > > Python is slow because: > (1) dynamic binding Yes. > (2) it is a interpretation language Not quite. It's compiled to byte-code - just like Java (would you call Java an 'interpreted language' ?) From ricaraoz at gmail.com Thu Sep 20 09:50:49 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 20 Sep 2007 10:50:49 -0300 Subject: re question In-Reply-To: References: Message-ID: <46F27AB9.8060007@bigfoot.com> Dan Bar Dov wrote: > I'm trying to construct a regular expression to match valid IP address, > without leading zeroes (i.e > 1.2.3.4 , 254.10.0.0 , but not > 324.1.1.1, nor 010.10.10.1 ) > > This is what I come up with, and it does not work. > > r'(^[12]?\d{0,2}\.){3,3}[12]?\d{0,2}' > > What am I doing wrong? > Any common knowledge IP matching RE? > > Thanks, > Dan > r'^[12]\d?\d?.\d{1,3}.\d{1,3}.\d{1,3}$' HTH From fredrik at pythonware.com Wed Sep 26 04:20:07 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 10:20:07 +0200 Subject: elementtree question In-Reply-To: <46F76F86.6010307@web.de> References: <46F76F86.6010307@web.de> Message-ID: Stefan Behnel wrote: > ET 1.3 will also support the extend() function, BTW. div.extend(seq) can be trivially rewritten as div[len(div):] = seq and in this case, you know that len(div) is 0, so you can simply do: div[:] = seq (this recent lxml habit of using lxml-specific versions of things that are trivial to do with the standard API is a bit disappointing. kind of defeats the purpose of having a standard API...) From frank at chagford.com Thu Sep 13 01:20:38 2007 From: frank at chagford.com (Frank Millman) Date: Wed, 12 Sep 2007 22:20:38 -0700 Subject: Is the wxPython list down? In-Reply-To: References: <1189602607.803546.180320@w3g2000hsg.googlegroups.com> <1189603681.292154.186620@o80g2000hse.googlegroups.com> Message-ID: <1189660838.832494.15000@d55g2000hsg.googlegroups.com> Chris Mellon wrote: > Frank Millman wrote: > > I noticed that cvs seems to be down as well - maybe it was on the same > > server. > > CVS is down because wx has moved to SVN, which is still up and running > fine. svn.wxwidgets.org. Thanks, Chris, I found it. However, the 'Browse sources' link on wxPython's home page still points to cvs. If the problem still exists when the mail list comes back up I will report it there. Frank From phil at freehackers.org Mon Sep 17 07:03:41 2007 From: phil at freehackers.org (BlueBird) Date: Mon, 17 Sep 2007 04:03:41 -0700 Subject: Reading text files where last line has no EOL Message-ID: <1190027021.235110.286450@g4g2000hsf.googlegroups.com> I tried and failed to read text files where the last line does not contain proper EOL. For my tests, I use a file that I create with the equivalent of : open('toto', 'w').write( '1234\n4567\n89AB' ) My reading code looks like this : l = f.readline() while len(l): self.appendLine( l ) l = f.readline() The last line is not returned (89AB) is never returned. I tried with "for l in f" with similar results. I read the doc : In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right. However, using seek() to reposition the file to an absolute position will flush the read-ahead buffer. New in version 2.3. I've tried to do a f.seek( f.tell() ) but that did not help. So how am I supposed to fetch that last line ? From afriere at yahoo.co.uk Mon Sep 10 20:53:10 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 10 Sep 2007 17:53:10 -0700 Subject: /dev/null as a file-like object, or logging to nothing In-Reply-To: References: <87k5r1jdzq.fsf@wilson.homeunix.com> <5kg48jF33dv5U3@mid.uni-berlin.de> <87fy1pjbpl.fsf@wilson.homeunix.com> Message-ID: <1189471990.613993.144130@d55g2000hsg.googlegroups.com> On Sep 11, 10:22 am, Lawrence D'Oliveiro wrote: > In message , Sion Arrowsmith wrote: > > > Torsten Bronger wrote: > > > Windows has a NUL: device which behaves like /dev/null . > > It's not a device, it's a reserved file name. Or rather, a reserved file > name prefix: any attempt to open a file name beginning with NUL, e.g. > NUL.DAT, will cause your output to disappear into a black hole. Yes Windows and its whacky error messages. While trying to save a Word doc as 'NUL.doc' I got this error message: "The file name 'NUL.doc' is a reserved device name." It's no wonder some might mistake it for a device! From vinay_sajip at yahoo.co.uk Thu Sep 13 08:24:03 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 13 Sep 2007 05:24:03 -0700 Subject: customizing a logging logger In-Reply-To: <1189621071.960166.30490@22g2000hsm.googlegroups.com> References: <1187412814.493872.325190@j4g2000prf.googlegroups.com> <1189527296.426004.17600@19g2000hsx.googlegroups.com> <1189615607.631091.214240@o80g2000hse.googlegroups.com> <1189621071.960166.30490@22g2000hsm.googlegroups.com> Message-ID: <1189686243.335406.79220@22g2000hsm.googlegroups.com> On 12 Sep, 19:17, garyjefferson... at gmail.com wrote: > It seems like using something other than a literal string in the > message is the way to go, since I assume that its __repr__() won't get > called unless the logger is actually going to log a message for it. > Is that right? > > Are any of the other methods likely to provide as-good or better > performance? You're almost right - it's __str__() rather than __repr__() that gets called, when str() is called on the msg object passed in the logging call. The str() call happens in LogRecord.getMessage(), which is called (indirectly) from a handler's emit() when the message needs to be formatted. So - I don't think that the other methods will provide better performance, as this approach is the simplest and most direct. I haven't done any tests to confirm this, though :-( Note that in order to avoid computation of *other* data passed to the logging call - i.e. other arguments - you should still use the logger.isXXXEnabled() idiom to avoid unnecessary computation, where performance is an issue. Best regards, Vinay Sajip From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Sep 25 05:34:26 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 25 Sep 2007 11:34:26 +0200 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: <5ls313F9ndm1U1@mid.individual.net> Lawrence D'Oliveiro wrote: > That's like saying, about a program that, when given "2 + 2", > outputs "5", that _of course_ it knows the correct answer is "4", > it just chooses to "modify" the answer before outputting it. No. Which laws say how transitions between modes have to be? Thus, I know laws saying 2 and 2 is 4. > Why does it "choose" to modify your position when you exit insert > mode? Does the phrase "broken as designed" mean anything to you? Does the phrase "everything I don't like is stupid" mean anything to you? Honestly, if you don't like it, either propose improvement or stop using it (and complaining about it). Your preference with user interfaces is obviously different. (Personally, I prefer single strokes to breaking my fingers with Esc-Meta-Alt-Control-Shift. :) ) > Why do you need so many ways to enter insert mode? It can be convenient. For you apprently not, though. > And the downside is that the largest single proportion of those > commands end up being variations on "enter insert mode". Because > most of the keystrokes you enter during an editing session are in > fact text to be input into the file, not commands to manipulate > that text. Strange -- mostly, this is not the case for me. When refactoring code for example, I jump around, copy, paste and modify many times. > So in a modal editor, having to jump in and out of insert mode all > the time just adds to the number of keystrokes you have to type. Much better than accessing special functions with finger breaking key combinations. IMHO. Regards, Bj?rn -- BOFH excuse #226: A star wars satellite accidently blew up the WAN. From meesters at uni-mainz.de Thu Sep 27 03:09:04 2007 From: meesters at uni-mainz.de (Christian Meesters) Date: Thu, 27 Sep 2007 09:09:04 +0200 Subject: strange behavious of the logging module? References: <1190643051.084144.230220@o80g2000hse.googlegroups.com> <1190672978.233964.232900@g4g2000hsf.googlegroups.com> <1190723915.218110.170720@k79g2000hse.googlegroups.com> Message-ID: Thanks Peter and Vinay, I finally understood. And indeed, removing the pyc-file in questions solves the problem - at least temporarily. Christian From hniksic at xemacs.org Tue Sep 4 12:34:12 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 04 Sep 2007 18:34:12 +0200 Subject: Printing lists in columns References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> <1188913394.763871.218660@d55g2000hsg.googlegroups.com> <46dd69b1$0$24998$426a74cc@news.free.fr> <1188917550.261894.84010@k79g2000hse.googlegroups.com> Message-ID: <87wsv6bda3.fsf@mulj.homelinux.net> cjt22 at bath.ac.uk writes: >> for row in izip_longest(*d, fillvalue='*'): >> print ', '.join(row) >> >> HTH > > I thought that but when I tried it I recieved a > "Syntax Error: Invalid Syntax" > with a ^ pointing to fillvalue :S Python isn't too happy about adding individual keyword arguments after an explicit argument tuple. Try this instead: for row in izip_longest(*d, **dict(fillvalue='*')): print ', '.join(row) From stodge at gmail.com Mon Sep 17 08:38:52 2007 From: stodge at gmail.com (Stodge) Date: Mon, 17 Sep 2007 05:38:52 -0700 Subject: Saving parameters between Python applications? In-Reply-To: References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> Message-ID: <1190032732.277479.221680@o80g2000hse.googlegroups.com> Good idea, but I can't guarantee that the two scripts will be run from the same directory - so where to store the pickle? On Sep 16, 5:25 pm, "Sebastian Bassi" wrote: > On 9/16/07, Stodge wrote: > > > python app1.py --location=c:\test1 > > What I want to do is save the location parameter, so I can then do (in > > the same window): > > python app2.py > > And have app2.py automatically have access to the value of "location". > > Do app1.py to save a pickle of the value you want app2 to read. > > -- > Sebasti?n Bassi ( ). Diplomado en Ciencia y Tecnolog?a. > Curso Biologia molecular para programadores:http://tinyurl.com/2vv8w6 > GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From __peter__ at web.de Sat Sep 8 03:58:33 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 8 Sep 2007 09:58:33 +0200 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <46e15959$0$16104$9b4e6d93@newsspool1.arcor-online.net> <13e3rd38ijilebd@corp.supernews.com> Message-ID: Am Sat, 08 Sep 2007 00:32:35 +0000 schrieb Steven D'Aprano: > On Fri, 07 Sep 2007 15:59:53 +0200, Wildemar Wildenburger wrote: > >> I just thought I'd go along with the analogy the OP created as that was >> his mindset and it would make things easier to follow if I didn't try to >> forcibly change that. > > My reaction to somebody trying to reason with the wrong analogy is to > teach them the right analogy, not to tell them they got it right when > they actually got it wrong. > > "My car won't start -- I must not have stirred the gasoline enough before > baking it." > > "Yes, that's right. It's very important to stir the gasoline fully so > that all the ingredients are fully mixed." I think Wildemar is too defensive. The pointer "analogy" is a good first approximation, not cargo cult. Peter From nfrancken at gmail.com Thu Sep 6 18:29:58 2007 From: nfrancken at gmail.com (windandwaves) Date: Thu, 06 Sep 2007 15:29:58 -0700 Subject: why should I learn python In-Reply-To: References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: <1189117798.506367.278560@y42g2000hsy.googlegroups.com> On Sep 7, 9:50 am, James Stroud wrote: > Seewww.python.org. Trust us all when we say that its the best. > I get that feeling - yes. Question is: 1. what is it good for? 2. why is it so good? I would love to hear some opinions. Cheers Nicolaas From horpner at yahoo.com Wed Sep 19 10:18:20 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 19 Sep 2007 14:18:20 GMT Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <876427zhzq.fsf@benfinney.id.au> <13f196qktorgc88@corp.supernews.com> <873axbxl2f.fsf@benfinney.id.au> <1190209294.584372.173410@o80g2000hse.googlegroups.com> Message-ID: On 2007-09-19, Michele Simionato wrote: > On Sep 19, 3:22 pm, Sion Arrowsmith > wrote: >> Ben Finney wrote: >> >> > If a function is named 'super' and operates on >> >classes, it's a pretty strong implication that it's about >> >superclasses. >> >> But it doesn't (under normal circumstances) operate on classes. >> It operates on an *instance*. And what you get back is a (proxy >> to) a superclass/ancestor of the *instance*. >> >> (And in the super(A, B) case, you get a superclass/ancestor of >> *B*. As has just been said somewhere very near here, what is >> misleading is the prominence of A, which isn't really the most >> important class involved.) >> > > Happily A (and B too) will become invisible in Python 3000. Nobody will miss A, but doesn't making B invisible recreate the current mystery in a new form? We want to get rid of A because it isn't possible to avoid repeating ourselves. But self is usually easily available and helps define what's happening. super.foo() to me, is even more confusing. self.super.foo() or super(self).foo() seem like improvements. Unfortunately, neither is one of the current alternate proposals. The closest competing proposal in PEP3135 is: self.__super__.foo() That syntax seems justified given the specialized application and involved pitfalls of super that you disclosed in your article. -- Neil Cerutti These people haven't seen the last of my face. If I go down, I'm going down standing up. --Chuck Person From infinioninternational at gmail.com Tue Sep 11 10:39:38 2007 From: infinioninternational at gmail.com (anky) Date: Tue, 11 Sep 2007 07:39:38 -0700 Subject: Make money to share photos Message-ID: <1189521578.357813.39540@d55g2000hsg.googlegroups.com> Make money to share photos Do you want to make money to post photos from internet.then just move on to http://goodtolove.com and start posting.They will pay their 50% adsense revenue with you...Then what are you waiting for just start posting photos in http://goodtolove.com. From paul.hankin at gmail.com Wed Sep 26 07:14:57 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 26 Sep 2007 11:14:57 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> Message-ID: <1190805297.182232.116830@50g2000hsm.googlegroups.com> On Sep 26, 9:31 am, Duncan Booth wrote: > Mark Summerfield wrote: > > As you've no doubt realised, this particular implementation gives best > > performance when the pattern of use is: lots of edits, lots of > > lookups, ..., and gives worst performance when the pattern of use is: > > edit, lookup, edit, lookup (in which case using a dict and sorted() is > > probably better). > > > So there is lots of scope for someone to do a version that has good > > performance for all patterns of use:-) > > I that's the point though: you can't write one implementation that has good > performance for all patterns of use: you have to either compromise on > performance somewhere, or use an implementation specifically matched to > your use case. > > For example, if the use case was some updates followed by iterating over > the first few keys only, it may be faster to use a heap for iteration. > > I suspect that for many use patterns you could improve performance > significantly by having two levels of invalidation for the the key list: in > __setitem__, if the key already exists you don't need to discard the list > in __keycache (although if a key or cmp function was provided it may no > longer be sorted). In that case it might be worthwhile keeping __keycache > but flagging it as needing to be sorted again next time it is used. Given > that Python's sort is very fast on sorted or nearly sorted lists this could > provide a worthwhile speedup for cases where the values change but the keys > don't change often. More flexibly, keep a set of inserted keys that haven't yet been included in the sorted list, and a set of deleted keys that haven't yet been removed from the sorted list. The cache is invalid if either of these sets are empty - and to make it valid you can choose what to do based on the sizes of the two sets (and the sorted list). For instance, if there's just been one insertion you're probably better doing an insertion rather than a full resort. Of course, there's a few nasty cases here but it's always possible to just throw away the sorted list and reconstruct it from the dict keys when things get too hairy (eg, the user deletes a key that's in the inserted-but-not-yet- sorted set). -- Paul Hankin From truelixin at gmail.com Thu Sep 6 01:50:40 2007 From: truelixin at gmail.com (truelixin at gmail.com) Date: Wed, 05 Sep 2007 22:50:40 -0700 Subject: Using wild character In-Reply-To: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> Message-ID: <1189057840.948838.60270@19g2000hsx.googlegroups.com> i will this may help you. countries = ["india","africa","atlanta","artica","nigeria"] filter(lambda country: country.startswith('a'), countries) From hassen62 at voila.fr Mon Sep 17 21:29:59 2007 From: hassen62 at voila.fr (hassen62 at voila.fr) Date: Tue, 18 Sep 2007 03:29:59 +0200 (CEST) Subject: using xlrd Message-ID: <14368282.847261190078999740.JavaMail.www@wwinf4603> Hi, I have installed Xlrd 0.6.1 Win 32. I have a file xls say "file.xls" located as follows:c:/file.xls. This file is composed with two columns of 5 lines. These columns are headed with "Col1" and "Col2", also the 5 rows are named with "Row1",...,"Row2". I have a silly question: What I can write to read this file from The Shell? sorry for this basic question but I can't find a document in the net that helps me for using xlrd. Thank you very much, Hassen. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdailey at gmail.com Mon Sep 24 22:17:59 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 24 Sep 2007 21:17:59 -0500 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> Message-ID: <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> On 9/24/07, Gabriel Genellina wrote: > > Yes: forget about regular expressions. ElementTree does that for free: > That's not an option. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.behnel-n05pAM at web.de Wed Sep 12 08:14:36 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 12 Sep 2007 14:14:36 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <5kq1hgF4r90oU1@mid.individual.net> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> Message-ID: <46E7D82C.40302@web.de> Bjoern Schliessmann wrote: >> What does "self" have to do with an object model? It's an >> function/method argument that might as well be hidden in the >> compiler without ever touching the role it has (if not, why?). I >> agree that it's needless noise in a language. > > If this was needless, why do C++ and Java have the "this" pointer? Be careful when you use the word "needless" in the context of Java. Stefan From anitnair at gmail.com Tue Sep 4 09:32:47 2007 From: anitnair at gmail.com (AniNair) Date: Tue, 04 Sep 2007 06:32:47 -0700 Subject: REGULAR EXPRESSION Message-ID: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> hi.. I am trying to match '+ %&/-' etc using regular expression in expressions like 879+34343. I tried \W+ but it matches only in the beginning of the string Plz help Thanking you in advance... From gagsl-py2 at yahoo.com.ar Thu Sep 20 01:48:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 20 Sep 2007 02:48:56 -0300 Subject: Memory Problem References: <200709181558.43026.cscheit@lstm.uni-erlangen.de> <200709181724.46141.cscheit@lstm.uni-erlangen.de> Message-ID: En Tue, 18 Sep 2007 12:24:46 -0300, Christoph Scheit escribi?: >> >> > # add row i and increment number of rows >> >> > self.rows.append(DBRow(self, self.nRows)) >> >> > self.nRows += 1 >> >> This looks suspicious, and may indicate that your structure contains >> cycles, and Python cannot always recall memory from those cycles, and >> you >> end using much more memory than needed. > > How can I detect if there are cycles? Analyzing your code, or maybe inspecting gc.garbage, or looking at sys.getrefcount(x) > self.rows is a list containing DBRow-objects, > each itself being an integer pointer (index) to the i-th row. > Im using this list in order to sort the table by sorting the index-list > instead of realy sorting the entries. (or to filter). What looks strange is the "self" argument to DBRow, since the items are already contained in self.rows But it's hard to tell anything more without looking at your code. -- Gabriel Genellina From jcd at sdf.lonestar.org Mon Sep 10 06:40:27 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 10 Sep 2007 06:40:27 -0400 Subject: Python syntax wart In-Reply-To: <46E51EAB.4030808@sdf.lonestar.org> References: <5khuq4F3ij9eU1@mid.individual.net> <46E51EAB.4030808@sdf.lonestar.org> Message-ID: <46E51F1B.5090008@sdf.lonestar.org> J. Cliff Dyer wrote: > Lawrence D'Oliveiro wrote: >> In message <5khuq4F3ij9eU1 at mid.individual.net>, Bjoern Schliessmann wrote: >> >> >>> What's wrong with this: >>> >>> for Link in GetEachRecord( >>> >> >> Then you're no longer showing the syntax structure in two dimensions. >> >> > If somebody handed me a program of more than twenty five lines that > was formatted "two dimensionally" as you call it, and asked me to deal > with it, the first thing I would do is reformat the code so a not to > be so hideously ugly. Your style has the unfortunate consequence of > requiring the reader to scroll ridiculous distances, making it more > difficult to maintain. I do see the benefit of using multiple lines > on complex statements, such as: > > if (actor == 'Tony Leung' > or actor == 'Alec Baldwin' > or actor == 'Divine' > or actor == 'Fitty-cent' > or actor == 'Sir Ian McKellen'): > go_see_the_movie() > > but even here, there is some attempt to keep things compact by making > each line meaningful. > > However, I utterly fail to see how putting the word "or" on its own > line, (or worse: "if!") clarifies things in the slightest. > > Part of the point of designing python with a line break as the > statement closer is to encourage you to write in a style that treats > each line as a statement. Changing the syntax to encourage people to > violate this principle would not be an improvement to the design, but > a relinquishing of basic principles. Obviously there are some cases > where you want to do something different, but that's what backslashes > are for. Frankly, I find your code just as ugly without the > backslashes as it is with them. > > Cheers, > Cliff > I replied to poster instead of to list. My apologies. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Sun Sep 9 00:27:45 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 08 Sep 2007 21:27:45 -0700 Subject: Parsing nested constructs In-Reply-To: <46e361f3$0$7695$9b4e6d93@newsspool2.arcor-online.net> References: <46e308d3$0$9153$426a74cc@news.free.fr> <1189296638.625012.286250@k79g2000hse.googlegroups.com> <46e361f3$0$7695$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1189312065.599420.218470@w3g2000hsg.googlegroups.com> On Sep 8, 10:01 pm, Wildemar Wildenburger wrote: > > Again pyparsing to the rescue :) > > I have to do a parsing project in Java right now and I dearly miss > pyparsing. I explained it to the guy I'm working for, and he was pretty > impressed. > > Thought that might make you smile. > > /W Wildemar - Thanks for such a glowing testimonial! It really is a boost of encouragement when I find projects that are using pyparsing, or see postings on c.l.py or the tutor list (by people other than me!) recommending using pyparsing in response to someone's post. I'm glad you find pyparsing so useful in your Python endeavors. -- Paul From grante at visi.com Thu Sep 13 11:35:27 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 13 Sep 2007 15:35:27 -0000 Subject: I want py2exe not to create library.zip References: <13egu7rmilu2ia4@corp.supernews.com> Message-ID: <13eim5vctdr00f5@corp.supernews.com> On 2007-09-13, Laszlo Nagy wrote: > >>> I want py2exe not to create library.zip. >>> >> >> setup ( >> [...] >> options = {"py2exe": {"skip_archive":1}} >> ) > > Cool! Just what I needed. Where it is documented? Ah, in the source. :-) That's pretty much it. :) I found on WorkingWithVariousPackagesAndModules Wiki page a reference to a command-line option --skip-archive. Then googling for "py2exe skip archive" found an example similar to the above. I haven't ever found any documentation for the py2exe options. The documentation for the some of general setup options tends to be a bit vague as well. I've added a few things to the py2exe Wiki pages, but somebody needs to start a page that just describes each of the py2exe options and what problem they're intended to solve... -- Grant Edwards grante Yow! Let's all show human at CONCERN for REVERAND MOON's visi.com legal difficulties!! From phil at riverbankcomputing.co.uk Fri Sep 28 19:07:12 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sat, 29 Sep 2007 00:07:12 +0100 Subject: ANN: PyQt v4.3.1 Released Message-ID: <200709290007.12197.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of PyQt v4.3.1 available from http://www.riverbankcomputing.co.uk/pyqt/. This is mainly a bug fix release. A Windows installer is provided for the GPL version of PyQt which contains everything needed for PyQt development (including Qt, Qt Designer, Qwt, QScintilla and the eric IDE) except Python itself. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. See http://www.riverbankcomputing.com/Docs/PyQt4/html/classes.html for the class documentation. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. PyQt v4 is implemented as a set of 11 extension modules containing approximately 400 classes and 6,000 functions and methods. QtCore The non-GUI infrastructure including event loops, threads, i18n, Unicode, signals and slots, user and application settings. QtGui A rich collection of GUI widgets. QtNetwork A set of classes to support TCP and UDP socket programming and higher level protocols (eg. HTTP, SSL). QtOpenGL A set of classes that allows PyOpenGL to render onto Qt widgets. QtScript A set of classes that implements a JavaScript interpreter. QtSql A set of classes that implement SQL data models and interfaces to industry standard databases. Includes an implementation of SQLite. QtSvg A set of classes to render SVG files onto Qt widgets. QtTest A set of classes to automate unit testing of PyQt applications and GUIs. QtXML A set of classes that implement DOM and SAX parsers. QtAssistant A set of classes that enables the Qt Assistant online help browser to be integrated with an application. QAxContainer A set of classes for Windows that allows the integration of ActiveX controls and COM objects. PyQt includes the pyuic4 utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. It is also able to load Designer XML files dynamically. From laurent.pointal at limsi.fr Mon Sep 10 09:23:23 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 10 Sep 2007 15:23:23 +0200 Subject: XML: SAX and XInclude Message-ID: [python 2.5, Linux Mandriva 2007.1] Hello, does anybody know about an XML parser usable with the sax API (xml.sax) and with XInclude feature support (directly or via hacks). With specifying nothing (default parser), it simply transmit xinclude elements (i tried to call parser on included file but it seem to be waiting for a complete document with root element). I tried libxml2, but failed with error (cf at the end). I tried xmlproc, but it simply transmit xinclude elements too. Thanks (its for PQRC - I've a first xhtml production which is not bad, when it'll be ok I will work on OpenDocument XML production - and would like to split PQRC xml source into several files). A+ Laurent. Problem with libxml2: [laurent at litchi qrccompiler]$ python compiler.py processing Traceback (most recent call last): File "compiler.py", line 573, in sys.exit(main(*sys.argv[1:])) File "compiler.py", line 569, in main handler.process_source() File "compiler.py", line 465, in process_source self.saxparser = make_parser(["libxml2"]) File "/usr/lib/python2.5/site-packages/_xmlplus/sax/sax2exts.py", line 37, in make_parser return XMLParserFactory.make_parser(parser_list) File "/usr/lib/python2.5/site-packages/_xmlplus/sax/saxexts.py", line 64, in make_parser return self._create_parser(parser_name) File "/usr/lib/python2.5/site-packages/_xmlplus/sax/saxexts.py", line 43, in _create_parser return drv_module.create_parser() AttributeError: 'module' object has no attribute 'create_parser' From wizzardx at gmail.com Fri Sep 21 14:16:29 2007 From: wizzardx at gmail.com (David) Date: Fri, 21 Sep 2007 20:16:29 +0200 Subject: Parameterize formatting string In-Reply-To: <1190397297.236691.137220@19g2000hsx.googlegroups.com> References: <1190397297.236691.137220@19g2000hsx.googlegroups.com> Message-ID: <18c1e6480709211116v1c830409q306605e414102272@mail.gmail.com> On 9/21/07, cyril giraudon wrote: > Hello, > > I 'd like to know if a std::setw() equivalent function exists in > python ? > > i thought of something like : > > a = 16 > "%ai" % 12 > > But it is not correct. > > Any Idea ? ("%i" % 12).rjust(a) Or, more ugly: "%%%di" % a % 12 The first % (after quotes) builds this string: "%16i". Then the second % operation converts that string to ' 12' See also: http://docs.python.org/tut/node9.html From gandalf at shopzeus.com Thu Sep 6 15:31:43 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 06 Sep 2007 21:31:43 +0200 Subject: library to launch program in linux In-Reply-To: <13e0itfgm0ida1c@corp.supernews.com> References: <1189103678.484278.321650@r34g2000hsd.googlegroups.com> <13e0itfgm0ida1c@corp.supernews.com> Message-ID: <46E0559F.5040704@shopzeus.com> Grant Edwards wrote: > On 2007-09-06, idzwan.nizam at gmail.com wrote: > > >> I'm a new user. What library should I use so that I can launch >> program in linux using python? Thank you in advance. >> > > subprocess > Hmm, there are some others. Here is a list: os.system os.popen (and os.popen2, os.popen3) os.spawn popen2 (the module) subprocess (this is often preferred over other modules) If you need to communicate with a subprocess using the system console, then possibly the third party pexpect module worth look at it. If you need to use this on Windows then you can use the win32 extensions and "CreateProcess"... I suggest that you read their documentation. Some of them are easy to use but feature less. Others are good for some purpose. Laszlo p.s.: In Python "there should be only one obvious and correct way to do it". What??? :-) From vinay_sajip at yahoo.co.uk Wed Sep 12 12:46:47 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 12 Sep 2007 09:46:47 -0700 Subject: customizing a logging logger In-Reply-To: <1189527296.426004.17600@19g2000hsx.googlegroups.com> References: <1187412814.493872.325190@j4g2000prf.googlegroups.com> <1189527296.426004.17600@19g2000hsx.googlegroups.com> Message-ID: <1189615607.631091.214240@o80g2000hse.googlegroups.com> On 11 Sep, 17:14, garyjefferson... at gmail.com wrote: > What is the best way to do this, so that I don't have to manually put > the self.ctx in the log string in hundreds of different places? > Another way is to generate your log messages via a factory method which prepends the context: you can do this via a mixin, too. def log_message(self, msg): return "%s: %s" % (self.ctx, msg) Note also that in recent versions, an optional "extra" parameter can be used, to pass info into the LogRecord. See http://mail.python.org/pipermail/patches/2007-January/021535.html which may be of some help - it's a similar use case. Best regards, Vinay Sajip From ivlenin at gmail.com Sat Sep 15 16:33:27 2007 From: ivlenin at gmail.com (I V) Date: Sat, 15 Sep 2007 20:33:27 GMT Subject: find and remove "\" character from string References: Message-ID: On Sat, 15 Sep 2007 19:34:45 +0300, Konstantinos Pachopoulos wrote: > Hi, > i have the following string s and the following code, which doesn't > successfully remove the "\", but sucessfully removes the "\\". There is no \\ in the string; there's one \ , which gets succesfully removed. > >>> s="Sad\\asd\asd" When you write a string in the source code \\ gets changed to \ and \a gets changed to "ASCII Bell (BEL)" (that's what the docs say), which is a (non-printable) control code that is supposed to make the terminal beep. > >>> newS="" > >>> for i in s: > ... if i!="\\": Here, your test is true if i is not \ > ... newS=newS+i > ... > >>> newS > 'Sadasd\x07sd' And here, you have a string containing no backslashes, but containing a character with ASCII code 7; it turns out that ASCII code 7 is the "ASCII Bell", i.e., the character that you added to the string when you wrote '\a'. From deets at nospam.web.de Mon Sep 3 05:06:41 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Sep 2007 11:06:41 +0200 Subject: TypeError: 'module object is not callable' References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> Message-ID: <5k2151F1p42tU2@mid.uni-berlin.de> christophertidy at hotmail.com wrote: > Hi > > I am new to Python and have recieved this error message when trying to > instantiate an object from a class from another file within the same > directory and wondered what I have done wrong. > > I have a Step.py class: > class Step(object) > def __init__(self, sName): > "Initialise a new Step instance" > self.sName = sName > self.depSteps = [] > self.remDepSteps = [] > self.isCompleted = 0 > > > Then I have created a new file within the same directory called > main.py: > > import Step > a = Step("magn") > > The following however generates the error > Traceback (most recent call last): > File "main.py", line 3, in ? > a = Step("magn") > TypeError: 'module' object is not callable > > If anyone could help point me in the right direction, how to fix this > problem it would be much appreciated. Do you by any chance come from a java-background? Your actual problem is simply solved by this: import Step Step.Step("magn") That's because Step.py is a module, and _not_ the class - there is no file-class-correspondence as it is in e.g. Java. Diez From jeremy+complangpython at jeremysanders.net Tue Sep 25 07:11:48 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 25 Sep 2007 12:11:48 +0100 Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> Message-ID: Mark Summerfield wrote: > If there is positive feedback I will submit the PEP to the reviewers, > so if you think it is a good idea please say so. (I'm sure that if you > _don't_ like it you'll tell me anyway:-) It would be nice to have the ability to use numerical indexes and the key, but I don't think they should share the same methods. A useful use case would be to make a LRU (least recently used) dictionary, where the keys are time-based (e.g. an incrementing counter). You should be able to identify the least recently used object for discarding by just accessing the last item in the dictionary. By the way, I think a LRU cache dictionary would be a great addition to the standard library. Is there any speed advantage from implementing the sorteddict as a red-black tree or something similar in C? Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From asma61 at dsl.pipex.com Wed Sep 19 15:46:00 2007 From: asma61 at dsl.pipex.com (DaveM) Date: Wed, 19 Sep 2007 20:46:00 +0100 Subject: can Python be useful as functional? (off topic) References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> <46F02FCF.7080209@pytex.org> Message-ID: On Tue, 18 Sep 2007 21:06:39 +0100, Jonathan Fine wrote: >Steve Holden wrote: > >> You remind me of the conversation between the philosopher and an >> attractive lady whom he was seated next to at dinner. He asked her if >> she would sleep with him for a million dollars, to which she readily >> agreed. So he followed this by asking her if she'd sleep with him for a >> dollar. She replied: "No. Do you take me for a prostitutte?", to which >> his riposte was "We have already established that fact, and are now >> merely haggling about the price". > >I've seen this before, and it is witty. > >However, it is perhaps unfair towards the woman. The man, after all, is >someone who has offered a woman money in return for sex. > >The whole story reads differently if we replace 'philosopher' by 'man' >and 'attractive lady' by 'woman'. The version I prefer has the woman asking, "What sort of woman do you take me for?" DaveM From kyosohma at gmail.com Thu Sep 27 10:20:03 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 27 Sep 2007 14:20:03 -0000 Subject: Launching command on windows In-Reply-To: <1190899078.141370.116190@57g2000hsv.googlegroups.com> References: <1190899078.141370.116190@57g2000hsv.googlegroups.com> Message-ID: <1190902803.222738.52050@w3g2000hsg.googlegroups.com> On Sep 27, 8:17 am, Alexandre Badez wrote: > Hy, > > I'm working on windows and I try to do something like: > > import os > APP = os.path.abspath("C:\\Program Files\\Notepad++\\notepad++.exe") > FILE1 = os.path.abspath("D:\\Documents and settings\\test1.py") > FILE2 = os.path.abspath("D:\\Documents and settings\\test2.py") > command = '"%(app)s" "%(file1)s" "%(file2)s"' % { > 'app' : APP, > 'file1' : FILE1, > 'file2' : FILE2} > # === FOR 'DEBUG' === > print APP > print FILE1 > print FILE2 > print command > print repr(command) > # === END FOR 'DEBUG' === > os.system(command) > > This code give in output: > C:\Program Files\Notepad++\notepad++.exe > D:\Documents and settings\test1.py > D:\Documents and settings\test2.py > "C:\Program Files\Notepad++\notepad++.exe" "D:\Documents and settings > \test1.py" "D:\Documents and settings\test2.py" > '"C:\\Program Files\\Notepad++\\notepad++.exe" "D:\\Documents and > settings\\test1.py" "D:\\Documents and settings\\test2.py"' > > 'C:\Program' n'est pas reconnu en tant que commande interne > ou externe, un programme ex,cutable ou un fichier de commandes. > # <= My windows is a french one > # This error message could be translated as: > # 'c:\Program' is not an internal nor external command, an executable > program nor a command file > > But if I copy the command in the output, an paste it in a console, it > work very well. > Does any of you know what I can do ? > > PS: I think I'm oblige to add " neer every path for spaces in path, > but if you know an other way, it could be cool :) I got it to work using subprocess.Popen Not sure why it doesn't work with os.system though. Mike From dijkstra.arjen at gmail.com Mon Sep 17 09:31:56 2007 From: dijkstra.arjen at gmail.com (duikboot) Date: Mon, 17 Sep 2007 13:31:56 -0000 Subject: simple regular expression problem In-Reply-To: <1190035328.837246.318920@d55g2000hsg.googlegroups.com> References: <1190034041.796626.66790@n39g2000hsh.googlegroups.com> <1190035328.837246.318920@d55g2000hsg.googlegroups.com> Message-ID: <1190035916.278037.56070@57g2000hsv.googlegroups.com> Thank you very much, it works. I guess I didn't read it right. Arjen On Sep 17, 3:22 pm, Jason Drew wrote: > You just need a one-character addition to your regex: > > regex = re.compile(r'', re.S) > > Note, there is now a question mark (?) after the .* > > By default, regular expressions are "greedy" and will grab as much > text as possible when making a match. So your original expression was > grabbing everything between the first opening tag and the last closing > tag. The question mark says, don't be greedy, and you get the > behaviour you need. > > This is covered in the documentation for the re module.http://docs.python.org/lib/module-re.html > > Jason > > On Sep 17, 9:00 am, duikboot wrote: > > > Hello, > > > I am trying to extract a list of strings from a text. I am looking it > > for hours now, googling didn't help either. > > Could you please help me? > > > >>>s = """ \n\n28996\n\n\n28997\n""" > > >>> regex = re.compile(r'', re.S) > > >>> L = regex.findall(s) > > >>> print L > > > ['organisatie>\n28996\n > > \n\n28997\n > > I expected: > > [('organisatie>\n28996\n > > \n), (\n28997\n > organisatie')] > > > I must be missing something very obvious. > > > Greetings Arjen From __peter__ at web.de Wed Sep 5 12:34:44 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 5 Sep 2007 18:34:44 +0200 Subject: python exec behaves inconsistent with respect to module imports References: <1188997944.162811.33640@r34g2000hsd.googlegroups.com> <1189003511.666050.293060@22g2000hsm.googlegroups.com> Message-ID: Am Wed, 05 Sep 2007 14:45:11 +0000 schrieb carl.dhalluin at gmail.com: > So now get back to my exec code in the previous post. > The exec applies a mixture of both rules > 1. The exec looks at its namespace to apply the rule for globals(). > Since I'm not at top-level, variables are not auto-populated in the > globals(), unless I add the keyword 'global' like you suggested. > 2. However, the exec applies the other rule for locals(). It does NOT > copy the locals() from one level to the nested one, although it > should. > > To me this seems a bug in python exec: > - exec should look at its context to find out if the exec is called > top-level or deeper > - if top-level: auto-populate globals, and do not allow inheritance of > locals to nested levels > - if non top-level: dont populate globals, but allow inheritance of > locals to nested levels. I like your systematic approach. > What do you think? Too much work :) Seriously, the local namespace in a normal python function is not a dictionary, and the decision on how to access a variable is made at compile time. One way to achieve consistency would be to always use dictionaries and have the lookup work its way up through the enclosing namespaces. Of course that would kill performance... Peter From http Sun Sep 9 23:10:37 2007 From: http (Paul Rubin) Date: 09 Sep 2007 20:10:37 -0700 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> <7xhcm4pl5m.fsf@ruckus.brouhaha.com> <7xsl5ndau8.fsf@ruckus.brouhaha.com> Message-ID: <7xzlzvw6z6.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > According to this , the family of > algorithms collectively described as "SHA-2" is by no means a definitive > successor to SHA-1. See : However, due to advances in technology, NIST plans to phase out of SHA-1 in favor of the larger and stronger hash functions (SHA-224, SHA-256, SHA-384 and SHA-512) by 2010. SHA-1 and the larger hash functions are specified in FIPS 180-2. For planning purposes by Federal agencies and others, note also that the use of other cryptographic algorithms of similar strength to SHA-1 will also be phased out in 2010. SHA-1 and the stronger hash functions in FIPS 180-2 are all NIST approved. This may also be of interest: http://www.csrc.nist.gov/pki/HashWorkshop/index.html From ruoyu0088 at gmail.com Wed Sep 26 00:22:37 2007 From: ruoyu0088 at gmail.com (HYRY) Date: Tue, 25 Sep 2007 21:22:37 -0700 Subject: the address of list.append and list.append.__doc__ In-Reply-To: References: <1190775258.351819.24930@22g2000hsm.googlegroups.com> Message-ID: <1190780557.879816.13800@d55g2000hsg.googlegroups.com> > No. a.append is a "bound method" - a method that already has an > associated instance, that will be provided as the first argument to the > method call. Bound methods are created "on the fly". > Does this means there is no method to get the original methods from the Bound methods created "on the fly"? I installed python 2.4.4 and tried id(list.append.__doc__) again, here is the result, only id(list.append.__doc__) changes, this is strange, and only happened in the command line. Because I am doing something program that use this id in the command line. Can someone help me try this on your PC, I want to know which is the problem: this version of python, or my PC. Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> id(list.__doc__) 11674984 >>> id(list.__doc__) 11674984 >>> id(list.__doc__) 11674984 >>> id(list.append.__doc__) 11747168 >>> id(list.append.__doc__) 11824352 >>> id(list.append.__doc__) 11747168 >>> id(list.append.__doc__) 11824352 >>> id(list.append.__doc__) 11747168 >>> id(list.append.__doc__) 11824352 >>> id(list.count.__doc__) 11863968 >>> id(list.count.__doc__) 11863968 >>> id(list.count.__doc__) 11863968 >>> id(list.count.__doc__) 11863968 From david at asdf.asdf Tue Sep 11 01:52:05 2007 From: david at asdf.asdf (bambam) Date: Tue, 11 Sep 2007 15:52:05 +1000 Subject: function to do dynamic import? Message-ID: <13ecb84p1ghrd64@corp.supernews.com> import works in the main section of the module, but does not work as I hoped when run inside a function. That is, the modules import correctly, but are not visible to the enclosing (global) scope. Questions: (1) Where can I read an explanation of this? (2) Is there a work around? BTW, sys.modules("filename") shows that the module is loaded, I just don't know how to use it when loaded that way. Also, if I import again at the global scope, the module name becomes available. Steve. --- >>> def gim(): ... exec "import gamel" ... >>> gim() >>> sys.modules["gamel"] >>>gamel NameError: name 'gamel' is not defined >>>exec "import gamel" >>>gamel From jjl at pobox.com Thu Sep 20 14:55:47 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 20 Sep 2007 18:55:47 GMT Subject: frange() question References: Message-ID: <87tzppjhe4.fsf@pobox.com> George Trojan writes: > A while ago I found somewhere the following implementation of frange(): > > def frange(limit1, limit2 = None, increment = 1.): > """ > Range function that accepts floats (and integers). > Usage: > frange(-2, 2, 0.1) > frange(10) > frange(10, increment = 0.5) > The returned value is an iterator. Use list(frange) for a list. > """ > if limit2 is None: > limit2, limit1 = limit1, 0. > else: > limit1 = float(limit1) > count = int(math.ceil(limit2 - limit1)/increment) > return (limit1 + n*increment for n in range(count)) > > I am puzzled by the parentheses in the last line. Somehow they make > frange to be a generator: >>> print type(frange(1.0, increment=0.5)) > Functions are never generators, senso stricto. There are "generator functions", which *return* (or yield) generators when you call them. It's true sometimes people refer to generator functions as simply "generators", but in examples like the above, it's useful to remember that they are two different things. In this case, frange isn't a generator function, because it doesn't yield. Instead, it returns the result of evaluating a generator expression (a generator). The generatator expression plays the same role as a generator function -- calling a generator function gives you a generator object; evaluating a generator expression gives you a generator object. There's nothing to stop you returning that generator object, which makes this function behave just like a regular generator function. John From steve at holdenweb.com Mon Sep 17 19:48:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Sep 2007 19:48:16 -0400 Subject: "once" assigment in Python In-Reply-To: <1190070620.926481.56620@k79g2000hse.googlegroups.com> References: <1189750616.597409.85380@w3g2000hsg.googlegroups.com> <1uSdnaFGwMuICHPbnZ2dnUVZ_tijnZ2d@comcast.com> <1190070620.926481.56620@k79g2000hse.googlegroups.com> Message-ID: Lorenzo Di Gregorio wrote: > On 17 Sep., 16:54, Larry Bates wrote: >> IMHO variables like what you describe are really data not program variables. >> You might consider putting variables like these in a dictionary and then check >> to see if the keys exist before assignment: >> >> var_dict={} >> >> # >> # See if 'varname' initialized, if not it needs to be >> # >> if 'varname' not in var_dict: >> var_dict[varname]=somevalue > > This is a good point! > > I could write something like: > > instantiate('component',function) > > and have instantiate() to conditionally do: > > instance['component']=Module(function) > > Of course this means using: > > instance['component'].method() > > instead of just: > > component.method() > Well, you could do that. Or you could define a class, with a __getattr__ that returns the required default value in the case where no setting had been made. Then you can assign components (with their own hierarchies) to the attributes of your top-level design ... > A more annoying difficulty is with the fact that, while the scope of > ordinary variables is limited (function, package), the scope of > 'component' would be global (the whole instance[]): having global > names could be pretty annoying in modeling a hierarchy. Anyway, some > scoping mechanism could be implemented over the global dictionary and > this could be a good price to pay to avoid other tricks. > Further suggestions? > It's not actually that hard to create objects that allow you to access their attributes using *either* attribute or indexing notation. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From pavlovevidence at gmail.com Fri Sep 28 19:15:22 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 28 Sep 2007 16:15:22 -0700 Subject: getopt with negative numbers? In-Reply-To: <87odfm3021.fsf@benfinney.id.au> References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <1190915197.390247.313590@57g2000hsv.googlegroups.com> <1190930134.780005.68510@22g2000hsm.googlegroups.com> <1190944143.521085.66910@g4g2000hsf.googlegroups.com> <871wcj4ib9.fsf@benfinney.id.au> <1190999036.588941.165610@g4g2000hsf.googlegroups.com> <87odfm3021.fsf@benfinney.id.au> Message-ID: <1191021322.905791.21300@r29g2000hsg.googlegroups.com> On Sep 28, 6:19 pm, Ben Finney wrote: > Steven Bethard writes: > > A user shouldn't have to go out of their way to specify regular > > numbers on the command line, regardless of whether they're positive > > or negative. > > A user shouldn't have to go out of their way to know whether what they > type on a command line will be treated as an option or an argument. I guess typing ./program --help is out of the question. Carl Banks From heikki at osafoundation.org Tue Sep 25 02:44:52 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Mon, 24 Sep 2007 23:44:52 -0700 Subject: M2Crypto 0.18 - new version, same old build bugs - more details In-Reply-To: <46F82296.5010701@animats.com> References: <46F82296.5010701@animats.com> Message-ID: John Nagle wrote: > But notice that the -D entry didn't appear on the SWIG command line. > Neither did the "-includeall". The "swig_opts" values around line > 129 aren't actually being used. I think that's left over from the code > intended > to allow builds with Python 2.3 and earlier. The "self.swig_opts" up at > line 53 of "setup.py" seems to be controlling. The patch was to > the obsolete code. Aha! Good find. I reopened https://bugzilla.osafoundation.org/show_bug.cgi?id=9404 and attached a patch that should address this for real this time. At least -includeall appears in my Ubuntu Dapper Drake environment. Could you give it a go and let me know how it works? -- Heikki Toivonen From rrr at ronadam.com Sat Sep 22 03:02:57 2007 From: rrr at ronadam.com (Ron Adam) Date: Sat, 22 Sep 2007 02:02:57 -0500 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <13f8unjjeqs5p97@corp.supernews.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <13f8unjjeqs5p97@corp.supernews.com> Message-ID: <46F4BE21.2050800@ronadam.com> Scott David Daniels wrote: > Cristian wrote: >> On Sep 21, 3:44 pm, Ron Adam wrote: >> >>> I think key may be to discuss names and name binding with your friend. > > Here's an idea: > > import math > > def sin_integral(start, finish, dx): > total = 0.0 > y0 = math.sin(start) > for n in range(1, 1 + int((finish - start) / float(dx))): > y1 = math.sin(start + n * dx) > total += (y0 + y1) > y0 = y1 > return total / 2. * dx > > > def cos_integral(start, finish, dx): > total = 0.0 > y0 = math.sin(start) > for n in range(1, 1 + int((finish - start) / float(dx))): > y1 = math.cos(start + n * dx) > total += (y0 + y1) > y0 = y1 > return total / 2. * dx > > generalize and separate the integration technique from the > function it integrates. How about this? It's based on the apple basic program example in How to Enjoy Calculus. Ron import math def integrate(fn, x1, x2, n=100): # Calculate area of fn using Simpson's rule. width = float(x2 - x1) / n area = fn(x1) if n % 2 != 0: # make sure its even n += 1 for n in range(1, n): x = x1 + n * width if n % 2 == 0: area += 2.0 * fn(x) else: area += 4.0 * fn(x) area += fn(x2) return area * (width / 3.0) def fn(x): return x**2 print "Area of fn:", integrate(fn, 0, 2) print "Area of cos fn:", integrate(math.cos, 1, 2) print "Area of sin fn:", integrate(math.sin, 1, 2) Area of fn: 2.66666666667 Area of cos fn: 0.0678264420216 Area of sin fn: 0.956449142468 From f.braennstroem at gmx.de Thu Sep 13 18:09:11 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Thu, 13 Sep 2007 22:09:11 +0000 Subject: extract text from log file using re In-Reply-To: References: Message-ID: me again... I should describe it better: the result should be an array with just: 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 as field values. Fabian Braennstroem schrieb am 09/13/2007 09:09 PM: > Hi, > > I would like to delete a region on a log file which has this > kind of structure: > > > #------flutest------------------------------------------------------------ > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > reversed flow in 1 faces on pressure-outlet 35. > > Writing > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.cas"... > 5429199 mixed cells, zone 29, binary. > 11187656 mixed interior faces, zone 30, binary. > 20004 triangular wall faces, zone 31, binary. > 1104 mixed velocity-inlet faces, zone 32, binary. > 133638 triangular wall faces, zone 33, binary. > 14529 triangular wall faces, zone 34, binary. > 1350 mixed pressure-outlet faces, zone 35, binary. > 11714 mixed wall faces, zone 36, binary. > 1232141 nodes, binary. > 1232141 node flags, binary. > Done. > > > Writing > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.dat"... > Done. > > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 > 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 > > reversed flow in 2 faces on pressure-outlet 35. > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > #------------------------------------------------------------------ > > I have a small script, which removes lines starting with > '(re)versed', '(i)teration' and '(t)urbulent' and put the > rest into an array: > > # -- plot residuals ---------------------------------------- > import re > filename="flutest" > reversed_flow=re.compile('^\ re') > turbulent_viscosity_ratio=re.compile('^\ tu') > iteration=re.compile('^\ \ i') > > begin_of_res=re.compile('>\ \ \ i') > end_of_res=re.compile('^\ ad') > > begin_of_writing=re.compile('^\Writing') > end_of_writing=re.compile('^\Done') > > end_number=0 > begin_number=0 > > > n = 0 > for line in open(filename).readlines(): > n = n + 1 > if begin_of_res.match(line): > begin_number=n+1 > print "Line Number (begin): " + str(n) > > if end_of_res.match(line): > end_number=n > print "Line Number (end): " + str(n) > > if begin_of_writing.match(line): > begin_w=n+1 > print "BeginWriting: " + str(n) > print "HALLO" > > if end_of_writing.match(line): > end_w=n+1 > print "EndWriting: " +str(n) > > if n > end_number: > end_number=n > print "Line Number (end): " + str(end_number) > > > > > > n = 0 > array = [] > array_dummy = [] > array_mapped = [] > > mapped = [] > mappe = [] > > n = 0 > for line in open(filename).readlines(): > n = n + 1 > if (begin_number <= n) and (end_number > n): > # if (begin_w <= n) and (end_w > n): > if not reversed_flow.match(line) and not > iteration.match(line) and not > turbulent_viscosity_ratio.match(line): > m=(line.strip().split()) > print m > if len(m) > 0: > # print len(m) > laenge_liste=len(m) > # print len(m) > mappe.append(m) > > > #--end plot > residuals------------------------------------------------- > > This works fine ; except for the region with the writing > information: > > #-----writing information > ----------------------------------------- > Writing "/home/fb/fluent-0500.cas"... > 5429199 mixed cells, zone 29, binary. > 11187656 mixed interior faces, zone 30, binary. > 20004 triangular wall faces, zone 31, binary. > 1104 mixed velocity-inlet faces, zone 32, binary. > 133638 triangular wall faces, zone 33, binary. > 14529 triangular wall faces, zone 34, binary. > 1350 mixed pressure-outlet faces, zone 35, binary. > 11714 mixed wall faces, zone 36, binary. > 1232141 nodes, binary. > 1232141 node flags, binary. > Done. > # -------end writing information ------------------------------- > > Does anyone know, how I can this 'writing' stuff too? The > matchingIt occurs a lot :-( > > Regards! > Fabian > From gherron at islandtraining.com Fri Sep 28 03:06:55 2007 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 28 Sep 2007 00:06:55 -0700 Subject: marshal bug? In-Reply-To: <1190961020.258850.215130@g4g2000hsf.googlegroups.com> References: <1190961020.258850.215130@g4g2000hsf.googlegroups.com> Message-ID: <46FCA80F.8050307@islandtraining.com> Anurag wrote: > I have been chasing a problem in my code since hours and it bolis down > to this > import marshal > marshal.dumps(str(123)) != marshal.dumps(str("123")) > > Can someone please tell me why? > when > str(123) == str("123") > > or are they different? > > it also means that > if s = str(123) > marshal.dumps(s) != marshal.dumps(marshal.loads(marshal.dumps(s))) > > rgds > Anurag > > Any string in Python can be "interned" or not, the difference being how/where the value is stored internally. The marshal module includes such information in its output. What you are doing is probably considered a misuse of the marshal module. I'd suggest using the pickle (or cPickle) modules instead. Here's the relevant part of the manual for marshal: version: Indicates the format that the module uses. Version 0 is the historical format, version 1 (added in Python 2.4) shares interned strings and version 2 (added in Python 2.5) uses a binary format for floating point numbers. The current version is 2 Gary Herron. From sjmachin at lexicon.net Sat Sep 15 06:33:52 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Sep 2007 03:33:52 -0700 Subject: trim start and trailing space chars from string In-Reply-To: References: Message-ID: <1189852432.173978.71370@19g2000hsx.googlegroups.com> On Sep 15, 7:24 pm, Konstantinos Pachopoulos wrote: > Hi, > is there something corresponding to the java String.trim() method, ie > trim start and trailing space/tab chars from string? > say convert " asdf " to "asdf"? http://docs.python.org/lib/string-methods.html From tec at knology.net Tue Sep 11 08:09:58 2007 From: tec at knology.net (Tim) Date: Tue, 11 Sep 2007 05:09:58 -0700 Subject: memcpy In-Reply-To: <5klnsbF3vfqqU10@mid.uni-berlin.de> References: <1189449530.171049.323230@22g2000hsm.googlegroups.com> <5klnsbF3vfqqU10@mid.uni-berlin.de> Message-ID: <1189512598.410810.224340@y42g2000hsy.googlegroups.com> On Sep 10, 3:31 pm, Marc 'BlackJack' Rintsch wrote: > On Mon, 10 Sep 2007 11:38:50 -0700, Tim wrote: > > How do I memcpy from a pointer to an array of floats in python? > > > I get errors: NameError: global name 'row' is not defined > > Well than the (global) name `row` is not defined. Quite clear message, > isn't it? ;-) > > > I want to be able to get the row[i] array element. In C I would > > normally place the address of row as the first argument. > > > cdll.msvcrt.memcpy( row, pData, 256 ) > > > If I define row as the following I also get the following error: > > > row = ones( TOTAL_PARAMETER_ENTRIES, dtype=float ) > > > ArgumentError: argument 1: : Don't know > > how to convert parameter 1 > > You don't give enough information so we have to guess. For example I > guess the `ones()` function comes from one of the packages `numeric`, > `numarray` or `numpy`!? > > This function returns a Python object. You can't use arbitrary Python > objects with `ctypes`. `memcpy` expects a pointer not an object. > > Ciao, > Marc 'BlackJack' Rintsch Can I initialize something in Python that I can get access to it's pointer? How about: self.data = TOTAL_OUTPUT_PARMETERS*[TOTAL_PARAMETER_ENTRIES*[c_float()] or self.data = TOTAL_OUTPUT_PARMETERS*[c_char_p("temp")] or self.data = [TOTAL_OUTPUT_PARMETERS*1.0]*TOTAL_PARAMETER_ENTRIES I need to be able to copy the contents of a pointer to shared memory into an array of floats so I can index into that array and see my data. I have a pointer to shared meory but I don't know how to access it. Here is what I would like to write: shared_memory_pointer = windll.kernel32.MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE) memcpy( self.data, shared_memory_pointer, my_size ) Thanks From aahz at pythoncraft.com Mon Sep 17 10:53:04 2007 From: aahz at pythoncraft.com (Aahz) Date: 17 Sep 2007 07:53:04 -0700 Subject: Un(der)documented bits of cgi.py References: Message-ID: In article , Bob Kline wrote: > >I'm trying to detect and intelligently deal with problems created when >a user of a Python CGI page uploads a file and then gets impatient >and clicks on some other button or the browser's cancel button (or >even closes the page). If the file is large enough, and the user is >impatient enough, this can result in the FieldStorage.file object >getting some, but not all of the bytes from the user's file, with no >documented means of detecting that this has happened. Poking around >in the code for cgi.py in the standard library, it appears that there >is an undocumented 'done' attribute which might be useful here (it >seems as if it might get set to -1 when this condition is encountered), >but of course one is reluctant to leave behind software which relies >on undocumented behavior of packages, since those bits have a way >of disappearing in the middle of the night, suddenly breaking one's >software. Can anyone think of a good reason why it would not be >desirable to expose a publicly documented means of detecting the >condition described above? What I suggest doing is submitting a doc patch to http://bugs.python.org/ explaining the ``done`` attribute with a note that you're not sure whether the attribute is intended to be undocumented. Alternatively, you might look in the svn logs to find out who added the ``done`` attribute and if they're still active in the Python community, ask them directly. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From s.rappard at gmail.com Tue Sep 11 14:35:00 2007 From: s.rappard at gmail.com (Sjoerd) Date: Tue, 11 Sep 2007 11:35:00 -0700 Subject: mod_python and pysvn In-Reply-To: <5ko2anF4iuuiU1@mid.individual.net> References: <1189525797.361829.69380@g4g2000hsf.googlegroups.com> <5ko2anF4iuuiU1@mid.individual.net> Message-ID: <1189535700.882545.253160@k79g2000hse.googlegroups.com> On Sep 11, 7:41 pm, Bjoern Schliessmann wrote: > Tim Golden wrote: > > Sjoerd wrote: > >> ClientError: Unable to open an ra_local session to URL > >> Unable to open repository 'file:///P:/tools/builds/repository' > > >> does anyone know how I can fix this? > > > Usually means that the process which Apache is running under > > (may well be LocalSystem) doesn't know about or doesn't have > > access to p:/tools etc. > > Isn't this an SVN client error? Seems to me that the repository URL > is invalid. > > Tim, try accessing the repository using svn list from the command > line. > > Regards, > > Bj?rn > > -- > BOFH excuse #350: > > paradigm shift...without a clutch Thank you both for your replies! I suspect that if I import the script that the script becomes local for apache Who tries to form the path. The actual command: client = Client() repLog = client.log("\\P:\\tools\builds\publish\\") I used an UNC path. The forming of the repository path must be inside the pysvn library. When I run the script via the command console it returns the right values. So I think what Tim replies is quite acurate! I'm going to try that tomorrow! Cheers! Sjoerd From martin at v.loewis.de Mon Sep 10 17:34:05 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 10 Sep 2007 23:34:05 +0200 Subject: Why zlib not included in Python tarball? In-Reply-To: References: Message-ID: <46E5B84D.5020803@v.loewis.de> > I need to install my own Python. I compiled Python 2.4.4 from sources. zlib > did not compile - it's not in the lib-dynload directory. > > I did not have this problem with any of my earlier Python compiles. I > routinely compile Python from source. > > What is the correct procedure for installing zlib from source into Python? Depends on the operating system and the Python version. On Unix, you need to install zlib first; if you install a precompiled zlib package, make sure you install the header files as well. Regards, Martin From massonmousson at gmail.com Fri Sep 14 01:11:10 2007 From: massonmousson at gmail.com (Thierry Masson) Date: Thu, 13 Sep 2007 22:11:10 -0700 Subject: Extending Python with C API In-Reply-To: References: <1189733193.3248.7.camel@localhost.localdomain> Message-ID: On 9/13/07, Carsten Haese wrote: >Your module C code uses an unknown function by the name of PyBuildValue. >The actual name of the function you mean is Py_BuildValue. Thank you so much, Carsten. I can't believe I missed that underscore! I'm posting the working code below in case it ever turns out to be useful for someone else who is new to the Python C API. (I also added the init function, which I forgot to include in my original post). I've verified that this code works on Red Hat Enterprise Linux ES release 3 (Taroon Update 8). Code for writing a C API Python Extension (cobbled together from so many online and printed sources that it's hard to know where to start with the acknowledgements): File gtestmodule.c: ============== #include "Python.h" /* First, a couple of C functions that do the real work */ /* In this test example, "real work" is perhaps exaggerating a little */ int GetInt(int iVal) { // Double the supplied value and pass it back return iVal * 2; } char* GetString(void) { return "This is the message"; } /* Now a couple of corresponding wrapper functions so that Python can get access to them */ /* Python requires this return data type and these arguments */ PyObject* gtestmodule_GetInt(PyObject* pSelf, PyObject* pArgs) { int x = 0, iRet = 0; /* Validate and assign the single integer argument (that's what GetInt() expects) */ /* The "i" means just one integer */ /* Two integers would be "ii"; an integer, a string, a float and a long would be "isdl" */ if (!PyArg_ParseTuple(pArgs, "i", &x)) return NULL; iRet = GetInt(x); return Py_BuildValue("i", iRet); } PyObject* gtestmodule_GetString(PyObject* pSelf, PyObject* pArgs) { char* szMsg = GetString(); return Py_BuildValue("s", szMsg); } /* Method table for mapping function names to wrapper functions */ static PyMethodDef gtestmoduleMethods[] = { {"GetInt", gtestmodule_GetInt, METH_VARARGS, "Description goes here"}, {"GetString", gtestmodule_GetString, METH_VARARGS, "Description goes here"}, {NULL, NULL} }; /* Module initialization function */ initgtestmodule(void) { Py_InitModule("gtestmodule", gtestmoduleMethods); } File setup.py: ========= # To build and install the module, use: python setup.py install # Running this will generate a library file (gtestmodule.so on Linux) # from distutils.core import setup, Extension setup(name = "gtestmodule", version = "1.0", maintainer = "your name here", maintainer_email = "you at yourdomain.com", description = "test module", ext_modules = [Extension("gtestmodule",[" gtestmodule.c"])], ) File test.py: ======== # Simple test routine to run after building the library file import gtestmodule print gtestmodule.GetInt(36); print gtestmodule.GetString(); -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolf_tracks at invalid.com Thu Sep 20 15:56:09 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 20 Sep 2007 19:56:09 GMT Subject: An Editor that Skips to the End of a Def In-Reply-To: <87hclpjm3a.fsf@rudin.co.uk> References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> Message-ID: Maybe I'll take a look. When I left the world of Unix/Linux 10 years ago, emacs went with it, as did vi. Paul Rudin wrote: > "W. Watson" writes: > >> Thanks, but no thanks. The learning curve is way too steep. > > Up to you but, these days emacs comes with all sorts of > pointing-clicky-menu-y type things - you don't really have to learn > anything to get started. > > (It even gives useful advice on top-posting if you use it as a news > client :/) -- Wayne Watson (Nevada City, CA) Web Page: From schilling.klaus at web.de Sun Sep 30 02:43:39 2007 From: schilling.klaus at web.de (Klaus Schilling) Date: Sun, 30 Sep 2007 08:43:39 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <13frd6vtarbee75@corp.supernews.com> Message-ID: <87lkao8xgk.fsf@web.de> Ken Tilton writes: > > Sure, but where does the infection thing come in? Suppose RMS > publishes a new library call add-42, whose api is add-42, inputs n, > outputs n+42, source left as an exercise, and Kenny decides he can use > it, it is great. Now if Kenny uses it in his commercial software, commercial software can be free as well, such as the GNU Ada compiler. > add-42 does not somehow become less free to ride 'neath the starry > skies above, don't fence me in. But RMS wants Kenny's hide. Nothing > Kenny wrote derived from add-42, but RMS wants it all. that's because it's immoral not to give it all > Kenny happened > to solve the traveling salesman problem and protein-folding and passed > the fricking Turing test by using add-42 wherever he needed 42 added > to a number, and RMS wants credit and ownership and control of it > all. He and his license shall now dictate access and use of all that > code. The handcuffs are on, and they are inscribed "free". of course they are free > > No wonder the GPL has gone nowhere. Freely. RMS reasonably wanted that > add-42 not get co-opted, but that in no way necessitated the land grab > that is GPL. The GPL is a gratuitous reach only fancifully justified > by wanting to ensure that open source remain open. which is necessary in a moral culture. Only an immoral culture may accept non-disclosure > So this has nothing > to do with freedom in /any/ sense of the word, it has to do with a > political agenda opposed to the idea of private property. > private property is unethical Klaus Schilling From george.sakkis at gmail.com Fri Sep 21 02:46:05 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 21 Sep 2007 06:46:05 -0000 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190330015.131971.265680@y42g2000hsy.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> Message-ID: <1190357165.381313.197910@19g2000hsx.googlegroups.com> On Sep 20, 7:13 pm, "mensana... at aol.com" wrote: > On Sep 20, 5:46 pm, Paul Hankin wrote: > > > > > On Sep 20, 10:59 pm, Python Maniac wrote: > > > > I am new to Python however I would like some feedback from those who > > > know more about Python than I do at this time. > > > > def scrambleLine(line): > > > s = '' > > > for c in line: > > > s += chr(ord(c) | 0x80) > > > return s > > > > def descrambleLine(line): > > > s = '' > > > for c in line: > > > s += chr(ord(c) & 0x7f) > > > return s > > > ... > > > Well, scrambleLine will remove line-endings, so when you're > > descrambling > > you'll be processing the entire file at once. This is particularly bad > > because of the way your functions work, adding a character at a time > > to > > s. > > > Probably your easiest bet is to iterate over the file using read(N) > > for some small N rather than doing a line at a time. Something like: > > > process_bytes = (descrambleLine, scrambleLine)[action] > > while 1: > > r = f.read(16) > > if not r: break > > ff.write(process_bytes(r)) > > > In general, rather than building strings by starting with an empty > > string and repeatedly adding to it, you should use ''.join(...) > > > For instance... > > def descrambleLine(line): > > return ''.join(chr(ord(c) & 0x7f) for c in line) > > > def scrambleLine(line): > > return ''.join(chr(ord(c) | 0x80) for c in line) > > > It's less code, more readable and faster! > > I would have thought that also from what I've heard here. > > def scrambleLine(line): > s = '' > for c in line: > s += chr(ord(c) | 0x80) > return s > > def scrambleLine1(line): > return ''.join([chr(ord(c) | 0x80) for c in line]) > > if __name__=='__main__': > from timeit import Timer > t = Timer("scrambleLine('abcdefghijklmnopqrstuvwxyz')", "from > __main__ import scrambleLine") > print t.timeit() > > ## scrambleLine > ## 13.0013366039 > ## 12.9461998318 > ## > ## scrambleLine1 > ## 14.4514098748 > ## 14.3594400695 > > How come it's not? Then I noticed you don't have brackets in > the join statement. So I tried without them and got > > ## 17.6010847978 > ## 17.6111472418 > > Am I doing something wrong? It has to do with the input string length; try multiplying it by 10 or 100. Below is a more complete benchmark; for largish strings, the imap version is the fastest among those using the original algorithm. Of course using a lookup table as Diez showed is even faster. FWIW, here are some timings (Python 2.5, WinXP): scramble: 1.818 scramble_listcomp: 1.492 scramble_gencomp: 1.535 scramble_map: 1.377 scramble_imap: 1.332 scramble_dict: 0.817 scramble_dict_map: 0.419 scramble_dict_imap: 0.410 And the benchmark script: from itertools import imap def scramble(line): s = '' for c in line: s += chr(ord(c) | 0x80) return s def scramble_listcomp(line): return ''.join([chr(ord(c) | 0x80) for c in line]) def scramble_gencomp(line): return ''.join(chr(ord(c) | 0x80) for c in line) def scramble_map(line): return ''.join(map(chr, map(0x80.__or__, map(ord,line)))) def scramble_imap(line): return ''.join(imap(chr, imap(0x80.__or__,imap(ord,line)))) scramble_table = dict((chr(i), chr(i | 0x80)) for i in xrange(255)) def scramble_dict(line): s = '' for c in line: s += scramble_table[c] return s def scramble_dict_map(line): return ''.join(map(scramble_table.__getitem__, line)) def scramble_dict_imap(line): return ''.join(imap(scramble_table.__getitem__, line)) if __name__=='__main__': funcs = [scramble, scramble_listcomp, scramble_gencomp, scramble_map, scramble_imap, scramble_dict, scramble_dict_map, scramble_dict_imap] s = 'abcdefghijklmnopqrstuvwxyz' * 100 assert len(set(f(s) for f in funcs)) == 1 from timeit import Timer setup = "import __main__; line = %r" % s for name in (f.__name__ for f in funcs): timer = Timer("__main__.%s(line)" % name, setup) print '%s:\t%.3f' % (name, min(timer.repeat(3,1000))) George From deets at nospam.web.de Thu Sep 13 04:36:06 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Sep 2007 10:36:06 +0200 Subject: Possible suggestion for removing the GIL References: <1189657576.772108.136550@d55g2000hsg.googlegroups.com> Message-ID: <5ksb3mF5828oU1@mid.uni-berlin.de> Prateek wrote: > Hi, > > Recently there was some talk on removing the GIL and even the BDFL has > written a blog post on it. > I was trying to come up with a scalable and backwards compatible > approach for how to do it. > > I've put my thoughts up in a blog post - and I'd really like to hear > what the community thinks of it. > Mainly it revolves around dedicating one core for executing > synchronized code and doing context switches instead of acquiring/ > releasing locks. Where is the gain? Having just one core doesn't give you true parallelism - which is the main reason behind the cries for a GIL-less Python. Diez From gregor.kling at its.fh-giessen.de Tue Sep 4 04:03:40 2007 From: gregor.kling at its.fh-giessen.de (Gregor Kling) Date: Tue, 04 Sep 2007 10:03:40 +0200 Subject: pickle error/instancemethod Message-ID: <46DD115C.2030408@its.fh-giessen.de> Hello, I have some of these nefarious pickle errors I do not understand, maybe some of you have a clue. This is what I get (nd is the object which I want to pickle [cPickle.dumps(nd,2)], with the printout of nd.__dict__): ERROR Error: Can't pickle : attribute lookup __builtin__.instancemethod failed, nd: {'dvzLogger': , '_DVZnetzDataBase__netzentries': [], '_DVZnetzDataBase__option_fqdn_alias': set(['a.b.c']), '_DVZnetzDataBase__admins': set([]), '_DVZnetzDataBase__aliasentries': []} I follow the hints on http://docs.python.org/lib/node318.html, so I do not understand the source of the problem. I do not try to pickle an instancemethod directly. The dict does apparently contains only top level tuples, lists, sets, and dictionaries, classes/instances. So if more Data is needed to analyse the problem - demand. gfk -- gfk -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 6145 bytes Desc: S/MIME Cryptographic Signature URL: From dimitri.pater at gmail.com Wed Sep 5 08:53:43 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Wed, 5 Sep 2007 14:53:43 +0200 Subject: StringIO MySQL data blob Image problem Message-ID: Hi, I am trying to insert an image, which is stored as a blob in MySQL, into a table using Reportlab. I have tried this: from StringIO import StringIO cfoto = StringIO(result[0][1]) # where result[0][1] is the 'blob' cfoto.seek(0) foto=cfoto.getvalue But when I do: print foto, I see something similar to this: array('c','\xff\xd8\............etc.......etc......') This is also the string I see in the table, in stead of the actual image. I have tried: cfoto StringIO() cfoto.write(result[0][1].tostring()) foto=cfoto.getvalue() that returns: ?????lbo?q?5???\???????Y|A???,???? "??m3Z???f??""N?,?????I??t"?b5?@xq?'?k????s??d???????1??? ?^?J?*?C(r)?{:t??_??????jo?? ?C(c)???[)?gN???X?i etc... etc... and return an UnicodeDecodeError when I try to insert this into the table Any ideas or clues someone? Your help is appreciated. Dimitri (BTW, the MySQL image blob is valid, it shows up in MySQL Query Browser) -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org From fabiofz at gmail.com Tue Sep 11 06:58:03 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 11 Sep 2007 07:58:03 -0300 Subject: Setting stdout encoding In-Reply-To: References: <1189416350.069995.220250@w3g2000hsg.googlegroups.com> Message-ID: > > You could place code like that on sitecustomize.py > I think this should be fixed on Eclipse/pydev. If they replace sys.stdout > with a different object - they should make sure it has the right behavior. > Same for IDLE if it's broken too. > Thanks for the tip... I wasn't aware of sitecustomize.py (site.py does call that just before removing setdefaultencoding() from sys, so I can still use sys.setdefaultencoding)... actually, setencoding() from site.py does have what I would like to execute: if 0: # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] I just don't get why the code has that "if 0:" instead of getting it from some user-config (like env variable or parameters passed)... Anyways, thanks a lot... I think I can arrange in providing a sitecustomize.py from pydev with that structure. Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From zunbeltz at gmail.com Fri Sep 7 09:08:19 2007 From: zunbeltz at gmail.com (zunbeltz at gmail.com) Date: Fri, 07 Sep 2007 06:08:19 -0700 Subject: exponential float formmating Message-ID: <1189170499.945175.275210@57g2000hsv.googlegroups.com> Hi, For compatibility reasons with an old program I have to format string in exponential format with the following format 0.xxxxxE-yy This means that the number start always by 0 and after the exponent there should be alway the sing and 2 number for the exponent. for example 13 shoud be 0.13000E+02 I always get 1.30000E001 Thanks, Zunbeltz From ldo at geek-central.gen.new_zealand Sat Sep 22 00:50:34 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 22 Sep 2007 16:50:34 +1200 Subject: Building Python with VC8 on x86-64 Vista References: <1190299551.573204.322440@57g2000hsv.googlegroups.com> Message-ID: In message <1190299551.573204.322440 at 57g2000hsv.googlegroups.com>, danfike at gmail.com wrote: > Though I don't know how useful it is, I did open the python libraries > in wordpad, and though most of the file wasn't legible, I did find > strings "Py_NoneStruct," "Py_RefTotal," and "PyExc_IndexError." Do you have some equivalent of the "nm" command for dumping the symbols and their definitions in the library? From iclark at mail.ewu.edu Fri Sep 14 18:50:44 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Fri, 14 Sep 2007 15:50:44 -0700 Subject: Spaces from string specifier In-Reply-To: References: <03a601c7f68b$ccdf1ed0$669d5c70$@com> Message-ID: Gabriel Genellina wrote: > En Fri, 14 Sep 2007 01:57:43 -0300, Gavin Tomlins > escribi???: > >> I'm trying to work out when using a format specifier I get spaces in the >> resulting string. Eg. Looking at the outputted string you can see that >> there are spaces after T5LAT, F4LAT etc. as I result from trying to keep >> the >> code aligned > > - You should *not* build the SQL text yourself; use a parametrised query > instead. It's not only easier to write; it's safer, less error prone, and > maybe faster. See this previous post > > > - Spaces are not significant in SQL, but you may have your own reasons to > format the SQL text in a certain way. In addition to the ideas already > menctioned on that thread (avoid \, use parenthesis, and auto-concatenate > adjacent strings), you may use a triple-quoted string + function dedent > from textwrap module: > > py> fmtSqlP300Amp = textwrap.dedent('''\ > ... UPDATE Patient SET > ... O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s", > ... P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s", > ... TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s" > ... WHERE Pat_Id = "%s"''') > py> print fmtSqlP300Amp > UPDATE Patient SET > O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s", > P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s", > TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s" > WHERE Pat_Id = "%s" > > I hope any of these ideas will fit your own needs. Completely agree that this should not be written by hand. But if you absolutely *must* you might try something like this: >>> fmt = """ ... UPDATE Patient SET ... 02AMP = "%(o2amp)s" ... O1AMP = "%(o1amp)s" ... ... ... """ >>> args = { ... 'o1amp': "2.77413", ... 'o2amp': "2.43119" ... } >>> print fmt % args UPDATE Patient SET 02AMP = "2.43119" O1AMP = "2.77413" ... >>> Ian From aahz at pythoncraft.com Tue Sep 18 12:08:37 2007 From: aahz at pythoncraft.com (Aahz) Date: 18 Sep 2007 09:08:37 -0700 Subject: Using pseudonyms (was Re: Python 3K or Python 2.9?) References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46ef893c$0$21882$426a34cc@news.free.fr> Message-ID: In article , Steve Holden wrote: >Aahz wrote: >> In article <46ef893c$0$21882$426a34cc at news.free.fr>, >> Bruno Desthuilliers wrote: >>> Aahz a ?crit : >>>> In article <46ee2d9d$0$26213$426a74cc at news.free.fr>, >>>> Bruno Desthuilliers wrote: >>>>> >>>>> But what, given that I'm an AOL user still thinking it's kewl to hide >>>>> behind a pseudo, what else would you expect ? >>>> >>>> What exactly is a "pseudo", pray tell? >>> >>> Sorry : a pseudonym (a nickname). >> >> You apparently missed the thrust of my sarcasm. You can't tell what is >> or is not a pseudonym online. For all I know, "Bruno Desthulliers" is a >> pseudonym. While I recognize that there is some social advantage to >> linking consistent identifiers with people, I have I think understandable >> irritation with people who insist that names follow certain patterns. >> >> (For those joining only recently, my full legal name is "Aahz", which I >> changed from my former name precisely because of attitudes like Bruno's.) > >... coupled with a certain bloody-mindedness that forces you to rub >people's noses in your ability to choose to do so? ;-) While there's certainly some truth to that, it is also the case that I have seen people like Bruno take exception to some people's born names. After all, there are people whose parents chose to name them "Moon Unit". For that matter, there are plenty of people who are better known by some nickname that is not their legal name. And even before I changed my name, I had plenty of problems from people believing that my name was a nickname and "helpfully" fixing it. (Which is really where my attitude comes from, and the practical difficulties of having only one legal name are not that much larger than my former difficulties.) Overall, I think that Bruno's attitude is more injurious to community than letting people be known by whatever name they choose. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From pavlovevidence at gmail.com Sat Sep 29 21:53:32 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Sep 2007 18:53:32 -0700 Subject: getopt with negative numbers? In-Reply-To: <87zlz510tw.fsf@benfinney.id.au> References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> <1190915197.390247.313590@57g2000hsv.googlegroups.com> <1190930134.780005.68510@22g2000hsm.googlegroups.com> <1190944143.521085.66910@g4g2000hsf.googlegroups.com> <871wcj4ib9.fsf@benfinney.id.au> <1190999036.588941.165610@g4g2000hsf.googlegroups.com> <87odfm3021.fsf@benfinney.id.au> <1191021322.905791.21300@r29g2000hsg.googlegroups.com> <87zlz510tw.fsf@benfinney.id.au> Message-ID: <1191117212.572680.36290@r29g2000hsg.googlegroups.com> On Sep 29, 7:58 pm, Ben Finney wrote: > Carl Banks writes: > > On Sep 28, 6:19 pm, Ben Finney > > wrote: > > > Steven Bethard writes: > > > > A user shouldn't have to go out of their way to specify regular > > > > numbers on the command line, regardless of whether they're > > > > positive or negative. > > > > A user shouldn't have to go out of their way to know whether what > > > they type on a command line will be treated as an option or an > > > argument. > > > I guess typing > > ./program --help > > > is out of the question. > > You're trying to have it both ways. > > You're saying the user "shouldn't have to go out of their way" to type > arbitrary arguments on the command line. No, I'm not. Don't put words in my mouth. I don't think it's "going out of your way" to read the documentation, or to put a couple hyphens on the line. Those were your words, and they were an utterly silly hyperbole. > Then, in your next message, > you suggest they must *read the detailed command-line help* in order > to know whether they *can* type arbitrary command-line arguments. You're writing a program that takes numerical positional arguments. Are you being more of asshole ir you A. Expect me to read the documentation, or B. Force me to type two hyphens every single time I want to enter a negative number? I would say B by a mile. Not that it's "going out of my way" to enter the extra hyphens; it's just irritating and completely, totally, and utterly unnecessary. > Is "learn about how the program expects options and arguments" within > your definition of "go out of their way", or isn't it? If it's not, > then "shouldn't have to go out of their way" is *not* an argument in > favour of special-casing negative-numbers. It's only a special case in your imagination. Try typing this: seq -9 -1 On my system, seq is a GNU tool, and the guys at the FSF are some of the biggest tightwads around when it comes to command line options. Even when they allow nonconformant options for the sake of backwards compatibility, they run a guilt trip on you. But even they see the practicality in allowing negative number arguments in some cases. Carl Banks From wolf_tracks at invalid.com Thu Sep 20 12:31:07 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 20 Sep 2007 16:31:07 GMT Subject: An Editor that Skips to the End of a Def Message-ID: Is there an editor that allows one to position to put the cursor and then by pushing some button goes to the end of the def? -- Wayne Watson (Nevada City, CA) Web Page: From andres.j.new at gmail.com Sun Sep 30 21:35:09 2007 From: andres.j.new at gmail.com (andresj) Date: Mon, 01 Oct 2007 01:35:09 -0000 Subject: Using fractions instead of floats Message-ID: <1191202509.853059.222530@k79g2000hse.googlegroups.com> I was doing some programming in Python, and the idea came to my mind: using fractions instead of floats when doing 2/5. The problem arises when you try to represent some number, like 0.4 in a float. It will tell you that it's equal to 0.40000000000000002. "This is easy to fix", you may say. "You just use the decimal.Decimal class!". Well, firsly, there would be an excess of typing I would need to do to calculate 0.4+0.6: from decimal import Decimal print Decimal("0.4")+Decimal("0.6") Secondly, what happens if I need to sum 1/3 and 0.4? I could use Decimal to represent 0.4 precisely, but what about 1/3? Sure, I could use _another_ class which works in a base (binary, decimal, octal, hexadecimal) in which 1/3 can be represented exactly... Not to mention the problem of operating with those two different classes... So the solution I think is using a fraction type/class, similar to the one found in Common Lisp. If you have used CLisp before, you only need to type: (+ 1/3 6/10) to get the exact result. (Yes, I also hate the (operator arg1 arg2) syntax, but it's just an example). I would like to have something similar in Python, in which dividing two numbers gives you a fraction, instead of an integer (python 2.x) or a float (decided for python 3.x). an implementation could be like this: class frac(object): # PS: This (object) thing will be removed in python 3.0, right? def __init__(self, numerator, denominator): pass def __add__(self, other): pass #... (I have an implementation of the frac class done (this meaning, it works for me), and although it's pretty dirty, I'd be happy to post it here if you want it.) My idea, in summary would be that this python shell session is true: >>> 5/2 2 1/2 >>> f = 5/2 >>> f.__class__ >>> # or >>> (0.6).__class__ # Treat decimal literals as fractions, so that... >>> 1/3+0.6 14/15 >>> # That was easy. ;) I would like to get some feedback on this idea. Has this been posted before? If so, was it rejected? and for what? Also, I would like to know if you have improvements on the initial design, and if it would be appropiate to send it as a PEP. From knipknap at gmail.com Mon Sep 3 16:01:54 2007 From: knipknap at gmail.com (Samuel) Date: Mon, 03 Sep 2007 13:01:54 -0700 Subject: Python object <-> XML Message-ID: <1188849714.128121.139450@r34g2000hsd.googlegroups.com> Hi, Say you have the following XML: item 1 item 2 my group Is there an easy way (i.e. without writing a sax/dom parser) to load this into a (number of) Python object(s), manipulate the instance, and save the result back to XML? -Samuel From tuomas.vesterinen at pp.inet.fi Tue Sep 4 15:54:57 2007 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Tue, 04 Sep 2007 19:54:57 GMT Subject: Undeterministic strxfrm? In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Tue, 04 Sep 2007 07:34:54 -0300, Tuomas > escribi?: > >> Python 2.4.3 (#3, Jun 4 2006, 09:19:30) >> [GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import locale >> >>> def key(s): >> ... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8') >> ... return locale.strxfrm(s.encode('utf8')) >> ... >> >>> first=key(u'maupassant guy') >> >>> first==key(u'maupassant guy') >> False >> >>> first >> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 >> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79' >> >> >>> key(u'maupassant guy') >> '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 >> $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5' >> >> >>> >> >> May be this is enough for a sort order but I need to be able to catch >> equals too. Any hints/explanations? > > > I can't use your same locale, but with my own locale settings, I get > consistent results: > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > py> import locale > py> locale.setlocale(locale.LC_COLLATE, 'Spanish_Argentina') > 'Spanish_Argentina.1252' > py> def key(s): > ... return locale.strxfrm(s.encode('utf8')) > ... Because I am writing a multi language application I need to plase the locale setting inside the key function. Actually I am implementing binary search in a locally sorted list of strings and should be able to count on stable results of strxfrm despite possibly visiting another locale at meantime. Could repeated calls to setlocale cause some problems? > py> first=key(u'maupassant guy') > py> print repr(first) > '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02 > > \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01' > py> print repr(key(u'maupassant guy')) > '\x0eQ\x0e\x02\x0e\x9f\x0e~\x0e\x02\x0e\x91\x0e\x91\x0e\x02\x0ep\x0e\x99\x07\x02 > > \x0e%\x0e\x9f\x0e\xa7\x01\x01\x01\x01' > py> print first==key(u'maupassant guy') > True > > Same thing with Python 2.4.4 > I get the same unstability with my locale 'fi_FI.utf8' too, so I am wondering if the source of the problem is the clib or the Python wrapper around it. Differences in strxfrm results for identical source are allways in the few latest bytes of the results. From bj_666 at gmx.net Fri Sep 7 19:17:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2007 23:17:55 GMT Subject: Speed of Python References: Message-ID: <5ke4h3F31i6hU9@mid.uni-berlin.de> On Fri, 07 Sep 2007 22:59:26 +0000, wang frank wrote: > I also have tried to use numpy to speed it up. However, surprisingly, it is > slower than the pure python code. > > Here is the code: > import numpy > arange=numpy.arange > nlog=numpy.log > def bench6(n): > for i in xrange(n): > for j in xrange(1000): > m=j+1 > z=nlog(m) > z1=nlog(m+1) > z2=nlog(m+2) > z3=nlog(m+3) > z4=nlog(m+4) > z5=nlog(m+5) > z6=nlog(m+6) > z7=nlog(m+7) > z8=nlog(m+8) > z9=nlog(m+9) > return z9 > > [?] > > Anyone know why? Because you don't really take advantage of `numpy`. The `numpy.log()` function can be used with scalars but I guess it is slower because it has to check if its argument is a scalar or array. Untested: from numpy import arange, log as nlog def bench6(n): for dummy in xrange(n): for j in xrange(1000): z = nlog(arange(j + 1, j + 11)) return z[-1] From gagsl-py2 at yahoo.com.ar Mon Sep 24 04:00:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Sep 2007 05:00:42 -0300 Subject: TRying to import files from my folder not pythons lib folder References: <1190395964.541835.114350@50g2000hsm.googlegroups.com> <1190396569.732154.234270@r29g2000hsg.googlegroups.com> <1190595699.093793.100960@w3g2000hsg.googlegroups.com> Message-ID: En Sun, 23 Sep 2007 22:01:39 -0300, Luis M. Gonz?lez escribi?: > This is exactly what I did, but I have a new problem now: > After seting PYTHONPATH I'm no longer able to start IDLE from the > start menu. > It seems the system cannot find the file. > But if I eliminate PYTHONPATH, everything works as it used to. > > I set PYTHONPATH because I wanted to import any existing file in my > desktop without having to use sys.path.append... > It works when using the command line but strangely, something get > messed up with IDLE. > Any hint? Perhaps a python module in your desktop has a name conflicting with a standard module? - On the Start menu, navigate to the IDLE item, but dont click it. - RIGHT click on it, and select Properties. Copy the Destination field. Should be something like "C:\Python25\Lib\idlelib\idle.bat" - Open a cmd window (console), paste the above text and press Enter. - Almost certainly you'll get an error; post here the full error and traceback. -- Gabriel Genellina From madzientist at gmail.com Tue Sep 11 13:38:42 2007 From: madzientist at gmail.com (madzientist) Date: Tue, 11 Sep 2007 10:38:42 -0700 Subject: Python code-writing for the blind. Was (Re: newbie: stani's python editor if-else) In-Reply-To: References: <1189484688.520933.25000@22g2000hsm.googlegroups.com> <46e6aa30$0$22433$426a74cc@news.free.fr> <1189531123.283413.160870@22g2000hsm.googlegroups.com> Message-ID: <1189532322.708734.274470@r29g2000hsg.googlegroups.com> Thanks, Gregor. Very helpful thread. Suresh On Sep 11, 1:26 pm, Gregor Horvath wrote: > madzientist schrieb: > > > > > Is Python a bad choice for the blind programmer, as a result of a > > tight linkage between visual aspects of the code and its function ? I > > wish the site blindprogramming.com weren't so lifeless... > > There was a thread regarding blind people and python indentation shortly: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Gregor From __peter__ at web.de Wed Sep 12 07:56:22 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Sep 2007 13:56:22 +0200 Subject: Get Only the Last Items in a Traceback References: <1189562968.529414.27910@w3g2000hsg.googlegroups.com> Message-ID: Am Wed, 12 Sep 2007 11:21:48 +0200 schrieb Michael Str?der: > gregpinero at gmail.com wrote: >> I'm running code via the "exec in context" statement within a much >> larger program. What I would like to do is capture any possible >> errors and show a pretty traceback just like the Python interactive >> interpreter does, but only show the part of the traceback relating to >> the code sent to exec. >> >> For example here is the code I'm using: >> >> try: >> exec code >> except Exception,Err: >> traceback.print_exc() > > Guess what's argument limit is for. Excerpt from the Python docs: Unfortunately traceback.print_exc(limit=N) trims the wrong end of the traceback: >>> def alpha(): beta() ... >>> def beta(): gamma() ... >>> def gamma(): 1/0 ... >>> try: ... alpha() ... except: ... traceback.print_exc() ... Traceback (most recent call last): File "", line 2, in File "", line 1, in alpha File "", line 1, in beta File "", line 1, in gamma ZeroDivisionError: integer division or modulo by zero >>> try: ... alpha() ... except: ... traceback.print_exc(limit=1) ... Traceback (most recent call last): File "", line 2, in ZeroDivisionError: integer division or modulo by zero >>> Peter From carsten at uniqsys.com Thu Sep 13 15:13:15 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 13 Sep 2007 15:13:15 -0400 Subject: Quick Modules question In-Reply-To: References: Message-ID: <1189710795.3407.11.camel@dot.uniqsys.com> On Thu, 2007-09-13 at 14:01 -0500, Lamonte Harris wrote: > How do you import modules that aren't in the main python Lib folder? > Is it possible to keep it in the same file as the script thats being > ran? See http://docs.python.org/tut/node8.html#SECTION008110000000000000000 and http://catb.org/~esr/faqs/smart-questions.html#before . -- Carsten Haese http://informixdb.sourceforge.net From gregturn at mindspring.com Wed Sep 12 08:25:38 2007 From: gregturn at mindspring.com (Goldfish) Date: Wed, 12 Sep 2007 05:25:38 -0700 Subject: Spring Python 0.3.0 is released! Message-ID: <1189599938.930862.308330@g4g2000hsf.googlegroups.com> Spring Python (http://springpython.python-hosting.com) version 0.3.0 was released yesterday. Key improvements include: * Make the web components WSGI-compatible, firstly working with CherryPy. * Extend PetClinic to use database accounts and have password encoding. * Add an ExceptionTranslationFilter so PetClinic handles errors more sophisticated. * Relicense Spring Python underneath GPLv3. * Generally, clean up the code and test cases. Also start using code coverage tools to improve quality of testing. From mail at timgolden.me.uk Thu Sep 20 11:29:36 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 20 Sep 2007 16:29:36 +0100 Subject: Python-list Digest, Vol 48, Issue 301 In-Reply-To: <200709201724.23611.cscheit@lstm.uni-erlangen.de> References: <200709201724.23611.cscheit@lstm.uni-erlangen.de> Message-ID: <46F291E0.40000@timgolden.me.uk> Christoph Scheit wrote: > Hello, > > is there a way to do something like > for i,j in l1, l2: > print i,j I'm assuming that l1 and l2 are in fact lists (or at least sequences). If that's the case: l1 = [1, 2, 3] l2 = ['a', 'b', 'c'] for i, j in zip (l1, l2): print i, j TJG From ricaraoz at gmail.com Sun Sep 2 13:55:57 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 14:55:57 -0300 Subject: localizing a sort In-Reply-To: <1i3t4p6.12j3kffgcfjoN%aleax@mac.com> References: <1i3t4p6.12j3kffgcfjoN%aleax@mac.com> Message-ID: <46DAF92D.3030000@bigfoot.com> Alex Martelli wrote: > Ricardo Ar?oz wrote: >> Peter Otten wrote: > ... >>>>>>> print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y))) >>>> aeiou??????????????? >>> The lambda is superfluous. Just write cmp=locale.strcoll instead. >> No it is not : >>>>> print ''.join(sorted(a, cmp=locale.strcoll(x,y))) >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: strcoll expected 2 arguments, got 0 >> >> You need the lambda to assign both arguments. > > No, your mistake is that you're CALLING locale.strcoll, while as Peter > suggested you should just PASS it as the cmp argument. I.e., > > ''.join(sorted('ciao', cmp=locale.strcoll)) > > Using key=locale.strxfrm should be faster (at least when you're sorting > long-enough lists of strings), which is why strxfrm (and key=...:-) > exist in the first place, but cmp=locale.strcoll, while usually slower, > is entirely correct. That lambda _IS_ superfluous, as Peter said. > > > Alex Got it! And it is MUCH more elegant than my code. Thanks. From blackmh at gmail.com Sun Sep 2 14:04:04 2007 From: blackmh at gmail.com (Kveldulv) Date: Sun, 02 Sep 2007 11:04:04 -0700 Subject: Glade + Python = No GUI In-Reply-To: <46daf2de$0$4530$9b4e6d93@newsspool3.arcor-online.net> References: <1188750465.530463.271750@22g2000hsm.googlegroups.com> <46daf2de$0$4530$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <1188756244.873383.54490@d55g2000hsg.googlegroups.com> On Sep 2, 7:29 pm, Wildemar Wildenburger wrote: > > Shouldnt there be more to that error message of yours? I would expect > something like "NameError: name 'gtk' is not defined"? > > Because as it seems you haven't impored gtk (only gtk.glade). So adding > "import gtk" at the beginning should help. > > I may be wrong; I recall some weird importing requirements for pygtk, so > I'm not sure if I'm to uninformed to see the actual problem. > > /W Nope, everything imports well, no errors. With import gtk added, I get the same thing... From chris.monsanto at gmail.com Fri Sep 21 17:48:02 2007 From: chris.monsanto at gmail.com (chris.monsanto at gmail.com) Date: Fri, 21 Sep 2007 21:48:02 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> Message-ID: <1190411282.060772.289270@y42g2000hsy.googlegroups.com> On Sep 21, 5:37 pm, Cristian wrote: > A friend of mine is an engineer and he's been needing to do more and > more programming as he goes on with is career. I convinced him to > learn Python instead of Perl and he's really started to like it. He > usually comes to me when he can't accomplish a task with his current > knowledge and I introduce him to a new feature in Python. FYIW, he > thought List Comprehensions were freakin' awesome. He's started > writing his own personal scripts for tasks like web scraping. So, from > personal experience, Python truly is a great first language to learn. > > Although his learning experience has gone mostly smoothly, he's hit a > lot of speed bumps with functions. Specifically, he's having trouble > thinking of functions as first order data (don't worry, I haven't > confused him with such terminology yet). He had a little trouble > understanding that you can pass functions as arguments to other > functions (e.g., passing a key to the list.sort method). He also had a > little trouble grasping functions within other functions. Last but not > least, he had trouble grasping methods in class declarations, > especially the required self as the first argument (I'm sure he wasn't > the first). > > Now, my friend's a smart guy so I know it isn't any lack of brain > cells on his part. I still remember many students in my CS classes > having trouble grasping the very same concept. And, after we finally > get a hold of first order functions, we appreciate its incorporation > into languages. It would be a shame if my friend just learns the > motions and never incorporates first order functions into his > programs. I began to wonder if there was anything Python could do to > help newcomers grasp the power of first order functions or, as > Pythonistas put it, everything is an object. > > To me, the biggest setback for new programmers is the different syntax > Python has for creating functions. Instead of the common (and easy to > grasp) syntax of foo = bar Python has the def foo(): syntax. So, when > a new programmer is first introduced to functions they are immediately > confronted with the notion that functions are "different". After all, > they have their own special syntax. This seems to only further the > separation newbies make between "data" and "functions" or "stuff" and > "actions". Now, the vast majority of us learned this dichotomy when we > first began to program, so we are ingrained to assume and even expect > a different syntax for function declaration, but in a program like > Python there doesn't seem to be any other reason to have it. > Furthermore, I think it actually inhibits the learning of the > uninitiated. We can, of course, keep the current syntax as sugar. > > To someone who's learning to program wouldn't a syntax like the > further give them all they need and also reinforces the idea that > functions are data just like everything else? > > my_function = function(foo, bar): pass > an_instance_method = function(self, foo): pass > a_method_declaration = method(self, foo): pass > > The last one is mostly my pet peeve of having Python "magically" > create methods out of (what is essentially) a function declaration. > When I first learned it, it felt wrong but you had to press through it > because there was really no other way of declaring methods. > > What do you think? Have you hit this roadblock when helping others > learn Python? Does the current syntax make you feel that functions are > still treated as second class (get it?) citizens? There are already anonymous functions in Python. lambda x, y, z: x + y + z is the same as: def _(x, y, z): return x + y + z As for the method stuff, check out staticmethod(). If you assign staticmethod() to an object, it will be treated as a normal function and not as a "method." I have my own personal opinions about how methods should be in Python, but, whatever. It's weird to deal with stuff like this: x.y = re.match # Assign a function to an attribute of a class, but it doesn't work because you can't assign anything but methods! x.y = staticmethod(re.match) # Ugly From steve at REMOVE-THIS-cybersource.com.au Sat Sep 1 03:52:21 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 01 Sep 2007 07:52:21 -0000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> <6ftgd35rd1g4mddqg2f44d7svd4r85ev17@4ax.com> <13dhvs3p5drsd99@corp.supernews.com> <87ejhic0iv.fsf@benfinney.id.au> Message-ID: <13di6hlnl7hhnfd@corp.supernews.com> On Sat, 01 Sep 2007 17:23:04 +1000, Ben Finney wrote: > Dennis Lee Bieber writes: > >> I suppose you also add an extra "i" to aluminum > > We're not out to rewrite the table of elements. There's no such thing as > "aluminum", and "aluminium" always has just the two "i"s. Although aluminium is the one and only correct spelling *grins*, it is not actually true that it has always been spelt that way (or for you Merkins out there, spelled). The discoverer of aluminium, Sir Humphrey Davy, originally spelt it alumium, then aluminum, and finally standardized on aluminium. http://www.worldwidewords.org/articles/aluminium.htm -- Steven. From steve at holdenweb.com Sat Sep 1 08:38:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Sep 2007 08:38:12 -0400 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> Message-ID: <46D95D34.9010906@holdenweb.com> Bryan Olson wrote: > Steve Holden wrote: > [...] >> If I can blow my own trumpet briefly, two customers (each using over 25 >> kLOC I have delivered over the years) ran for two years while I was away >> in the UK without having to make a single support call. One of the >> systems was actually locked in a cupboard all that time (though I have >> since advised that client to at least apply OS patches to bring it up to >> date). > >> This was achieved by defensive programming, understanding the user >> requirements and just generally knowing what I was doing. > > On the one hand, nice work. Made your customers happy and kept > them happy. Can't argue with success. On the other hand, 25K lines > is tiny by software engineering standards. If a support call would > have to go to you, then the project must be small. Software > engineering is only a little about an engineer knowing or not > knowing what he or she is doing; the bigger problem is that > hundreds or thousand of engineers cannot possibly all know what > all the others are doing. > I agree that programming-in-the-large brings with it problems that aren't experienced in smaller scale projects such as the ones I mentioned. > I work on large and complex systems. If I screw up -- O.K., face > facts: *when* I screw up -- the chance of the issue being assigned > to me is small. Other engineers will own the problems I cause, > while I work on defects in code I've never touched. I wish I could > own all my own bugs, but that's not how large and complex systems > work. Root-cause analysis is the hard part. By the time we know > what went wrong, 99.99% of the work is done. > This is the kind of realism I like to see in engineering. I am always suspicious when any method is promoted as capable of reducing the error rate to zero. > > Design-by-contract (or programming-by-contract) shines in large > and complex projects, though it is not a radical new idea in > software engineering. We pretty much generally agree that we want > strong interfaces to encapsulate implementation complexity. > That's what design-by-contract is really about. > > There is no strong case for adding new features to Python > specifically for design-by-contract. The language is flexible > enough to support optionally-executed pre-condition and > post-condition checks, without any extension. The good and bad > features of Python for realizing reliable abstraction are set > and unlikely to change. Python's consistency and flexibility > are laudable, while duck-typing is a convenience that will > always make it less reliable than more type-strict languages. > Python's dynamic nature certainly makes it more difficult to reason about programs in any formal sense. I've always thought of it as a pragmatist's language, and we need to be pragmatic about the downside as well as the upside. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From ed at leafe.com Wed Sep 12 19:55:11 2007 From: ed at leafe.com (Ed Leafe) Date: Wed, 12 Sep 2007 19:55:11 -0400 Subject: Python Database Apps In-Reply-To: <1189608814.932322.301950@22g2000hsm.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> <1189536987.259907.68650@e34g2000pro.googlegroups.com> <1189608814.932322.301950@22g2000hsm.googlegroups.com> Message-ID: <15503997-EB3C-4A1E-A27A-ED48F09F505E@leafe.com> On Sep 12, 2007, at 10:53 AM, darien.watkins at gmail.com wrote: > Thanks for ideas Ed. I am checking out dabo now. I do have a few > questions about it. Packaging. Is it easy to package into a quick > install for windows. The users are going to want to get too in > depth. py2exe is your friend here. I know several developers who have used this to distribute Dabo apps, so we could certainly help you get your setup.py working. > Second, data sources. When I'm adding a data source to the > window in class designer, it always picks up the one I created (which > incidentally was a sample, my form for connection manager isn't > working at the moment.) My idea is to have the the local sqlite > database as the only viewable data source, and the server side only > for syncing. So they logon, sync up, sync down, and view. I'm > worried about having to get them to install python, dabo, and the app. The users would never see any of the Class Designer, connection editor, or any of the other development tools. I would imagine that you would need to code the sync parts by getting the current changed data from the local SQLite database, creating a connection to the server DB, doing the insert/update as needed, grabbing the latest from the server, disconnecting from the server, and then updating the local data. The user would probably need to do nothing more than click a button to start running your code. As far as what the user must install, that's what will happen with any Python solution. py2exe takes care of all of that, bundling Python, Dabo, your database modules, and any other dependencies into a single .exe file. You can then use something like Inno Setup to create a basic Installer that will look and work like any other Windows application installer. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From paul.hankin at gmail.com Wed Sep 19 12:04:37 2007 From: paul.hankin at gmail.com (paulhankin) Date: Wed, 19 Sep 2007 16:04:37 -0000 Subject: Quick shallow-copy idiom In-Reply-To: References: Message-ID: <1190217877.723092.117630@o80g2000hse.googlegroups.com> On Sep 19, 10:48 am, Lawrence D'Oliveiro wrote: > y = type(x)(x) Nice trick, but is it better than the explicit: y = copy.copy(x) (I think not, because copy.copy works for example, on classes which take more than one argument to their constructor). -- Paul Hankin From arkanes at gmail.com Wed Sep 12 11:20:11 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 12 Sep 2007 10:20:11 -0500 Subject: Is the wxPython list down? In-Reply-To: <1189603681.292154.186620@o80g2000hse.googlegroups.com> References: <1189602607.803546.180320@w3g2000hsg.googlegroups.com> <1189603681.292154.186620@o80g2000hse.googlegroups.com> Message-ID: <4866bea60709120820v7f20f3f4k2cb89a2c7377b4e8@mail.gmail.com> On 9/12/07, Frank Millman wrote: > On Sep 12, 3:10 pm, kyoso... at gmail.com wrote: > > Hi, > > > > Does anyone know if the wxPython mailing list is having issues? I > > subscribe to it and haven't seen anything come through since > > 09/06/2007. I went to ActiveState's archives and the last message > > there is from the 7th (http://aspn.activestate.com/ASPN/Mail/Browse/ > > Threaded/wxPython-users). > > > > Thanks, > > > > Mike > > This is from the wxPython home page - > > "(8-Sept-2007) Yes, the mail lists are down. There were multiple disk > failures in RAID5 array of the machine that hosts the mail lists. The > hardware has been replaced and data is being restored from tape > backups." > > I noticed that cvs seems to be down as well - maybe it was on the same > server. > CVS is down because wx has moved to SVN, which is still up and running fine. svn.wxwidgets.org. From grante at visi.com Sat Sep 29 12:38:49 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 29 Sep 2007 16:38:49 -0000 Subject: Program inefficiency? References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> <13fss68juscn33@corp.supernews.com> <1191080844.248426.316340@g4g2000hsf.googlegroups.com> Message-ID: <13fsvsp6p743qba@corp.supernews.com> On 2007-09-29, hall.jeff at gmail.com wrote: > I'm not sure what an shell+sed script is... http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_05_01.html#sect_05_01_01 http://tldp.org/LDP/Bash-Beginners-Guide/html/chap_05.html http://www.grymoire.com/Unix/Sed.html http://www.gnu.org/software/bash/ http://en.wikipedia.org/wiki/Bash Unfortuantely it appears you're using Windows (a partucular bad choice for this sort of file processing). You can, however, get bash and sed for Windows if you wish: http://www.cygwin.com/ > In case it helps... We started with only 6 loops of replacecycle() but > had to keep adding progressively more as we found more and more links > with lots of spaces in them... I would think with the correct RE's you'd only have to call it once. > As we did that, the program's time grew progressively longer > but the length grew multiplicatively with the added number of > cycles... This is exactly what I would have expected and it > leads me to believe that the problem does not lie in the > replacecycle() def but in the masseditor() def... *shrug* As the program runs on progressively more files does the process's memory usage grow without bounds? Does the machine start swapping? -- Grant Edwards grante Yow! I'm pretending that at we're all watching PHIL visi.com SILVERS instead of RICARDO MONTALBAN! From evan at yelp.com Tue Sep 18 00:42:41 2007 From: evan at yelp.com (Evan Klitzke) Date: Mon, 17 Sep 2007 21:42:41 -0700 Subject: super() doesn't get superclass In-Reply-To: <8764281uea.fsf@benfinney.id.au> References: <8764281uea.fsf@benfinney.id.au> Message-ID: <1190090561.5759.8.camel@thinkpad> On Tue, 2007-09-18 at 14:15 +1000, Ben Finney wrote: > Howdy all, > > After banging my head against super() trying to reliably get > attributes of a superclass, I gained a little enlightenment when this > turned up in a search: > > "Python's Super is nifty, but you can't use it > (Previously: Python's Super Considered Harmful)" > > > An early paragraph stood out that made my current problems clear: > > One big problem with 'super' is that it sounds like it will cause > the superclass's copy of the method to be called. This is simply > not the case, it causes the next method in the MRO to be called. > > Oh. The author's right, I got that mistaken impression too. Obviously, > then, I must have misread the documentation of 'super'. I went back to > double-check, and was appalled to find: > > super(type[, object-or-type]) > Return the superclass of type. [...] > > > > Why does the documentation of 'super' say that it returns the > superclass when *that's not true*? It doesn't return the superclass, > it returns the next class in the MRO, whether that's a superclass or > not. The next class in the MRO _is_ a superclass. Maybe not the way you've defined it in your own code, but certainly of the new class you created with MI. > Actually, even that's not true. The error message "AttributeError: > 'super' object has no attribute 'bazfunc'" makes it clear that 'super' > actually returns not the superclass, but a 'super' object, whatever > that's supposed to be. No, super really does return a class. What makes you think that super returns a special sort of object? > After reading the rest of the article, I'm amazed that 'super' as > currently implemented is in Python at all. I agree with the author > that it's useless unless *everyone* uses it for *everything*, and even > then it's pretty limited. I don't see what the problem is. If you don't use super, then you can break the inheritance chain, but this is no different than calling superclass methods by passing in self (i.e. the old-style way of doing it), and in fact using super is far more flexible. There's no way to magically know when to call the superclass' method, and even if you knew when, there's no way to magically know when it needs to be called. If you're using multiple inheritance, and you're _not_ using super everywhere, then your code is broken anyway. Use super correctly in your own code, and you don't need to worry about other people using it incorrectly. -- Evan Klitzke From duncan.booth at invalid.invalid Sun Sep 9 06:06:59 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Sep 2007 10:06:59 GMT Subject: Python syntax wart References: <13e7ddd9hgibae6@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sun, 09 Sep 2007 17:16:05 +1200, Lawrence D'Oliveiro wrote: > >> The one thing I don't like about Python syntax is using backslashes to >> continue lines. > > Then don't use them. Put everything in one long line. > > Or do something like this. Instead of > > for Link in GetEachRecord("lots", "and", "lots", "of", "arguments"): > > you can do this: > > args = ("lots", "and", "lots", "of", "arguments") > for Link in GetEachRecord(*args): > Or even just: records = GetEachRecord("lots", "and", "lots", "of", "arguments") for link in records: ... From spammehere at gmx.com Thu Sep 20 15:28:36 2007 From: spammehere at gmx.com (Michael v. Fondern) Date: Thu, 20 Sep 2007 21:28:36 +0200 Subject: An Editor that Skips to the End of a Def In-Reply-To: References: Message-ID: <46f2c9c0$0$7365$a9611f8e@news.cityweb.de> W. Watson: > Is there an editor that allows one to position to put the cursor and > then by pushing some button goes to the end of the def? Eclipse, together with the pydev plugin. (Ctrl-Shift-Down) Greetings - Michael - From ldo at geek-central.gen.new_zealand Sat Sep 1 02:56:59 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 18:56:59 +1200 Subject: ANN: SCF released GPL References: <2qnAi.21495$eY.19028@newssvr13.news.prodigy.net> <7x3ay5d1mn.fsf@ruckus.brouhaha.com> Message-ID: In message <7x3ay5d1mn.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > hg writes: > >> I am looking for a free subversion server resource to put the code >> ... if you know of any. > > Does it have to be SVN? I think Savannah and Sourceforge both still > use CVS. Why would you want to use CVS rather than Subversion? From steve at REMOVE-THIS-cybersource.com.au Sat Sep 8 05:44:24 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Sep 2007 09:44:24 -0000 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <13e2jdobu2kqkf1@corp.supernews.com> Message-ID: <13e4rno5qal6h4b@corp.supernews.com> On Sat, 08 Sep 2007 10:07:14 +0200, Peter Otten wrote: > Am Fri, 07 Sep 2007 13:10:16 +0000 schrieb Grant Edwards: > >> On 2007-09-07, Peter Otten <__peter__ at web.de> wrote: >>> Am Fri, 07 Sep 2007 10:40:47 +0000 schrieb Steven D'Aprano: >>> >>>> Python doesn't have any pointers. >>> >>> Thinking of python variables or "names" as pointers should get you a >>> long way when trying to understand python's behaviour. >> >> But thinking of them as names bound to objects will get you further >> (and get you there faster). ;) > > Understanding a new system in terms of one I already know works for me. > When terminology and the system it describes make a perfect fit that is > a strong indication that you have reached a dead end. Ways that Python objects are not like C pointers: (1) You don't have to manage memory yourself. (2) You don't have typecasts. You can't change the type of the object you point to. (3) Python makes no promises about the memory location of objects. (4) No pointer arithmetic. (5) No pointers to pointers, and for old-school Mac programmers, no handles. (6) No dangling pointers. Ever. (7) There's no null pointer. None is an object, just like everything else. (8) You can't crash your computer by writing the wrong thing to the wrong pointer. You're unlikely even to crash your Python session. Ways that Python objects are like pointers: (1) ... um... Oh yeah, if you bind the _same_ object to two different names, _and_ the object is mutable (but not if it is immutable), mutating the object via one name will have the same effect on the object -- the same object, naturally -- bound to the other name. You know, maybe because I came to Python with no C experience, I never had trouble with the "unexpected behaviour" that so confused the original poster. It's just obvious. -- Steven. From esosman at ieee-dot-org.invalid Thu Sep 27 22:43:44 2007 From: esosman at ieee-dot-org.invalid (Eric Sosman) Date: Thu, 27 Sep 2007 22:43:44 -0400 Subject: Traveling Europe In-Reply-To: <1190907679.164542.149190@19g2000hsx.googlegroups.com> References: <1190907679.164542.149190@19g2000hsx.googlegroups.com> Message-ID: freeaircon at gmail.com wrote: > World's most popular traveling destinations > > http://... "Nobody goes there any more; it's too crowded." -- LPB -- Eric Sosman esosman at ieee-dot-org.invalid From mensanator at aol.com Sun Sep 30 22:35:44 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 30 Sep 2007 19:35:44 -0700 Subject: Using fractions instead of floats In-Reply-To: <1191202509.853059.222530@k79g2000hse.googlegroups.com> References: <1191202509.853059.222530@k79g2000hse.googlegroups.com> Message-ID: <1191206144.339867.134820@d55g2000hsg.googlegroups.com> On Sep 30, 8:35?pm, andresj wrote: > I was doing some programming in Python, and the idea came to my mind: > using fractions instead of floats when doing 2/5. > > The problem arises when you try to represent some number, like 0.4 in > a float. It will tell you that it's equal to 0.40000000000000002. > "This is easy to fix", you may say. "You just use the decimal.Decimal > class!". Well, firsly, there would be an excess of typing I would need > to do to calculate 0.4+0.6: > > from decimal import Decimal > print Decimal("0.4")+Decimal("0.6") > > Secondly, what happens if I need to sum 1/3 and 0.4? I could use > Decimal to represent 0.4 precisely, but what about 1/3? Sure, I could > use _another_ class which works in a base (binary, decimal, octal, > hexadecimal) in which 1/3 can be represented exactly... Not to mention > the problem of operating with those two different classes... > > So the solution I think is using a fraction type/class, similar to the > one found in Common Lisp. If you have used CLisp before, you only need > to type: > (+ 1/3 6/10) > to get the exact result. (Yes, I also hate the (operator arg1 arg2) > syntax, but it's just an example). I would like to have something > similar in Python, in which dividing two numbers gives you a fraction, > instead of an integer (python 2.x) or a float (decided for python > 3.x). > > an implementation could be like this: > class frac(object): # PS: This (object) thing will be removed in > python 3.0, right? > def __init__(self, numerator, denominator): > pass > def __add__(self, other): > pass > #... > > (I have an implementation of the frac class done (this meaning, it > works for me), and although it's pretty dirty, I'd be happy to post it > here if you want it.) > > My idea, in summary would be that this python shell session is true: > > >>> 5/2 > 2 1/2 > >>> f = 5/2 > >>> f.__class__ > > >>> # or > >>> (0.6).__class__ # Treat decimal literals as fractions, so that... > > >>> 1/3+0.6 > 14/15 > >>> # That was easy. ;) > > I would like to get some feedback on this idea. Has this been posted > before? If so, was it rejected? and for what? > Also, I would like to know if you have improvements on the initial > design, and if it would be appropiate to send it as a PEP. The gmpy module has unlimited precision rationals. Works pretty good, too. From eduardo.padoan at gmail.com Sun Sep 2 20:35:26 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Sun, 2 Sep 2007 21:35:26 -0300 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> Message-ID: On 9/2/07, llothar wrote: > I'm afraid that the GIL is killing the usefullness of python for some > types of applications now where 4,8 oder 64 threads on a chip are here > or comming soon. > > What is the status about that for the future of python? > > I know that at the moment allmost nobody in the scripting world has > solved this problem, but it bites and it bites hard. Only groovy as a > Java Plugin has support but i never tried it. Writing an interpreter > that does MT this seems to be extremely difficult to do it right, with > lots of advanced stuff like CAS and lock free programming. > > Even Smalltalk and Common Lisp didn't get it until know (with the > exception of certain experiments). No. http://www.artima.com/weblogs/viewpost.jsp?thread=211430 -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Sep 22 05:16:09 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 22 Sep 2007 11:16:09 +0200 Subject: Writing Object Data to Disk References: Message-ID: <5lk4qnF8iosiU1@mid.individual.net> Amit Kumar Saha wrote: > I have a Python class with data members, say: > > class Foo: > def __init__(self): > > self.a=7 > self.b[]={1,3,4} ^^ This is invalid syntax. > I would like to know if "Pickling" the class object is the only > way of writing it to disk for persistent storage. It isn't. Every means of serialisation works, but pickling is especially convenient if you only use Python. > Also, do we have a concept similar to "array of objects" in > Python? You can put all objects in lists, be it a string, an integer or some complex class instance. > The number of objects is only known at "run-time". class and function definitions also happen at runtime. I suggest you worked through the Python tutorial to get a deeper insight in Python's concepts. http://docs.python.org/tut/ Regards, Bj?rn -- BOFH excuse #89: Electromagnetic energy loss From steven.bethard at gmail.com Thu Sep 6 12:19:14 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 06 Sep 2007 10:19:14 -0600 Subject: reload(sys) In-Reply-To: <1189094496.120836.61870@o80g2000hse.googlegroups.com> References: <1188521143.421431.119100@l22g2000prc.googlegroups.com> <1188564816.430863.219560@w3g2000hsg.googlegroups.com> <1188662049.337034.58220@w3g2000hsg.googlegroups.com> <1189077209.646830.111990@19g2000hsx.googlegroups.com> <1189094496.120836.61870@o80g2000hse.googlegroups.com> Message-ID: <5-WdnUzNZuwZtX3bnZ2dnUVZ_vOlnZ2d@comcast.com> S?nmez Kartal wrote: > I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as > "f.write(str(xml))". At execution of that line, it gives error with > description, configure your default encoding... > [and later] > > http://rafb.net/p/RfaF8215.html > > products in the code is a list of dictionaries which are returned by > makeProduct function. > > I'm not typing or pasting those characters into my script. So, > declaring an encoding didn't make it. :-( But, your code excerpt > runned well. Gabriel Genellina wrote: > You should ensure that arguments to makeProduct are either: > - unicode objects > - ASCII strings > > If you got them from some other place, decode the strings as soon as > possible into unicode. Read > to understand what's happening To further illustrate Gabriel's point, here is some code where I read in some UTF8 text from a file. If you properly decode that text from UTF8, you don't get any errors. If you forget to decode that text, you'll get exactly the "default encoding" error you were getting before: >>> f = open('temp.txt', 'w') >>> f.write(u'? and ?'.encode('utf8')) >>> f.close() >>> non_decoded_text = open('temp.txt').read() >>> decoded_text = non_decoded_text.decode('utf8') >>> import xmlbuilder >>> builder = xmlbuilder.XMLBuilder() >>> builder.foo = dict(bar=non_decoded_text) >>> str(builder) Decoding Error: You must configure default encoding >>> builder = xmlbuilder.XMLBuilder() >>> builder.foo = dict(bar=decoded_text) >>> str(builder) '\xc2\xae and \xc2\x99' Note that I didn't have to do anything with the default encoding. I simply had to decode the text file with the appropriate codec. So, looking at your code, I'm guessing that you need to figure out where you're reading in the "name", "url" and "image" values, and make sure you're properly decoding that text. STeVe P.S. If you can find somewhere to file a bug report for XMLBuilder, you really should. The error instructing you to configure the default encoding is really just wrong. From linuxprog at gmail.com Mon Sep 24 09:42:57 2007 From: linuxprog at gmail.com (linuxprog) Date: Mon, 24 Sep 2007 13:42:57 +0000 Subject: SOAPpy Error In-Reply-To: <46F7867F.3090607@gmail.com> References: <46F7867F.3090607@gmail.com> Message-ID: <46F7BEE1.300@gmail.com> linuxprog a ?crit : > hi all > > i'm building a webservice client with soappy > > when i send some informations it's returns an error > here is the informations that generates the error > var = SOAPpy.structType() > var._addItem("code", u"XysZjd") > var._addItem("value", 1) > when i send the var variable SOAPpy prints this > > File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 473, in > __call__ > return self.__r_call(*args, **kw) > File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 495, in > __r_call > self.__hd, self.__ma) > File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 366, in > __call > config = self.config) > File "C:\Python23\lib\site-packages\SOAPpy\Client.py", line 228, in call > data = r.getfile().read() > AttributeError: 'NoneType' object has no attribute 'read' > > when i have activate debug , the debug mode shows : > code : -1 > msg : headers : None > > it should prints some thing like this if all goes well : > code : 200 > msg : OK > headers : Date: Mon, 24 Sep 2007 09:08:45 GMT > Server: Apache/2.2.3 (Debian) PHP/5.2.0-8+etch7 > X-Powered-By: PHP/5.2.0-8+etch7 > Content-Length: 2116 > Connection: close > Content-Type: text/xml; charset=utf-8 > > wha's wrong ? > > Thanks > still no answer !? From pavlovevidence at gmail.com Thu Sep 13 15:47:27 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Sep 2007 12:47:27 -0700 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <13eigagsuk74l55@corp.supernews.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189666095.727426.135170@o80g2000hse.googlegroups.com> <1189685403.306218.13270@22g2000hsm.googlegroups.com> <13eigagsuk74l55@corp.supernews.com> Message-ID: <1189712847.666826.230680@50g2000hsm.googlegroups.com> On Sep 13, 9:55 am, Steven D'Aprano wrote: > On Thu, 13 Sep 2007 12:10:03 +0000, timothy.soehn... at gmail.com wrote: > > Why not use '_' as the self variable. It is minimal and achieves close > > to '.var', as '_.var' isn't that different. I know its a little > > perl-esque, but its not a bad convention if you are aiming to up > > readability of your code. > > I think the definitions of "up" or "readability" you are using are very > different from mine. To me, to up something means to increase it, and > readability means the ease of comprehension when reading something. You > seem to be using the opposite definition for one or the other. He's not. People who've never done a lot of numerical programming might have a hard time understanding this, but what is considered readable for "ordinary" programming is just does not apply when reading and writing pages of mathematical formulae. Trying to apply the "ordinary" standards of readability to numerical programming is like trying to write a mathematical treatise in English prose only, with no mathematical notation. It would be totally unreadable, almost as unreadable as a sociology textbook. In the same way, many pages of formulas would be unreadable using "ordinary" standards of readability (though not quite to the same degree). The most readable numerical code looks as much like the printed equations as possible. "self." is a distraction; it's not in the original formula; it's boilerplate. It takes away from the readability of the code. Assuming that you can't get rid of the attribute syntax, minimizing the visual footprint of it will increase readability. So "_." is more readable than "self." because it changes the appearance of the printed formula a lot less. Having said all that, I would not use "_.", ever. I probably wouldn't even use Python if I had lots of numerical formulas to implement; I'd wrap up some C or Fortran code. If I did use Python I'd avoid implementing lots of formulas in class methods. If I had do this stuff in a method, and I only had a few formulas, I'd tolerate "self." for the sake of conformance. If I had many fomulas, I would make local copies at the top. Carl Banks From fredrik at pythonware.com Wed Sep 26 03:24:09 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 09:24:09 +0200 Subject: Inserting an element into existing xml file In-Reply-To: <1190716205.955284.220810@n39g2000hsh.googlegroups.com> References: <1190712485.761290.136570@50g2000hsm.googlegroups.com> <46F8E0E2.3050602@web.de> <1190716205.955284.220810@n39g2000hsh.googlegroups.com> Message-ID: Anand wrote: > I'm Afraid to say, I can't use lxml or elementTree as it requires many > legal approvals and there is high chances of not getting it through. > So Do you have any other method / idea just by using plain 2.4 to > accomplish the task Are you allowed to use code samples you found on the net? http://svn.effbot.org/public/elementtree/ (if not, are you even allowed to ask for help? ;-) ElementTree (aka xml.etree) is pure Python, and you only need the ElementTree.py module to do what you want, so I guess you could always pretend you wrote it yourself... From orsenthil at gmail.com Sun Sep 9 13:57:37 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Sun, 9 Sep 2007 23:27:37 +0530 Subject: python 2.5 problems In-Reply-To: <3nVEi.98555$Vk6.66626@newsfe07.phx> References: <3nVEi.98555$Vk6.66626@newsfe07.phx> Message-ID: <20070909175737.GA4050@gmail.com> > Finally deleted 2.2 and loaded 2.5 (see below), using Dont delete. Uninstall python 2.2 and additional modules if you have installed them. > So is there something not stable about ver 2.5 on XP ? Nothing like that. Python 2.5 works perfectly fine on Windows XP. Download from www.python.org and if you face the same problem, try the python distribution available from ActiveState. If both of them give the same problem, good chances that the problem is with your OS. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From f.guerrieri at gmail.com Sun Sep 2 11:29:28 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Sun, 2 Sep 2007 17:29:28 +0200 Subject: list index() In-Reply-To: <1188742647.266967.33720@w3g2000hsg.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> <1188498199.557521.31700@z24g2000prh.googlegroups.com> <1188742647.266967.33720@w3g2000hsg.googlegroups.com> Message-ID: <79b79e730709020829p594f22e0qce0ee33c0d707503@mail.gmail.com> On 9/2/07, Zentrader wrote: > > On Aug 30, 11:23 am, zzbba... at aol.com wrote: > > Neil, Steve, > > > > Thanks for the responses on sets. I have not used them before and was > > not even aware Python had them. I will try them out. > > And if there weren't sets you would still not use find or index but a > brute force method or dictionaries > for each in dir_a_list : > if each not in dir_b_list : > print each, "not in dir_b" > This is O(N_a * N_b)... unless the list are always small, it's definitely better (if one is decided not to use sets) to use dictionaries :-) bye francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From tec at knology.net Mon Sep 10 12:03:52 2007 From: tec at knology.net (Tim) Date: Mon, 10 Sep 2007 09:03:52 -0700 Subject: shared memory pointer In-Reply-To: References: <1189436265.841415.234050@w3g2000hsg.googlegroups.com> Message-ID: <1189440232.421738.283100@k79g2000hse.googlegroups.com> On Sep 10, 10:11 am, Tim Golden wrote: > Tim wrote: > > Hello Everyone, > > > I am getting shared memory in python using the following. > > > szName = c_char_p(name) > > hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE, > > None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName) > > if (hMapObject == 0): > > print "OpenKey: Could not open name file mapping object" > > raise WinError() > > > self.pData = windll.kernel32.MapViewOfFile(hMapObject, > > FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE) > > Without answering your question directly, why not use > the stdlib mmap module, which does exactly this for > you behind the scenes? > > Docs -http://docs.python.org/lib/module-mmap.html > Example -http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413807 > > TJG I reviewed the mmap function and I have a question. In the example code below, what is the connection between the data in shared memory and the mmap function. The fileno is zero. Why is it zero? The size makes sense because there is 256 bytes in shared memory. The tag is MyFileMappingObject. This tag does not have anything in common with the shared memory. How can mmap point to any data in shared memory? There is no coorelation. pBuf = windll.kernel32.MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, SHMEMSIZE) if (pBuf == 0): print "Could not map view of file" raise WinError() else: memcpy = cdll.msvcrt.memcpy memcpy(pBuf, szMsg, len(szMsg)) shmem = mmap.mmap(0, 256, "MyFileMappingObject", mmap.ACCESS_WRITE) shmem.write("Message from Python process") From http Sun Sep 2 13:05:27 2007 From: http (Paul Rubin) Date: 02 Sep 2007 10:05:27 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188742231.470668.29910@g4g2000hsf.googlegroups.com> <1i3t4ha.1r0xx7414w0taxN%aleax@mac.com> Message-ID: <7xfy1x0zhk.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > ...which suggests that creating an xrange object is _cheaper_ than > indexing a list... Why not re-use the xrange instead of keeping a list around? Python 2.4.4 (#1, Oct 23 2006, 13:58:00) >>> a = xrange(3) >>> print list(a) [0, 1, 2] >>> print list(a) [0, 1, 2] From steve at holdenweb.com Fri Sep 14 01:48:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Sep 2007 01:48:41 -0400 Subject: Just bought Python in a Nutshell In-Reply-To: References: Message-ID: Lamonte Harris wrote: > http://www.powells.com/biblio/63-9780596001889-7 Used, has anyone read > this book. Any additional information that you like,dislike about this > book? [I like having real books and stead of ebooks because its better > on the eyes.] Should be her 2morrow Afternoon :), few hours before I > get home great deal :D. You have just purchased the most comprehensive language reference and instructional manual currently available, written by an acknowledged expert whose pedantry ensures an excruciating level of correctness in the text. It's a well-written book, and contains enough information that almost every Python programmer will find it a useful addition to his or her bookshelf. You will enjoy it whether you choose to read from the beginning or just dip in. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From gherron at islandtraining.com Thu Sep 6 11:50:20 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 06 Sep 2007 08:50:20 -0700 Subject: Getting original working directory In-Reply-To: <1520.1657-1856-1993609010-1189091974@seznam.cz> References: <1520.1657-1856-1993609010-1189091974@seznam.cz> Message-ID: <46E021BC.7050607@islandtraining.com> rave247 rave247 wrote: > Hi, > > I' am unable to solve this problem. I've got python program, it is installed in standard location. I run this program from some location X (note that I just type relative "myscript", leaving operating system to look up script itself using PATH variable) and this program somewhere in the code calls os.chdir() to change it is current working directory and I would need in python code to get the *original* directory location *after* os.chdir() is performed. This means the location X from which script was performed - it is the location I am in after script is finished. > > Thanks for any help > Not quite sure what you want, but one of these should work for you: sys.argv[0] gives the path of the script begin run. Strip off the filename part to get its directory. os.getcwd() returns the current working directory. Call this before you change things with os.chdir(). Gary Herron From steve at REMOVE-THIS-cybersource.com.au Wed Sep 19 11:51:57 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 19 Sep 2007 15:51:57 -0000 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> Message-ID: <13f2hctdoob87e5@corp.supernews.com> On Tue, 18 Sep 2007 18:09:26 -0700, TheFlyingDutchman wrote: > How much faster/slower would Greg Stein's code be on today's processors > versus CPython running on the processors of the late 1990's? I think a better question is, how much faster/slower would Stein's code be on today's processors, versus CPython being hand-simulated in a giant virtual machine made of clockwork? -- Steven. From seannakasone at yahoo.com Fri Sep 14 06:21:42 2007 From: seannakasone at yahoo.com (Sean Nakasone) Date: Fri, 14 Sep 2007 00:21:42 -1000 Subject: smtp debugging methods Message-ID: I'm having trouble with sending smtp mail. It's hanging after the smtplib.SMTP() line. It doesn't works from home but not from work. What's the best way to debug this? # Here's my script import smtplib msg = "Subject: Hello\n\nThis is the\nbody of the message." server = smtplib.SMTP("smtp.gmail.com",465) # "Connection refused" normally means there is no server listening for # connections on the specified IP/port-combination. # use netstat -an to view connections. server.set_debuglevel(1) server.ehlo() server.starttls() server.ehlo() # !!! set the password server.login("myuser", "mypass") server.sendmail("... # Here's the error >>> server = smtplib.SMTP("smtp.gmail.com",465) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/smtplib.py", line 241, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.4/smtplib.py", line 304, in connect (code, msg) = self.getreply() File "/usr/lib/python2.4/smtplib.py", line 345, in getreply line = self.file.readline() File "/usr/lib/python2.4/socket.py", line 340, in readline data = self._sock.recv(self._rbufsize) socket.error: (113, 'Software caused connection abort') From w_a_x_man at yahoo.com Sun Sep 30 14:37:51 2007 From: w_a_x_man at yahoo.com (William James) Date: Sun, 30 Sep 2007 11:37:51 -0700 Subject: Create a string array of all comments in a html file... In-Reply-To: <1191166775.660477.97840@o80g2000hse.googlegroups.com> References: <1191166775.660477.97840@o80g2000hse.googlegroups.com> Message-ID: <1191177471.105525.195000@o80g2000hse.googlegroups.com> On Sep 30, 10:39 am, sophie_newbie wrote: > Hi, I'm wondering how i'd go about extracting a string array of all > comments in a HTML file, HTML comments obviously taking the format > "". > > I'm fairly stumped on how to do this? Maybe using regular expressions? > > Thanks. E:\Ruby>irb --prompt xmp "And so funny!

It was a dark and stormy night.

".scan(//m) ==>["", ""] From kay.schluehr at gmx.net Tue Sep 18 05:13:49 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 18 Sep 2007 02:13:49 -0700 Subject: can Python be useful as functional? In-Reply-To: <46ef8895$0$21882$426a34cc@news.free.fr> References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> <46ef8895$0$21882$426a34cc@news.free.fr> Message-ID: <1190106829.680544.159250@g4g2000hsf.googlegroups.com> On 18 Sep., 10:13, Bruno Desthuilliers wrote: > Lorenzo Stella a ?crit : > > > Hi all, > > I haven't experienced functional programming very much, but now I'm > > trying to learn Haskell and I've learned that: 1) in functional > > programming LISTS are fundmental; > > Not exactly. They are used quite a lot, yes, but that's also the case in > other paradigms. What's important in functional programming is *functions*. Functional lists are not quite the same. They are actually recursive datastructes. In Python you would model them as nested tuples: t = (a, (b, (c, ...(d, None))))) These are essentially pairs build from the bottom up using a list constructor and they have little in common with those mutable list objects ( arrays, vectors ) being used in Python. You can easily extend them into n-ary trees and implement mutations on them as forks where the original strucure is almost preserved. This leads to all kinds of "functional data structures". In order to access an element you already need a recursive function defintion ( unless you just want to examine the head or the tail only ) and this makes functional programming and "consed" lists a perfect match. [...] > Strictly speaking, a language is functional if it has functions as first > class objects. Period. No, not period and not strictly speaking. A language is functional when its semantics is based on lambda calculus where everything is a function or a variable bound to a function which can be substituted by a function. Each functional language, to be usefull, must be augmented with programming language constructs used from other paradigms or support unsafe operations to enable proper side effects. This is not a humpty-dumpty issue where everyone can name his language a functional programming language just because one can pass functions as first class citizens around and he says so. Otherwise those languages can support a few functional programming language idioms such as map, reduce and filter or comprehensions as in Pythons case. From carsten at uniqsys.com Fri Sep 7 21:12:23 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 07 Sep 2007 21:12:23 -0400 Subject: Is a Borg rebellion possible? (a metaclass question) In-Reply-To: References: <1189168282.665210.260840@19g2000hsx.googlegroups.com> <1189180478.257790.60160@g4g2000hsf.googlegroups.com> Message-ID: <1189213943.3262.11.camel@localhost.localdomain> On Fri, 2007-09-07 at 14:54 -0600, Steven Bethard wrote: > Carsten Haese wrote: > > [slightly convoluted example...] > > I think I would probably write that as:: > [concise example...] > > That is, I don't think there's really a need for __new__ if you're using > a metaclass. Just set the instance's __dict__ in the __call__ method of > the metaclass. Good point. I suppose it shows that this is the first metaclass I've ever written, but it works, and it didn't make my brain explode ;) -- Carsten Haese http://informixdb.sourceforge.net From steve at holdenweb.com Fri Sep 28 16:04:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 16:04:00 -0400 Subject: OCBC connection In-Reply-To: <1191008769.878419.307310@k79g2000hse.googlegroups.com> References: <1191000128.112881.111790@r29g2000hsg.googlegroups.com> <1191008769.878419.307310@k79g2000hse.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: [...] >> >> >>> curs = conn.cursor() >> >>> import psycopg2 as db >> >>> conn = db.connect(database="pycon", user="username", >> password="password", host="localhost", port=5432) >> >>> curs = conn.cursor() >> >>> curs.execute("SELECT orgid, orgname FROM organization") >> >>> from pprint import pprint # just for neatness >> >>> pprint(curs.fetchall()) >> [(1, 'AB Strakt'), >> (79, 'DevIS'), >> ... >> (113, 'Test Organization'), >> (19, 'Holden Web LLC')] >> >>> > Whoops! I almost posted some code using the adodb or the odbc module, > which is what I would have probably used, but I figured I'd take a > look and see if there was a postgres module available. I'm not seeing > any basic differences between your code and the code I linked to > though...except that if I ran your first line of code, I would get an > exception as "conn" hasn't been defined yet. > > Whatever. I apologize for being misleading(?) > I screwed up anyway - the first line shouldn't have been included. But perhaps Sean could enlighten us as to whether ODBC is really a requirement, or simply the first solution that he thought of. I don't know why one would *require* ODBC. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From ivonet at gmail.com Fri Sep 21 15:14:10 2007 From: ivonet at gmail.com (Ivo) Date: Fri, 21 Sep 2007 21:14:10 +0200 Subject: Remote Command a Python Script In-Reply-To: <1190384953.774277.249350@k79g2000hse.googlegroups.com> References: <1190384953.774277.249350@k79g2000hse.googlegroups.com> Message-ID: <46f4171e$0$3060$e4fe514c@dreader31.news.xs4all.nl> Ulysse wrote: > Hello, > > I've installed Python 2.5 on my WRT54G Linksys Router. On this router > a script is executed. This script write a little Pickle database in > the router memory. > > I would like to write another Python script which will be able to : > > 1. Stop and start the remote script from my Windows Computer. At > present I use Putty to connect to the router by the SSL, then I > manually kill the python process. > > 2. Retrieve the little database located in router memory and backup it > on my Window PC. At present I use WinSCP (like FTP) to get the pickle > file. > > Can you help me with that (modules to use, useful code snippets) > > Thank a lot, > > Maxime > or SPyRO From ldo at geek-central.gen.new_zealand Sun Sep 9 23:04:38 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 10 Sep 2007 15:04:38 +1200 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> <13e99756io95p66@corp.supernews.com> Message-ID: In message <13e99756io95p66 at corp.supernews.com>, bambam wrote: > Thank you, Don't top-post. From puredata at 11h11.com Tue Sep 25 22:58:12 2007 From: puredata at 11h11.com (patrick) Date: Tue, 25 Sep 2007 22:58:12 -0400 Subject: stopping a while True: with the keyboard In-Reply-To: <1190774898.348656.190760@y42g2000hsy.googlegroups.com> References: <1190774898.348656.190760@y42g2000hsy.googlegroups.com> Message-ID: <46F9CAC4.6050609@11h11.com> i don't want to quit my program only get out from a while True: also i want to use only 1 key like s. pat Benjamin wrote: > On Sep 25, 8:19 pm, patrick wrote: > >> hi all, >> >> i am looking for a way to break a while True: when pressing "s" on my >> keyboard. how can i do this? >> >> pat >> > > Ctrl-C > > From fredrik at pythonware.com Wed Sep 26 07:16:11 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 13:16:11 +0200 Subject: Return status from methods in socket class In-Reply-To: <46fa3a39$1_1@glkas0286.greenlnk.net> References: <46fa3a39$1_1@glkas0286.greenlnk.net> Message-ID: Paul D Ainsworth wrote: > As part of a debugging investigation I would like to be able to display the > return status from various methods in the socket class. The methods I'm > using are accept, bind, connect, listen, send, recv although not necessarily > in that order. > > Is this possible and if so, how? umm. don't they all throw exceptions if something goes wrong? From steve at holdenweb.com Thu Sep 6 15:13:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Sep 2007 12:13:25 -0700 Subject: Getting original working directory In-Reply-To: <1658.1882-17889-1055570935-1189104422@seznam.cz> References: <1658.1882-17889-1055570935-1189104422@seznam.cz> Message-ID: rave247 rave247 wrote: > If I could use os.getcwd() or save the value to some variable before calling os.chdir() > I would do it, believe me. However I can't because it is the part of code where I > can't do any changes. > > Also I do not agree that such thing is not possible because after python script > finishes its work, it naturally gets back into the original location from where > you started the script (in shell you are in the original location after script > finishes). So this information has to be stored somewhere (probably in shell which > runs the interpreter) and there *must* be a way how to get it. Simply after > calling os.chdir() the original value doen't disappear, I think it just needs > some nice hack if python doesn't provide a way how to get it. > Python runs as a sub-process. The parent process (the one that started Python) contains the working directory that the Python interpreter inherited from it. But you can't expect to just go poking around inside the environment of your parent process, which will typically be waiting for you to finish before it continues. Why *must* there be a way to get at its current directory? Once it continues, of course, it does so in the same directory. If you want to hack into your parent process to find that information that's up to you, but Python certainly has no special mechanism for doing it. If you treat the answers to all your questions with so little respect it's a wonder you bother asking the questions in the first place. You didn't even explain what the relationship was between the "myscript" that you want to run and the Python code that you want to switch back to the original working directory. Sorry, we aren't mind readers (though some of the guys on this list get close on occasion). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From stefan.behnel-n05pAM at web.de Fri Sep 21 09:02:56 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 21 Sep 2007 15:02:56 +0200 Subject: An Editor that Skips to the End of a Def In-Reply-To: <46f2c9c0$0$7365$a9611f8e@news.cityweb.de> References: <46f2c9c0$0$7365$a9611f8e@news.cityweb.de> Message-ID: <46F3C100.70000@web.de> Michael v. Fondern wrote: > (Ctrl-Shift-Down) Is this the opposite of thumbs up, or is it just to suggest that Eclipse can come close to Emacs's usability if you try hard? Stefan From frank at chagford.com Wed Sep 12 01:22:48 2007 From: frank at chagford.com (Frank Millman) Date: Tue, 11 Sep 2007 22:22:48 -0700 Subject: Minor documentation bug In-Reply-To: References: <1189518490.939985.101460@g4g2000hsf.googlegroups.com> Message-ID: <1189574568.565787.175240@k79g2000hse.googlegroups.com> On Sep 11, 4:55 pm, Tim Golden wrote: > Frank Millman wrote: > > I spotted a minor bug in the documentation to SimpleXMLRPCServer. It > > does not seem worth getting a login to the bugtracker just to enter > > this, so if it is confirmed as a bug perhaps someone would be so kind > > as to enter it for me. > > Frank, please do take the trouble to enter this. With the > new roundup bugtracker, it's *really easy* to get a login. > > http://bugs.python.org > > TJG You are right - it was pretty easy. I have entered the report. Thanks, Tim Frank From bj_666 at gmx.net Sun Sep 16 12:26:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Sep 2007 16:26:59 GMT Subject: We need PIGs :) References: <46d74472$0$402$426a34cc@news.free.fr> <87hcm81dot.fsf@kip.sateh.com> <5k9qpsF2mrncU3@mid.uni-berlin.de> Message-ID: <5l53qjF655kfU4@mid.uni-berlin.de> On Sun, 16 Sep 2007 10:17:18 -0400, Colin J. Williams wrote: > Marc 'BlackJack' Rintsch wrote: > >> `getFoo()` is discouraged by PEP 8. [?] > > Perhaps PEP 8 needs rethinking. I prefer getFoo(). Yeah, *your* preference is a very good reason to rethink PEP?8? ;-) Ciao, Marc 'BlackJack' Rintsch From whamil1 at entergy.com Tue Sep 11 13:28:35 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 11 Sep 2007 12:28:35 -0500 Subject: Python code-writing for the blind. Was (Re: newbie: stani's pythoneditor if-else) In-Reply-To: <1189531123.283413.160870@22g2000hsm.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB3F@LITEXETSP001.etrsouth.corp.entergy.com> > From: madzientist > > Thanks, everybody, for the very very useful and kind responses. > > There is a second reason why I asked the question about automatic de- > indenting. I am teaching myself Python partly so I can then help my > technically astute, but blind friend learn programming. For the many > reasons that Pythonistas like to cite often, I thought Python would be > a good choice to learn programming, and that perhaps the indentation > problem would be solved by the use of an intelligent editor. > > But now I am not so sure, though I will try Emacs. Is there anyone > here with experience in such issues ? Maybe for her sake, I should > switch to learning Perl ;) ;) > > More seriously, the added issue is that SPE uses spaces, not a single > tab to indent the lines, and I believe it is extremely tedious to use > screen-readers to keep track of blank spaces at the beginning of each > line. I have not tried it myself yet, but I will soon. > > Is Python a bad choice for the blind programmer, as a result of a > tight linkage between visual aspects of the code and its function ? I > wish the site blindprogramming.com weren't so lifeless... > Can you set SPE to use a single space rather than the typical four spaces? Python should accept it just fine. You'll still have problems reading other people's code. Maybe you can write a quick script that converts code down to one-space indents. -- -Bill Hamilton From hat at se-162.se.wtb.tue.nl Tue Sep 4 06:50:37 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 04 Sep 2007 12:50:37 +0200 Subject: Printing lists in columns (was: TypeError: 'module object is not callable') References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> Message-ID: On 2007-09-04, Chris.Tidy at jet.uk wrote: > Thanks guys. Changing to how Python does things has a lot of geting > used to! That's part of the fun :-) > Do any of you have any ideas on the best way to do the following > problem: > > Each loop I perform, I get a new list of Strings. > I then want to print these lists as columns adjacent to each other > starting with the first > created list in the first column and last created list in the final > column. Use zip: >>> x = ['1', '2'] >>> y = ['3', '4'] >>> for row in zip(x,y): ... print ', '.join(row) ... 1, 3 2, 4 zip() constructs a list of rows, like [('1', '3'), ('2', '4')] which is then quite easy to print Good luck, Albert From richyjsm at gmail.com Sat Sep 22 20:10:29 2007 From: richyjsm at gmail.com (richyjsm at gmail.com) Date: Sun, 23 Sep 2007 00:10:29 -0000 Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <13fbahtem90fp99@corp.supernews.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> <1190484589.890198.266430@y42g2000hsy.googlegroups.com> <13fbahtem90fp99@corp.supernews.com> Message-ID: <1190506229.092718.41690@g4g2000hsf.googlegroups.com> On Sep 22, 7:50 pm, Steven D'Aprano wrote: > Everybody forgets that pow can take three arguments, except of course for > those who use that functionality and would be mighty peeved if it went > away. And who is it who uses this functionality? It's useful in elementary number theory, sure, but I'd argue that if there are going to be number theoretical functions in the core then there are other things, like gcd(), that are far more deserving of inclusion. It comes up in the RSA cryptosystem, but if you're using Python's pow for this then you're surely only writing a toy RSA implementation, perhaps for educational purposes(?). Neither of these seem like compelling arguments to have pow in the core. Richard From edgrsprj at ix.netcom.com Sat Sep 1 21:50:22 2007 From: edgrsprj at ix.netcom.com (E.D.G.) Date: Sat, 1 Sep 2007 19:50:22 -0600 Subject: Important Research Project References: <13ddcvm1bsu3s94@corp.supernews.com> <13dhm7uec5sp855@corp.supernews.com> Message-ID: <13dk3p5mqdbvc7f@corp.supernews.com> "E.D.G." wrote in message news:13dhm7uec5sp855 at corp.supernews.com... I have the Gnuplot graphics program running now with Windows XP. And it looks like it will work for my application. http://www.gnuplot.info From whamil1 at entergy.com Tue Sep 11 09:35:06 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 11 Sep 2007 08:35:06 -0500 Subject: newbie: stani's python editor if-else In-Reply-To: <1189517164.302630.307850@w3g2000hsg.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CB3A@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of > kyosohma at gmail.com > Sent: Tuesday, September 11, 2007 8:26 AM > To: python-list at python.org > Subject: Re: newbie: stani's python editor if-else > > On Sep 10, 11:24 pm, madzientist wrote: > > hi, > > > > two quick questions: > > > > a) i am using SPE (latest version) and for some reason, when i type, > > say > > > > if 1==2: > > print "not equal" > > else: > > print "equal" > > > > the else is at the same indentation level as the preceding print > > statement, and i get a syntax error > > > > why doesn't spe automatically put the else at the level of the if > > statement ? what am i dong wrong ? once i manually change the > > indentation, the code snippet runs perfectly. > > > > b) if this is not the group for such elementary questions, please do > > let me know. > > > > thanks !!!! > > > > suresh > > I agree with Steve. I have yet to see an IDE for Python (or anything > else) that unindents statements. Even IDLE, the Official IDE for > Python, doesn't do that. > IDLE (At least, IDLE 1.0.5) unindents in obvious situations. I think it's only on break, continue, pass, and return statements, but there may be others. -- -Bill Hamilton From ldo at geek-central.gen.new_zealand Sun Sep 23 22:53:11 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 24 Sep 2007 14:53:11 +1200 Subject: subprocess -popen - reading stdout from child - hangs References: <1190518129.356844.242710@19g2000hsx.googlegroups.com> Message-ID: In message <1190518129.356844.242710 at 19g2000hsx.googlegroups.com>, gregpinero at gmail.com wrote: > Let's say I have this Python file called loop.py: > > import sys > print 'hi' > sys.stdout.flush() > while 1: > pass > > And I want to call it from another Python process and read the value > 'hi'. How would I do it? > > So far I have tried this: > >>>> proc = subprocess.Popen('python >>>> /home/chiefinnovator/loop.py',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE) >>>> proc.stdout.read() > > But it just hangs at read() That's because you didn't tell it how much to read, so by default it tries to read until EOF . But since the subprocess is still running and hasn't closed its stdout, the pipe has not reached EOF. From kay.schluehr at gmx.net Tue Sep 18 02:33:37 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 17 Sep 2007 23:33:37 -0700 Subject: can Python be useful as functional? In-Reply-To: References: <1190073045.618869.261290@k79g2000hse.googlegroups.com> Message-ID: <1190097217.181332.140620@d55g2000hsg.googlegroups.com> On 18 Sep., 03:30, "Evan Klitzke" wrote: > > My question is: how can we call a language "functional" if it's major > > implementation has a limited stack? Or is my code wrong? > > Python does not optimize tail recursion. Never mind. In the provided example the call to sieve() is not in tail position anyway ;) [...] > If you > want to write functional code, use a real functional language! It's hard to disagree. As a Python programmer I'd rather care for smooth integration with code written in Haskell or OCaml than adopting their particular programming idioms. For instance the Python - OCaml bridge is aged and I'm not aware that one between Python and Haskell even exists. From robertoedwins at gmail.com Wed Sep 5 22:33:15 2007 From: robertoedwins at gmail.com (rieh25) Date: Wed, 5 Sep 2007 19:33:15 -0700 (PDT) Subject: Module for mod_python In-Reply-To: <1189041758.262088.60520@y42g2000hsy.googlegroups.com> References: <12506829.post@talk.nabble.com> <1189041758.262088.60520@y42g2000hsy.googlegroups.com> Message-ID: <12514597.post@talk.nabble.com> Thanks for your response. Actually I have looked at some of them, although not in great detail and haven't actually installed them. I do have to do some more investigating, but I think I can say something right now. The one thing I think I have to offer in terms of originality is the idea of keeping state of record selection, and making that selection affect (filter) the listing of related tables. As an example this is the way a master-detail application for a chain of book stores works normally: There is a detail form with a list of stores, and upon selection of one of them, the id of the store is passed as a parameter to a new page which lists the books in that store. In my version, there is also a detail form with a list of the stores, but the store id is not passed as a parameter, it is saved as a session variable. Upon loading the page with the list of books, a filter takes effect taking into accoung the store id. The saving of the session variable and the filtering is never specified though. It is done automatically given the existence of a foreign key in the books table making reference to a store id. As far as I know, db object relational mapper systems take care of the creation of the tables in the actual database, and are capable of generating forms given a table name, but my system would also take care of the selection of records, and the cascading effect that has on related tables in the sense of how they are listed in detail forms with corresponding filters. I'm not sure that it is that new of an idea, or that helpful from someone else's point of view, but it is something that I have put into practice and have a good concept of it. And I do recognize I should do more investigating... Graham Dumpleton-2 wrote: > > On Sep 6, 9:32 am, rieh25 wrote: >> Is it such a bad idea that it doesn't deserve a reply? > > You only posted the question six hours ago. Maybe the people who might > want to comment are asleep. > > BTW, have you done an analysis of the various existing database object > relational mapper systems for Python that already exist? There are > also some systems for automatic web application forms generation based > on database data as well. > > How is what you have in mind different to or not covered by these > existing packages? > > If you describe how what you want to do isn't satisfied by the > existing systems then people may be more interested in commenting. If > you aren't aware of these existing systems then perhaps use Google to > do some research on them first. > > Graham > >> rieh25 wrote: >> >> > I've been thinking about a module (actually I have it partially >> > implemented in Zope), that would do the following things: >> >> > - Read the structure of a MySql database (fill a dictionary with it) >> >> > In order to: >> >> > - Quickly create detail/filter/update forms given a table name (without >> > specifying the fields because they have already been detected) >> > - Keep state of record selection. In order to implement Master-Detail >> form >> > processing, with unlimited levels of parent-child table relations, >> which >> > have also been detected already (foreign keys) >> > - Management of interrelation between security and menus (a user can >> only >> > access certain parts of the application) >> >> > I think that Ruby on Rails does something similar, but still I thing it >> > would be interesting to implement it in Python. What do you think? >> >> -- >> View this message in >> context:http://www.nabble.com/Module-for-mod_python-tf4386823.html#a12513012 >> Sent from the Python - python-list mailing list archive at Nabble.com. > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Module-for-mod_python-tf4386823.html#a12514597 Sent from the Python - python-list mailing list archive at Nabble.com. From stefan.behnel-n05pAM at web.de Tue Sep 4 02:20:20 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 04 Sep 2007 08:20:20 +0200 Subject: Python object <-> XML In-Reply-To: <1188849714.128121.139450@r34g2000hsd.googlegroups.com> References: <1188849714.128121.139450@r34g2000hsd.googlegroups.com> Message-ID: <46DCF924.8080904@web.de> Samuel wrote: > Say you have the following XML: > > > item 1 > > > item 2 > > > > > my group > > > Is there an easy way (i.e. without writing a sax/dom parser) to load > this into a (number of) Python object(s), manipulate the instance, and > save the result back to XML? Try lxml.objectify. It doesn't copy your data into other objects, but it gives you all the freedom to design your own objects as an abstraction of the XML data. See here: http://codespeak.net/lxml/objectify.html especially these sections: http://codespeak.net/lxml/objectify.html#element-access-through-object-attributes http://codespeak.net/lxml/objectify.html#python-data-types http://codespeak.net/lxml/objectify.html#defining-additional-data-classes It's part of lxml, which makes it plenty fast, highly flexible and gives you all the XML features you might ever need. :) Stefan From paul.hankin at gmail.com Wed Sep 26 18:44:16 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 26 Sep 2007 22:44:16 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <1190805297.182232.116830@50g2000hsm.googlegroups.com> <1190815180.945099.248670@n39g2000hsh.googlegroups.com> <1190816657.574437.80980@g4g2000hsf.googlegroups.com> <1190820026.299569.110250@n39g2000hsh.googlegroups.com> Message-ID: <1190846656.770087.173230@19g2000hsx.googlegroups.com> On Sep 26, 9:52 pm, Duncan Booth wrote: > Paul Hankin wrote: > >> So should Duncan's > > >> def __removekey(self, key): > >> if key in self.__addkeys: > >> del self.__addkeys[key] > >> else: > >> self.__delkeys.add(key) > > >> be changed to: > > >> def __removekey(self, key): > >> if key in self.__addkeys: > >> del self.__addkeys[key] > >> self.__delkeys.add(key) > > > Yes, and the same in __addkey: if it's in __delkeys it should be > > removed from there, and added to __addkeys. There's an invariant: any > > key is in at most one of __addkeys and __delkeys. > > No, don't do that. The code was fine as I had written it, except for the > minor point that sets don't support 'del'! Also there need to be some tests > which actually exercise those two branches of the code: once you add > appropriate tests it will become obvious that you really do need the else. > > A key which is in dict must be either in __keycache or in __addkeys, but > never in both. Yes, I'm sorry: you're right. But there's a different bug: if you delete a key that's not in the dict, you'll add it to the deleted list before the exception for the missing key is raised. sd = sorteddict.sorteddict() sd['a'] = 'a' print sd.keys() = ['a'] try: del sd['b'] except: pass sd['b'] = 'b' print sd.keys() The second print statement produces ['a'] rather than ['a', 'b'] -- Paul Hankin From chris.monsanto at gmail.com Fri Sep 21 18:22:02 2007 From: chris.monsanto at gmail.com (chris.monsanto at gmail.com) Date: Fri, 21 Sep 2007 22:22:02 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190412475.772358.109810@n39g2000hsh.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> Message-ID: <1190413322.962737.53900@r29g2000hsg.googlegroups.com> On Sep 21, 6:07 pm, Cristian wrote: > On Sep 21, 2:48 pm, chris.monsa... at gmail.com wrote: > > > > > There are already anonymous functions in Python. > > > lambda x, y, z: x + y + z > > > is the same as: > > > def _(x, y, z): return x + y + z > > > As for the method stuff, check out staticmethod(). If you assign > > staticmethod() to an object, it will be treated as a > > normal function and not as a "method." > > > I have my own personal opinions about how methods should be in Python, > > but, whatever. It's weird to deal with stuff like this: > > > x.y = re.match # Assign a function to an attribute of a class, but it > > doesn't work because you can't assign anything but methods! > > x.y = staticmethod(re.match) # Ugly > > True, there is lambda, but that is very limited. It might be useful > for key arguments, but not much else. It doesn't solve the teaching > problem of "See, functions are just like any other data type. You can > assign it to a variable." It would be a footnote if it's mentioned at > all. My hope is to subtly reinforce the notion that functions are data > and can be passed around. The current function declaration doesn't > help with this. Creating a function and assigning it to a name is > exactly what Python does, why not have it come out in the syntax? It's > not necessary, yes, but I think it would be helpful for teaching > purposes. > > Again, it's not necessary as much as it's more intuitive and obvious > what's going on. This helps a beginner sort out the process from the > syntax without taking it on faith. They can see the class declaration > and see "I'm defining just another attribute to this class only this > time it happens to be method". > > There is nothing functionally lacking in Python. I'm just curious if > there's anything Python can do syntax-wise to help a person better > grasp programming ideas and Python's inner workings. Guido apparently doesn't like lambda; I'm not really sure why, it's extremely useful. There were rumors of it leaving in Python 3000, but thankfully there was the decision to keep them. (I have a feeling if they weren't kept in, a project fork would have happened or such.) Anyway, one of the biggest problems implementation wise is indentation in an expression - there is no expression currently that uses significant whitespace. Python draws a pretty clear line between expression and statement. I do agree with you however, it seems as if there is an arbitrary line between function definitions and normal variable assignment that shouldn't be there for the sake of consistency. A question: if you WERE to implement function definitions as normal expressions, how would you go about embedding it within an expression? x = map(def a: , [1, 2, 3]) It looks hideous in my opinion and lining up the , with the def is ugly. Not to mention currently, inside groupings, whitespace is ignored. How would you handle a whitespace signif. expression inside a grouping which by definition ignores whitespace? From jzgoda at o2.usun.pl Mon Sep 3 17:58:58 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 03 Sep 2007 23:58:58 +0200 Subject: Let's Unite Against Jews and Mongrels! In-Reply-To: <203fd3ln96hpvqt8ha1vm99frauso8fm8l@4ax.com> References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> <13d7kfckusd3kb3@corp.supernews.com> <203fd3ln96hpvqt8ha1vm99frauso8fm8l@4ax.com> Message-ID: Barry OGrady napisa?(a): > What could anyone have against mongrels? You clearly don't know how abusive ROR can be. -- Jarek Zgoda http://jpa.berlios.de/ From kar1107 at gmail.com Wed Sep 19 19:26:10 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Wed, 19 Sep 2007 23:26:10 -0000 Subject: Sets in Python In-Reply-To: <1190239608.835359.51150@22g2000hsm.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <1190239608.835359.51150@22g2000hsm.googlegroups.com> Message-ID: <1190244370.741482.6540@y27g2000pre.googlegroups.com> On Sep 19, 3:06 pm, Paddy wrote: > On Sep 19, 9:58 pm, Karthik Gurusamy wrote: > > > Since we know hashing is used, all that is needed is, a well-defined > > way to construct a hash out of a mutable. "Given a sequence, how to > > get a hash" is the problem. If later the given sequence is different, > > that's not the dict's problem. > > Oh it is possible to construct a hash from a mutable. What is > difficult is creating the same hash when the mutable mutates. Why? There is no reason that the dict should maintain the same hash, after all the user is calling with a different sequence as key (after the mutation). There seems to be an underlying assumption that the dictionary key- >value mapping should somehow maintain the mapping even when the key changes behind its back. The contract could very well be, hey if you give me a different sequence later (by mutating the one you added), don't expect me to find it in the dictionary. >Or > indeed working out what it means when a hash key mutates and you > access the dictionary. > Ignoring this gives the programmer a big problem hence the limitation. > > I don't think you have a better solution. But why would a programmer expect to find the match, when his/her code has changed the sequence (or has somehow let the hash key mutate) from the time of dictionary addition. If I did, a = [10, 20] and I did d[a]= 'foo', then a.append(30). If dict complains key error on d[a] now, I won't be surprised. If I do d[[10, 20, 30]], I will be surprised if it doesn't find the item. Of course, in today's behavior the above is syntax error. Karthik > > - Paddy. From claird at lairds.us Wed Sep 12 11:14:35 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 12 Sep 2007 15:14:35 +0000 Subject: Basic GUI References: <1189569282.372083.264560@57g2000hsv.googlegroups.com> <1189603073.639193.193390@19g2000hsx.googlegroups.com> Message-ID: In article <1189603073.639193.193390 at 19g2000hsx.googlegroups.com>, wrote: . . . >You can also use threads, which is a little bit more portable than >using Python's fork methodology, or so I've read. The concepts on this >page can be applied to any GUI toolkit you choose: >http://wiki.wxpython.org/LongRunningTasks > >I've used them with wxPython, but iirc, Lutz does something quite >similar with Tkinter in his latest edition of "Programming Python". > >I think what Michele is referring to is the subprocess module, which >is also useful. > >Mike > Let's make it even more definite: read for details about the subprocess module. Don, you describe do-something-and-retrieve-the- results, and ask about inter-task communications. We can give more pointed advice with just a few more details: is it OK for your application to block during a do-something-and-retrieve-the-results sequence? Is it acceptable, for example, that some- one push a button on your GUI, Python directs an HTTP query, then the GUI freezes until the answer returns? If your application can behave so, the programming will be more direct than if you require the retrievals to be done "in the background" while the GUI remains "live". From http Thu Sep 27 21:52:38 2007 From: http (Paul Rubin) Date: 27 Sep 2007 18:52:38 -0700 Subject: Python 3.0 migration plans? References: Message-ID: <7x641vh7yx.fsf@ruckus.brouhaha.com> Steve Holden writes: > So what we need is a poll on what the questions should be. I *love* c.l.py. One of the offered answers to the current question should be "never". That is, I'm hoping to skip 3.0 and switch directly to PyPy. From zentraders at gmail.com Sun Sep 2 10:43:24 2007 From: zentraders at gmail.com (Zentrader) Date: Sun, 02 Sep 2007 14:43:24 -0000 Subject: Let's Unite Against Jews and Mongrels! In-Reply-To: <46D40BFE.2020301@comcast.net> References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> <1188300284.507909.126770@57g2000hsv.googlegroups.com> <46D40BFE.2020301@comcast.net> Message-ID: <1188744204.822322.198360@57g2000hsv.googlegroups.com> On Aug 28, 4:50 am, "Richard B. Gilbert" wrote: >> Unless, of course, someone has a working "Killbot". If anyone has such > a thing, please kill that "MI5victim" moron as well! I reported MI5victim to spam at uce.gov and it appears to be gone, as well as the "free air conditioner"'s posts. (Thanks Steve Holden for the reminder that it doesn't have to be personal e-mail spam in order to be reported). If the OP posts again, report it. Something like 75% of internet mail is spam. From mensanator at aol.com Sun Sep 16 20:58:09 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 16 Sep 2007 17:58:09 -0700 Subject: Try this In-Reply-To: <1189984913.956999.163100@n39g2000hsh.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> Message-ID: <1189990689.259451.232570@g4g2000hsf.googlegroups.com> On Sep 16, 6:21?pm, John Machin wrote: > On Sep 17, 8:53 am, "mensana... at aol.com" wrote: > > > > > > > On Sep 16, 5:28?pm, John Machin wrote: > > > > On Sep 17, 7:54 am, "mensana... at aol.com" wrote: > > > > > On Sep 16, 2:22?pm, Steve Holden wrote: > > > > > > mensana... at aol.com wrote: > > > > > > On Sep 16, 1:10?pm, Dennis Lee Bieber wrote: > > > > > >> On Sun, 16 Sep 2007 01:46:34 -0700, GeorgeRXZ > > > > > >> declaimed the following in comp.lang.python: > > > > > > >>> Then Open the Notepad and type the following sentence, and save the > > > > > >>> file and close the notepad. Now reopen the file and you will find out > > > > > >>> that, Notepad is not able to save the following text line. > > > > > >>> Well you are speed > > > > > >>> This occurs not only with above sentence but any sentence that has > > > > > >>> 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) > > > > > >> I tried. I also opened the saved file in SciTE... > > > > > >> And the text WAS there... > > > > > > >> It is Notepad that can not properly render what it, > > > > > >> itself, saved. > > > > > > > C:\Documents and Settings\mensanator\My Documents>type huh.txt > > > > > > Well you are speed > > > > > > > Yes, file was saved correctly. > > > > > > But reopening it shows 9 unprintable characters. > > > > > > If I copy those to a new file (huh1.txt): > > > > > > > C:\Documents and Settings\mensanator\My Documents>type huh1.txt > > > > > > ????????? > > > > > > > But wait...the new file is 20 characters, not 9. > > > > > > > 09/16/2007 01:44 PM 18 huh.txt > > > > > > 09/16/2007 01:54 PM 20 huh1.txt > > > > > > > C:\Documents and Settings\mensanator\My Documents>dump huh.txt > > > > > > huh.txt: > > > > > > 00000000 5765 6c6c 2079 6f75 2061 7265 2073 7065 Well you are spe > > > > > > 00000010 6564 ed > > > > > > > Here's what it's actually doing: > > > > > > > C:\Documents and Settings\mensanator\My Documents>dump huh1.txt > > > > > > huh1.txt: > > > > > > 00000000 fffe 5765 6c6c 2079 6f75 2061 7265 2073 .~Well you are s > > > > > > 00000010 7065 6564 peed > > > > > > One word: Unicode. > > > > > > The "open" and "save" dialogs allow you to specify an encoding. > > > > > And the encoding specified was ANSI. > > > > > > If you > > > > > specify Unicode the you will get what you see above. > > > > > And if you specify ANSI _before_ you click the file name, > > > > the specification switches to Unicode and has to then > > > > be manually switched back to ANSI. > > > > > > If you specify ANSI > > > > > you will get the text you entered. > > > > > It's still a bug in the "open" dialog. > > > > It's more like a bug/feature in its encoding detector. > > > It is NOT a feature. If I save something as ANSI, > > there is no excuse for it not to re-open in ANSI. > > It doesn't know that you or anybody else saved it as "ANSI". All it is > seeing is a string of bytes. > > If you are silly enough to type in > [that's "\xef\xbb\xbf" repeated a few times] > and save it as "ANSI", it has every excuse to open it as something > else :-) > Did you notice that those three bytes all have bit 7 set? So they are not ASCII. There is no excuse to treat a string of ASCII codes as anything other than ASCII without specific direction from the user. > > > > I can get it to > > > switch to Unicode only if there's an even number of characters AND the > > > line is NOT terminated by CRLF -- add/remove one alpha character, or > > > hit the enter key at the end of the line, and it won't detect it as > > > Unicode when you open it again. > > > > You only get the BOM (0xfffe) if you are silly enough to save it while > > > it's open in Unicode mode. > > > That was a test. I wasn't so stupid as to save > > to the original file, but to make a copy. > > > > > > By the way, this has precisely what to do with Python? > > > > > I've been known to use Notepad to create Python > > > > source code. > > > > Your source code would have to be trivially short to trigger the > > > strange behaviour. > > > Makes you wonder what other edge cases aren't > > handled properly. > > > Makes you wonder why Microsoft doesn't employ > > professional programmers. > > I'm eagerly awaiting publication of your professional specification > for correctly detecting the encoding of an arbitrary stream of > bytes The very presence of an algorithm to detect encoding is a bug. Files with they .txt extension should always be treated as ANSI even if they contain binary data. Notepad should never be allowed to try to decide what the encoding is if the the open dialog has the encoding set to ANSI. From paul.ainsworth at baesystems.com Wed Sep 26 07:09:17 2007 From: paul.ainsworth at baesystems.com (Paul D Ainsworth) Date: Wed, 26 Sep 2007 12:09:17 +0100 Subject: Return status from methods in socket class Message-ID: <46fa3a39$1_1@glkas0286.greenlnk.net> As part of a debugging investigation I would like to be able to display the return status from various methods in the socket class. The methods I'm using are accept, bind, connect, listen, send, recv although not necessarily in that order. Is this possible and if so, how? TIA, Paul. From jstroud at mbi.ucla.edu Tue Sep 18 05:41:10 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 18 Sep 2007 02:41:10 -0700 Subject: raw string In-Reply-To: References: Message-ID: <7ZMHi.8465$z_5.4637@nlpi069.nbdc.sbc.com> Konstantinos Pachopoulos wrote: > Hi, > i am trying to execute the following query on a DB: > qe.execQuery(r"SELECT * FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY > '"' LINES TERMINATED BY '\n' FROM Commiter") > > However, whether i put the r in the front or not, i always get an error > about the "\n". > What's wrong? Try Triple-quoting the whole thing (you have an un-escaped " in your present version): r"""SELECT[yadda][yadda]Commtter"""" James From debl2NoSpam at verizon.net Sat Sep 1 01:31:00 2007 From: debl2NoSpam at verizon.net (David Lees) Date: Sat, 01 Sep 2007 05:31:00 GMT Subject: HowTo Use Cython on a Windows XP Box? In-Reply-To: <1188623610.532790.114000@o80g2000hse.googlegroups.com> References: <1188618022.208258.15620@22g2000hsm.googlegroups.com> <1188623610.532790.114000@o80g2000hse.googlegroups.com> Message-ID: John Machin wrote: > On Sep 1, 1:40 pm, Paul McGuire wrote: >> On Aug 31, 9:06 pm, David Lees wrote: >> >>> August 31, 2007 >>> I just downloaded the current Cython release and have no problem running >>> the cpython.py translator on the demo code. But when I try compiling, I >>> get an error complaining that my version of Python (which is the current >>> 2.5.1 downloaded from python.org) was compiled with Visual C++ 2003. I >>> only have Visual C++ 2005 on my machine and am unable to find a download >>> of 2003 on the Microsoft site (no big surprise). I have never built >>> Python from source. Is it necessary or can someone suggest an alternative? >>> TIA >>> david lees >> Unless you are customizing Python (and you can accomplish a *lot* >> without doing so), it is not necessary to build Python from source. >> Download one of the pre-built Windows binaries and install it, or get >> the Win Python distribution from ActiveState and install that. Then >> start writing your own Python demo scripts. >> > > Paul, AFAICT the OP is referring not to CPython, but to Cython, which > is a Pyrex fork. See http://www.cython.org/ > > Building CPython from source is likely to be a red herring. The OP's > question appears to be "How do I, on Windows, compile C code generated > by Cython into a pyd that will play happily with the standard-issue > python.exe and python25.dll?", and is probably best directed to one of > the 3 forums mentioned on the above-referenced page. > > HTH, > John > > > > John, Yes, you are correct in understanding my question. I thought my post was clear, but I guess not. I will go try the pyrex list. From steve at REMOVE-THIS-cybersource.com.au Fri Sep 7 23:24:54 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Sep 2007 03:24:54 -0000 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> <7x3axq7a8a.fsf@ruckus.brouhaha.com> <13e3us269f59s7a@corp.supernews.com> <7xd4wt99yv.fsf@ruckus.brouhaha.com> Message-ID: <13e45g6tljmfc32@corp.supernews.com> On Fri, 07 Sep 2007 19:17:44 -0700, Paul Rubin wrote: >> Here's something which is a little less predictable than a straight >> counter: > > It's still very easy to generate valid id's from that, or guess the next > one with non-negligible probability. Well, in my specific application, the only consequences of guessing a valid id is that you get to congratulate yourself for guessing a valid id :) As it turned out, I decided that since the only reason I had for avoiding consecutive ids was that they didn't look random, and that this would not really matter because no human being (including myself) was actually going to be looking at them except during debugging, I used the intertools.count() solution. Thanks to all who replied. -- Steven. From attn.steven.kuo at gmail.com Fri Sep 7 11:03:09 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Fri, 07 Sep 2007 08:03:09 -0700 Subject: exponential float formmating In-Reply-To: <1189170499.945175.275210@57g2000hsv.googlegroups.com> References: <1189170499.945175.275210@57g2000hsv.googlegroups.com> Message-ID: <1189177389.629836.250660@57g2000hsv.googlegroups.com> On Sep 7, 6:08 am, zunbe... at gmail.com wrote: > Hi, > > For compatibility reasons with an old program I have to format string > in exponential > format with the following format > > 0.xxxxxE-yy > > This means that the number start always by 0 and after the exponent > there should be alway the sing and 2 number for the exponent. > > for example 13 shoud be 0.13000E+02 > I always get 1.30000E001 > Perhaps it would then be worthwhile to subclass float? import math class ffloat(float): """Formatted float?""" def __str__(self): prefix = (self < 0) and '-' or '' fabs = math.fabs(self) exponent = math.floor(math.log10(fabs)) + 1 significand = fabs / math.pow(10, exponent) width = exponent > 0 and 2 or 3 return '%s%fE%0*d' % (prefix,significand,width,exponent) f = ffloat(13) print f f = ffloat(-12.23e-4) print f -- Hope this helps, Steven From mbratcher at cclpcitrus.com Fri Sep 28 10:48:58 2007 From: mbratcher at cclpcitrus.com (Mark Bratcher) Date: Fri, 28 Sep 2007 10:48:58 -0400 Subject: Emailing the attachment created with the Quick Screenshots Script(Python + PIL) Message-ID: <000001c801de$b670c370$eafca8c0@tfccorp.intra> I tried the suggestion at the other end of this link without any luck. Does anyone have a working script which will send the screenshot file created by the Quick Screenshots Script (Python + PIL)? I receive errors like access denied errors and not defined errors. See the second example from the email package; it creates a MIME message with an attachment and sends it using SMTP. Mark Bratcher Consolidated Citrus, LP 4210-250 Metro, Parkway Fort Myers, FL 33916 239-275-4060 ext 219 -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregpinero at gmail.com Wed Sep 12 11:09:02 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Wed, 12 Sep 2007 15:09:02 -0000 Subject: Get Only the Last Items in a Traceback In-Reply-To: References: <1189562968.529414.27910@w3g2000hsg.googlegroups.com> Message-ID: <1189609742.781671.143320@g4g2000hsf.googlegroups.com> On Sep 12, 5:17 am, Peter Otten <__pete... at web.de> wrote: > > Your assessment is wrong. You only get the extra lines in the traceback if > you don't immediately wrap the exec statement in a try ... except block: > > $ cat snip_traceback1.py > import traceback > > def alpha(): > try: > beta() > except Exception, e: > traceback.print_exc() > > def beta(): > gamma() > > def gamma(): > exec s in {} > > s = """ > def delta(): > epsilon() > > def epsilon(): > 1/0 > delta() > """ > > if __name__ == "__main__": > alpha() > > $ python snip_traceback1.py > Traceback (most recent call last): > File "snip_traceback1.py", line 5, in alpha > beta() > File "snip_traceback1.py", line 10, in beta > gamma() > File "snip_traceback1.py", line 13, in gamma > exec s in {} > File "", line 7, in > File "", line 3, in delta > File "", line 6, in epsilon > ZeroDivisionError: integer division or modulo by zero > > So the first step is to move the try ... except closer to the exec: > > $ cat snip_traceback2.py > import traceback > > def alpha(): > beta() > > def beta(): > gamma() > > def gamma(): > try: > exec s in {} > except Exception, e: > traceback.print_exc() > > s = """ > def delta(): > epsilon() > > def epsilon(): > 1/0 > delta() > """ > > if __name__ == "__main__": > alpha() > > $ python snip_traceback2.py > Traceback (most recent call last): > File "snip_traceback2.py", line 11, in gamma > exec s in {} > File "", line 7, in > File "", line 3, in delta > File "", line 6, in epsilon > ZeroDivisionError: integer division or modulo by zero > > You are almost there. Now let's strip off the outermost traceback: > > $ cat snip_traceback3.py > import sys > import traceback > > def alpha(): > beta() > > def beta(): > gamma() > > def gamma(): > try: > exec s in {} > except Exception, e: > etype, value, tb = sys.exc_info() > traceback.print_exception(etype, value, tb.tb_next) > > s = """ > def delta(): > epsilon() > > def epsilon(): > 1/0 > delta() > """ > > if __name__ == "__main__": > alpha() > > $ python snip_traceback3.py > Traceback (most recent call last): > File "", line 7, in > File "", line 3, in delta > File "", line 6, in epsilon > ZeroDivisionError: integer division or modulo by zero > > Heureka. > > Peter Thanks for the help, Peter. That's exactly what I need. Now could I use your tb.tb_next trick a couple times and thus avoid moving the try/ except? -Greg From gagsl-py2 at yahoo.com.ar Thu Sep 6 12:01:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Sep 2007 09:01:36 -0700 Subject: reload(sys) In-Reply-To: <1189077209.646830.111990@19g2000hsx.googlegroups.com> References: <1188521143.421431.119100@l22g2000prc.googlegroups.com> <1188564816.430863.219560@w3g2000hsg.googlegroups.com> <1188662049.337034.58220@w3g2000hsg.googlegroups.com> <1189077209.646830.111990@19g2000hsx.googlegroups.com> Message-ID: <1189094496.120836.61870@o80g2000hse.googlegroups.com> On 6 sep, 08:13, S?nmez Kartal wrote: > On 3 Eyl?l, 05:40, Steven Bethard wrote: > > S?nmez Kartal wrote: > > > I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as > > > "f.write(str(xml))". At execution of that line, it gives error with > > > description, configure your default encoding... > > > Can you show the code where you populate the XMLBuilder? I'm guessing > > you're doing something like:: > > import xmlbuilder > > builder = xmlbuilder.XMLBuilder() > > builder.foo = dict(bar='? and ?') > > str(builder) > > > That breaks because the string '? and ?' is not properly encoded. Have > > you declared an encoding in your source file? PEP 263 shows you how: > http://rafb.net/p/RfaF8215.html > > products in the code is a list of dictionaries which are returned by > makeProduct function. > > I'm not typing or pasting those characters into my script. So, > declaring an encoding didn't make it. :-( But, your code excerpt > runned well. You should ensure that arguments to makeProduct are either: - unicode objects - ASCII strings If you got them from some other place, decode the strings as soon as possible into unicode. Read to understand what's happening (and why the XMLBuilder error message is *not* a good advice) -- Gabriel Genellina From miki.tebeka at gmail.com Sun Sep 9 02:34:45 2007 From: miki.tebeka at gmail.com (Miki) Date: Sun, 09 Sep 2007 06:34:45 -0000 Subject: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute In-Reply-To: <87k5r2zhd6.fsf@kip.sateh.com> References: <1189173455.525144.326300@y42g2000hsy.googlegroups.com> <87k5r2zhd6.fsf@kip.sateh.com> Message-ID: <1189319685.273092.31830@r34g2000hsd.googlegroups.com> > steps.sort(key = lambda s: s.time) This is why attrgetter in the operator module was invented. from operator import attrgetter ... steps.sort(key=attrgettr("time")) HTH, -- Miki http://pythonwise.blogspot.com From bignose+hates-spam at benfinney.id.au Wed Sep 19 22:00:40 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 20 Sep 2007 12:00:40 +1000 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <87k5qn5cwi.fsf@mulj.homelinux.net> Message-ID: <87y7f2w0xj.fsf@benfinney.id.au> Hrvoje Niksic writes: > Ben Finney writes: > > > Evan is claiming that "the next class in the MRO _is_ a superclass", > > apparently by his definition or some other that I've not seen. > > The definition of superclass is not the issue, the issue is > "superclass *of which class*"? You expect super(A, self) to iterate > only over superclasses of A, even when self is an instance of a > subtype of A. Yes. Those are the specific parameters to the function call, so that *is* what I expect. > What really happens is that super(A, self) yields the next method in > type(self)'s MRO, which can and does cause include classes that are > not by any definition superclasses of A. Then the function is misnamed, and implies that it does the former ("You expect ...") above, instead of the latter ("What really happens ..."). In its latter form, it is worthless to me when I'm looking for "get superclass of A", but its name and parameters and documentation all lead me very strongly to believe otherwise. -- \ "I put contact lenses in my dog's eyes. They had little | `\ pictures of cats on them. Then I took one out and he ran around | _o__) in circles." -- Steven Wright | Ben Finney From phil at freehackers.org Mon Sep 17 04:41:59 2007 From: phil at freehackers.org (BlueBird) Date: Mon, 17 Sep 2007 01:41:59 -0700 Subject: QPicture and Qpainter PyQt4 In-Reply-To: <1190014183.462244.135560@w3g2000hsg.googlegroups.com> References: <1190014183.462244.135560@w3g2000hsg.googlegroups.com> Message-ID: <1190018519.858640.100440@w3g2000hsg.googlegroups.com> Hi, It looks like you have several things wrong: On Sep 17, 9:29 am, luca72 wrote: > class Form(QWidget, Ui_Form): > [...] > > @pyqtSignature("") > def on_pushButton_clicked(self): > """ > Slot documentation goes here. > """ > # TODO: not implemented yet > #raise "Not implemented yet" > #gr = QtGui.QPainter() > picture = QtGui.QPicture() > gr = QtGui.QPainter() > gr.begin(picture) > gr.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine)) > gr.drawLine(70,100,150,100) > gr.end() > picture.save('dis.pic') > self.frame.update() Normally, you don't paint inside a slot. You paint inside the paintEvent() method which is called automatically by Qt when an area of your widget needs to be repainted. > from PyQt4.QtGui import QWidget > from PyQt4.QtCore import pyqtSignature > from PyQt4 import * > > class PictureFrame(QtGui.QFrame): > > def __init__(self, parent = None): > QFrame.__init__(self, parent) > picture = QtGui.QPicture() > > def paintEvent(self, event): > picture.load('dis.pic') > gr = QtGui.QPainter() > gr.begin(self.frame) > gr.drawPicture(0, 0, picture) > gr.end() Don't load a picture inside a paintevent. Loading is an expensive process, you don't want to repeat it all the time. Second, you should check that your picture was loaded. Sometimes, it's a file problem. Check the size of your picture for example. Third, I think you should have : gr.begin( self ) Else, the painter is not painting on your widget. Hope that helps. PHilippe From onurays23 at gmail.com Sat Sep 1 20:44:21 2007 From: onurays23 at gmail.com (onurays) Date: Sun, 2 Sep 2007 03:44:21 +0300 Subject: A big problem with _name_ == '_main_' References: Message-ID: Oh, i solve the problem. It should be double underscore.. I am so careless..! Onuray. "onurays" , haber iletisinde ?unlar? yazd?:fbd0g8$e3c$1 at aioe.org... > Hi, > > I have begun to teach me Python today. The problem is : > > NameError: name 'name' is not defined. > > I am using winXP and i used that: > > if _name_ == '_main_' : > MyClass() > gtk.main() > > Onuray. > From fabioztessitore at libero.it Mon Sep 3 12:02:08 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 03 Sep 2007 16:02:08 GMT Subject: How can I wait for all the threads I spawn for 5 minutes References: <1188603646.671414.272760@w3g2000hsg.googlegroups.com> Message-ID: <46dc3000$0$10623$4fafbaef@reader2.news.tin.it> > [cut] > But this code ends up waiting 5 minutes for **each** thread. that is > not what I want. I just want to wait for 5 minutes for all threads. how > can I do that? I've written a little code for you using threading. Hope it will help you: #! /usr/bin/env python # -*- coding: utf8 -*- import threading import time class MyLittleThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): time.sleep(5) if __name__ == "__main__": # create a list of 10 MyLittleThread # total time to wait is 5 sec (NOT 5sec*10) lt = [] for i in range(10): lt.append(MyLittleThread()) for th in lt: th.start() bye From wizzardx at gmail.com Sat Sep 8 18:02:44 2007 From: wizzardx at gmail.com (David) Date: Sun, 9 Sep 2007 00:02:44 +0200 Subject: How to insert in a string @ a index In-Reply-To: <1189288040.775913.8090@g4g2000hsf.googlegroups.com> References: <1189274564.462664.131240@22g2000hsm.googlegroups.com> <1189288040.775913.8090@g4g2000hsf.googlegroups.com> Message-ID: <18c1e6480709081502i542be4dbv27d58e5cdd7f02ad@mail.gmail.com> On 9/8/07, Zentrader wrote: > Same solution as above, but if you just want "Hello" and to not > include words containing "Hello", i.e. "Helloing" or "Unhello", then > you want to include a leading and/or trailing space. You can also use the re (regular expression) module to search for "hello" and make sure it's a complete word. You would use re to search for something like "\bhello\b". "\b" being regex for an empty string that only occurs at the start or beginning of a word. More information on python regexes here: http://www.amk.ca/python/howto/regex/ Here is an example from that page: >>> p = re.compile(r'\bclass\b') >>> print p.search('no class at all') >>> print p.search('the declassified algorithm') None >>> print p.search('one subclass is') None From steve at holdenweb.com Tue Sep 11 14:50:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 14:50:42 -0400 Subject: ValueError: insecure string pickle ? In-Reply-To: References: Message-ID: robert wrote: > cPickle.loads raised "ValueError: insecure string pickle". > The error is from a log file and I cannot reproduce it (quickly). > What can be the cause for that error? > > Robert Make sure that your pickle files are being read and written in binary mode ("rb" and "wb" as the second argument to open()). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From kyosohma at gmail.com Thu Sep 13 10:23:53 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 13 Sep 2007 07:23:53 -0700 Subject: Help to start python In-Reply-To: <1189693144.493878.130220@w3g2000hsg.googlegroups.com> References: <1189693144.493878.130220@w3g2000hsg.googlegroups.com> Message-ID: <1189693433.545822.89580@o80g2000hse.googlegroups.com> python_lover wrote: > Hi All, > > I'm new to python. I installed python 2.5 and IDLE 1.2.1 . I'm able > to run shell commands. > > But I don't know how to execute a python program using this. When I'm > opeing a py program a seperate IDLE window opeing with program text. > But I don't know to to execute the prg. > > Please help me on this . > > thank you > > regards > Sat When in IDLE, you can go to the Run menu and choose Run Module (or press F5) in the window that has the program code. Hope that helps! Mike From michele.simionato at gmail.com Wed Sep 12 03:47:51 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 12 Sep 2007 07:47:51 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> Message-ID: <1189583271.343615.305070@y42g2000hsy.googlegroups.com> On Sep 12, 9:33 am, Mark Summerfield wrote: > I feel that Python lacks one useful data structure: an ordered > dictionary. > > I find such data structures v. useful in C++. I know that in Python > the sort function is v. fast, but often I prefer never to sort but > simply to use an ordered data structure in the first place. > (I'm aware that for ordered lists I can use the bisect module, but I > want an ordered key-value data structure.) > > I think other people must find such things useful. There are three > implementations on the Python Cookbook site, and one on PyPI, all in > pure Python (plus I have my own implementation, also pure Python). > > I would suppose that it would be better if it was implemented in C--- > for example, my own pure Python ordered dict loads data about eight > times slower than the built-in dict. Nonetheless, I still find it > worth using for the convenience it offers. > > Do other Python programmers feel this lack? Is this worth a PEP? > Yes, this is a serious lack in the standard library. Michele Simionato From gazelle at xmission.xmission.com Sat Sep 1 10:49:14 2007 From: gazelle at xmission.xmission.com (Kenny McCormack) Date: Sat, 1 Sep 2007 14:49:14 +0000 (UTC) Subject: Important Research Project References: <13ddcvm1bsu3s94@corp.supernews.com> <46D6CA0E.E66ED5C8@yahoo.com> <13deq9nj9atft62@corp.supernews.com> Message-ID: In article , Keith Thompson wrote: >"E.D.G." writes: >> "CBFalconer" wrote in message >> news:46D6CA0E.E66ED5C8 at yahoo.com... >>> "E.D.G." wrote: >> >>> Where is Perl described in the C standard? This seems rather OT. >> >> It has been my experience that a person who is an expert with one computer >> language can usually do reasonably well when working with other languages. >> I am trying to find some people who can assist with getting a Perl program >> running. It would probably be easier for expert programmers in any language >> to help with this type of work compared with people such as myself who are >> not experts in any programming language. > >CBFalconer's point is that this newsgroup (comp.lang.c, where he and I >are both reading this) is for discussion of the C programming >language. If you want to discuss something other than C, please find >another forum. Massive cross-posts like this are rarely appropriate. IOW (for the OP and for the various readers in all these groups): The rod up Keith's butt has a rod up its butt. Note, incidentally, that this thread is yet the latest occurrence of a phenomenon that I've observed many times in the past, and have described here in clc on more than a few occasions. That is, somebody starts a thread, posted to several different groups, in the hope of getting help from at least one of them. The thread is pretty much on-topic for most of the groups, primarily because the keepers of most of the groups do not have rods up their butts. However, and this is the big however, one of the groups listed just happens to be clc, where rod-filled butts are the norm. The result is that all of the responses come from clc (including, of course, this one) and, as we see, it's all topicality BS, and nobody ever ends up discussing the original subject. Really a pity, that. From fredrik at pythonware.com Wed Sep 26 12:06:45 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 18:06:45 +0200 Subject: Asynchronous Messaging In-Reply-To: <1190819912.344267.52680@50g2000hsm.googlegroups.com> References: <1190807252.731074.141450@k79g2000hse.googlegroups.com> <1190819912.344267.52680@50g2000hsm.googlegroups.com> Message-ID: wink wrote: > But its performance is poor if the number of items on a > Queue becomes large because it is implemented using a list. > One of the things I was thinking of was doing another implementation > using of Queue which was based on deque. Updating from 2.3 to something newer will fix that, of course: $ more Queue.py ... from collections import deque ... class Queue: ... def _init(self, maxsize): self.maxsize = maxsize self.queue = deque() From bj_666 at gmx.net Thu Sep 6 03:47:04 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Sep 2007 07:47:04 GMT Subject: Using wild character References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> <1189058095.671230.262190@o80g2000hse.googlegroups.com> Message-ID: <5k9pjoF2mrncU1@mid.uni-berlin.de> On Wed, 05 Sep 2007 22:54:55 -0700, TheFlyingDutchman wrote: > To do a "*string" wildcard filter use the endswith() function instead > of startswith() and to do a *string* type wildcard filter use > the find() function > -1. Maybe better the ``in`` operator for the '*string*' type. `str.find()` will go away in the future. Ciao, Marc 'BlackJack' Rintsch From mickey at disney.com Tue Sep 11 18:47:43 2007 From: mickey at disney.com (Wiseman) Date: Tue, 11 Sep 2007 18:47:43 -0400 Subject: Python Problem References: Message-ID: Hi, OK - it works in WindowsXP. I installed "enchant" on my SuSE 10.0 (using YAST). The enchant Suse package looks like a general Linux package, not a Python specific. Running the program in Python I am getting the same error message from the line: "import enchant". ImportError: No module named enchant What am I missing? Thanks ((:-() Meir >Hi, > >The line: > >import enchant > >works perfectly OK when I call a Python progrma (sp.py) from IDLE >(WInXP). When I try to run it ftom the command line (python sp.py) the >response is: > >Traceback (most recent call last): > File "sp.py", line 3, in > import enchant >ImportError: No module named enchant > >Searching my computer (the whole of drive c:\) I could not find ANY >file called enchant.*. > >Does anyone know what is wrong? > >Thanks > >((:-() Meir > From Graham.Dumpleton at gmail.com Wed Sep 12 00:58:18 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 12 Sep 2007 04:58:18 -0000 Subject: Python 3K or Python 2.9? In-Reply-To: <87abrs7c6v.fsf@benfinney.id.au> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <7x7imwpn1u.fsf@ruckus.brouhaha.com> <87abrs7c6v.fsf@benfinney.id.au> Message-ID: <1189573098.290501.72630@50g2000hsm.googlegroups.com> On Sep 12, 2:14 pm, Ben Finney wrote: > Paul Rubin writes: > > TheFlyingDutchman writes: > > > Python user and advocate Bruce Eckel is disappointed with the > > > additions (or lack of additions) in Python 3: > > > >http://www.artima.com/weblogs/viewpost.jsp?thread=214112 > > > That article is pretty weak. > > It is responded to by Guido here: > > "A Response to Bruce Eckel" > In that blog, Guido says: """Concurrency: It seems we're now happily out exploring here. I'm looking forward to benchmarks showing that PP or similar (or dissimilar!) solutions actually provide a performance gain. Another route I'd like to see explored is integrating one such solution into an existing web framework (or perhaps as WSGI middleware) so that web applications have an easy way out without redesigning their architecture.""" Maybe I don't fully understand where Guido is coming from, but solutions for spreading web applications across multiple processes have been available for a long time in solutions such as mod_python and mod_fastcgi. With a view to improving further on these solutions mod_wsgi has also been created. All these solutions either use the multi process nature of the web server, or themselves use multiple daemon processes to which requests are distributed by Apache. End result is that one can make better use of multi processor or multi core machines. Also, when using multi threaded Apache worker MPM, because a lot of stuff is not even done in Python code, such as static file serving, multiple cores can even be used within the same process. Thus, in the larger context of how Apache is implemented and what web applications provide, the GIL isn't as big a problem as some like to believe it is as far as preventing proper utilisation of the machines resources. FWIW, I have blogged my own response to Guido's comment above at: http://blog.dscpl.com.au/2007/09/parallel-python-discussion-and-modwsgi.html Now over the years I have seen a lot of Python developers showing quite a dislike for using Python integrated with Apache. As a result the last thing people seem to want to do is fix such solutions up and make them work better. Reality is though that unless a very good solution for hosting Python with Apache comes up, you will probably never see good cheap commodity web hosting for Python. Older solutions simply aren't safe to use or are hard to set up and manage. Creating lots of distinct Python processes and proxying to them, like the purists would like to see, simply isn't going to happen as such setups are too hard to manage and use up too much resources on a large scale. Web hosting companies want something simple which they can integrate into their existing PHP focused Apache installations and which don't chew up huge amounts of additional resources, thereby forcing a reduction in their site densities. To that end, we still have a way to go. An older blog entry of mine where I have covered these problems is: http://blog.dscpl.com.au/2007/07/commodity-shared-hosting-and-modwsgi.html Graham From bj_666 at gmx.net Sat Sep 8 02:27:44 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Sep 2007 06:27:44 GMT Subject: Speed of Python References: Message-ID: <5ketn0F33dv5U1@mid.uni-berlin.de> On Fri, 07 Sep 2007 23:53:48 +0000, wang frank wrote: >>From: "Marc 'BlackJack' Rintsch" >>To: python-list at python.org >>Subject: Re: Speed of Python >>Date: 7 Sep 2007 23:17:55 GMT >> >>On Fri, 07 Sep 2007 22:59:26 +0000, wang frank wrote: >> >> > I also have tried to use numpy to speed it up. However, surprisingly, > it is >> > slower than the pure python code. >> > >> > Here is the code: >> > import numpy >> > arange=numpy.arange >> > nlog=numpy.log >> > def bench6(n): >> > for i in xrange(n): >> > for j in xrange(1000): >> > m=j+1 >> > z=nlog(m) >> > z1=nlog(m+1) >> > z2=nlog(m+2) >> > z3=nlog(m+3) >> > z4=nlog(m+4) >> > z5=nlog(m+5) >> > z6=nlog(m+6) >> > z7=nlog(m+7) >> > z8=nlog(m+8) >> > z9=nlog(m+9) >> > return z9 >> > >> > [??] >> > >> > Anyone know why? >> >>Because you don't really take advantage of `numpy`. The `numpy.log()` >>function can be used with scalars but I guess it is slower because it has >>to check if its argument is a scalar or array. Untested: >> >>from numpy import arange, log as nlog >> >>def bench6(n): >> for dummy in xrange(n): >> for j in xrange(1000): >> z = nlog(arange(j + 1, j + 11)) >> return z[-1] > > I am just trying to compare the speed with matlab. The arrange is used for > another test, that is why it shows up in the mail. I think I don't get what you are after. If you want to compare the speed of code that *calculates* the same values it doesn't have to *look* the same. So what's the point of importing `numpy` and its `log` function if you don't write the code in a fashion that takes advantage of the package at all!? And the other "pure" Python versions may gain some speed if you think Python and not Matlab with Python syntax. That might look like this: from math import log def bench42(n): the_range = xrange(1, 1001) for dummy in xrange(n): for i in the_range: z = [log(x) for x in xrange(i, i + 10)] return z[-1] Ciao, Marc 'BlackJack' Rintsch From nebulous99 at gmail.com Thu Sep 13 01:35:53 2007 From: nebulous99 at gmail.com (nebulous99 at gmail.com) Date: Thu, 13 Sep 2007 05:35:53 -0000 Subject: Car-ac-systems In-Reply-To: References: <1189511932.371621.112970@o80g2000hse.googlegroups.com> Message-ID: <1189661753.315182.53630@22g2000hsm.googlegroups.com> On Sep 11, 9:35 am, "John Timney \(MVP\)" wrote: > How do I control one with C# then! Thats not on your site, clearly not > everything I need to know then. Waste of a site! C# is just as off topic in comp.lang.java.programmer as car air- conditioning systems. The latter, however, have the redeeming characteristic that they are not the demonic spawn of evil Microsoft. From ldo at geek-central.gen.new_zealand Sat Sep 8 01:20:39 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 08 Sep 2007 17:20:39 +1200 Subject: exponential float formmating References: <1189170499.945175.275210@57g2000hsv.googlegroups.com> <5kd2q6F31i6hU4@mid.uni-berlin.de> <1189174673.600550.288440@50g2000hsm.googlegroups.com> Message-ID: In message <1189174673.600550.288440 at 50g2000hsm.googlegroups.com>, zunbeltz at gmail.com wrote: > In all cases I need the number to start with 0 > 0.13000E+01 So why not move the decimal point left one, and add one to the exponent. From bj_666 at gmx.net Thu Sep 6 04:07:24 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Sep 2007 08:07:24 GMT Subject: We need PIGs :) References: <46d74472$0$402$426a34cc@news.free.fr> <87hcm81dot.fsf@kip.sateh.com> Message-ID: <5k9qpsF2mrncU3@mid.uni-berlin.de> On Thu, 06 Sep 2007 09:00:02 +0200, Stefan Arentz wrote: > What I find really frustrating in Python (combined with usually bad > documentation) is that many people have different styles. The most > frustratinng being getFoo() vs .foo, vs get_foo(). `getFoo()` is discouraged by PEP 8. You don't have the choice between `.foo` and `.get_foo()` in Java because Java has no properties and people are trained to write getters and setters for everything. I like that choice in Python because I can write shorter code that is not cluttered with very simple getters and setters. Ciao, Marc 'BlackJack' Rintsch From aahz at pythoncraft.com Thu Sep 13 23:51:00 2007 From: aahz at pythoncraft.com (Aahz) Date: 13 Sep 2007 20:51:00 -0700 Subject: Decimal formatting References: <1189716651.810481.260850@y42g2000hsy.googlegroups.com> <1189717147.538624.189890@19g2000hsx.googlegroups.com> Message-ID: In article <1189717147.538624.189890 at 19g2000hsx.googlegroups.com>, mensanator at aol.com wrote: > >>>> a >12.33333 >>>> print '%0.2f' % a >12.33 >>>> a = 1 >>>> print '%0.2f' % a >1.00 >>> '%.2f' % 1 '1.00' -- 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 http://www.lysator.liu.se/c/ten-commandments.html From kyosohma at gmail.com Thu Sep 20 11:30:58 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 20 Sep 2007 15:30:58 -0000 Subject: Finding prime numbers In-Reply-To: References: <1190218927.7991.25.camel@apprentice-laptop> <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> <1190219929.7991.28.camel@apprentice-laptop> <2dc0c81b0709191013k181d1a74m76a08cecadb005c4@mail.gmail.com> <1190225821.182650.227540@k79g2000hse.googlegroups.com> Message-ID: <1190302258.922419.113030@w3g2000hsg.googlegroups.com> On Sep 19, 1:31 pm, "Shawn Milochik" wrote: > > If you'd just search the archives, you would have found this: > > >http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Yeah, but that's no fun. ;o) Yes! Never do what you can fool others into doing for you. Mike From bjorn.kempen at gmail.com Sat Sep 15 18:06:17 2007 From: bjorn.kempen at gmail.com (buffi) Date: Sat, 15 Sep 2007 22:06:17 -0000 Subject: Needless copying in iterations? In-Reply-To: References: Message-ID: <1189893977.487320.231700@n39g2000hsh.googlegroups.com> On Sep 15, 11:58 pm, James Stroud wrote: > Hello all, > > I was staring at a segment of code that looked like this today: > > for something in stuff[x:y]: > whatever(something) > > and was wondering if the compiler really made a copy of the slice from > stuff as the code seems to suggest, or does it find some way to produce > an iterator without the need to make a copy (if stuff is a built-in > sequence type)? Or would it be more efficient to do the more clumsy (in > my opinion): > > for i in xrange(x, y): > whatever(stuff[i]) > > James itertools.islice does what you want import itertools for something in itertools.islice(stuff, x, y): whatever(something) From bbansi_1982 at yahoo.com Wed Sep 26 03:34:42 2007 From: bbansi_1982 at yahoo.com (bbansi_1982 at yahoo.com) Date: Wed, 26 Sep 2007 00:34:42 -0700 Subject: unable to load dco2 in python Message-ID: <1190792082.126432.51360@n39g2000hsh.googlegroups.com> Hi, I have built DCOracle2 with python. But when i try to import dco2 inside python prompt it gives me the error Failed to load dco2.sl although it has been built properly and dlopen is also able to load the shared library without any unresolved symbols. The machine details are as follows: Machine: HP-UX dafne B.11.23 U ia64 Compiler: HP aC++/ANSI C B3910B A.06.05 Python version: 2.4 DCOracle2 version: 2-1.2 Oracle version: Oracle10g I am pasting the error that i am getting on my machine below: Python 2.4 (#4, Nov 16 2005, 09:24:18) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> import dco2 Traceback (most recent call last): File "", line 1, in ? ImportError: Failed to load dco2.sl Please help me in resolving the same. Thanks, Anil From python at hope.cz Fri Sep 14 15:51:22 2007 From: python at hope.cz (Johny) Date: Fri, 14 Sep 2007 12:51:22 -0700 Subject: Https conversation - debug? Message-ID: <1189799482.314951.238470@r34g2000hsd.googlegroups.com> Is there any good sniffer for https protocol? How can be watched https conversation? Thanks for reply L. From http Sun Sep 23 15:31:51 2007 From: http (Paul Rubin) Date: 23 Sep 2007 12:31:51 -0700 Subject: Untrusted python code References: Message-ID: <7xwsuh9o0o.fsf@ruckus.brouhaha.com> Thomas Dybdahl Ahle writes: > Hi, I have an application for which I want users to be able to make > themes. > I've planed a rather advanced model (in xml), which gives themes the > option to redefine various drawing methods. > Now I don't want those themes to be able to take over the current user, > but I'd still like the scripts to be able to import stuff like math. > Is there a way to ensure no IO and other dangerous stuff is done? No. There used to be something called rexec/bastion but it was removed because it was insecure. You might look at http://webpy.org which is a web kit written in Python, that has its own sandboxed interpreter for a Python-like user templating language, for doing what you're doing. You could also consider using something like client side XSLT. From steve at REMOVE-THIS-cybersource.com.au Tue Sep 4 11:55:32 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 04 Sep 2007 15:55:32 -0000 Subject: parameter list notation References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> Message-ID: <13dqvvk42v5ujfd@corp.supernews.com> On Mon, 03 Sep 2007 22:00:28 -0700, TheFlyingDutchman wrote: > I am trying to use a database written in Python called buzhug. > > In looking at some of the functions I see this prototype: > > def create(self,*fields,**kw): > > I am not clear on what the * and the ** are for or what they represent. > Or, what are they referred to as so I can do a query for information on > them. And yet you're making your own fork of Python. Good luck with that! Do let us know how it works out for you. For the record, your question is answered in the FAQ: http://www.python.org/doc/faq/programming/ and in the tutorial: http://docs.python.org/tut/node6.html -- Steven. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 7 03:28:26 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 07 Sep 2007 09:28:26 +0200 Subject: why should I learn python In-Reply-To: <1189126109.189507.150580@w3g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> <1189119676.239459.325280@w3g2000hsg.googlegroups.com> <1189126109.189507.150580@w3g2000hsg.googlegroups.com> Message-ID: <46e0fd95$0$2273$426a74cc@news.free.fr> TheFlyingDutchman a ?crit : > On Sep 6, 4:01 pm, windandwaves wrote: (snip) >> but because I am really not much of a >> programmer, it is often too detailed for me). I have limited time, >> but it does sound like something to learn, just for fun and for >> practical use. How would you use it in a web development >> environment? > > Python can be used as an apache module called mod_python and also as a > CGI language. And also with fast-cgi, or wsgi, or as it's own HTTP server, etc... From bdesth.quelquechose at free.quelquepart.fr Sat Sep 8 12:52:20 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 08 Sep 2007 18:52:20 +0200 Subject: Enum class with ToString functionality In-Reply-To: <1189425154.788466.132370@d55g2000hsg.googlegroups.com> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <1189425154.788466.132370@d55g2000hsg.googlegroups.com> Message-ID: <46e59bf7$0$21897$426a74cc@news.free.fr> TheFlyingDutchman a ?crit : > On Sep 10, 2:28 am, bg... at yahoo.com wrote: > >>Hi, >> >>I have the following class - >> >>class TestOutcomes: >> PASSED = 0 >> FAILED = 1 >> ABORTED = 2 >> >>plus the following code - >> >>testResult = TestOutcomes.PASSED >> >>testResultAsString >>if testResult == TestOutcomes.PASSED: >> testResultAsString = "Passed" >>elif testResult == TestOutcomes.FAILED : >> testResultAsString = "Failed" >>else: >> testResultAsString = "Aborted" >> >>But it would be much nicer if I had a function to covert to string as >>part of the TestOutcomes class. How would I implement this? >> >>Thanks, >> >>Barry > > > class TestOutcomes: > PASSED = 0 > FAILED = 1 > ABORTED = 2 > > def ToString(outcome): > if outcome == TestOutcomes.PASSED: > return "Passed" > elif outcome == TestOutcomes.FAILED : > return "Failed" > else: > return "Aborted" > > ToString = staticmethod(ToString) > > if __name__ == "__main__": > testResult = TestOutcomes.PASSED > testResultAsString = TestOutcomes.ToString(testResult) > print testResultAsString > print TestOutcomes.ToString(testResult) > Technically correct, but totally unpythonic. May I suggest some reading ? http://dirtsimple.org/2004/12/python-is-not-java.html From news at sandipan.com Sun Sep 2 12:14:03 2007 From: news at sandipan.com (Sandipan News) Date: Sun, 2 Sep 2007 12:14:03 -0400 Subject: Pythonwin Install COM exceptions on Windows Vista Ultimate In-Reply-To: <00a701c7eaa6$d13c01f0$73b405d0$@com> References: <46d578dc$0$25911$ba4acef3@news.orange.fr> <00a701c7eaa6$d13c01f0$73b405d0$@com> Message-ID: <000001c7ed7c$4a688580$df399080$@com> Here are some steps I used to finally successfully install Python and Pythonwin on Vista Ultimate: 1. Uninstalled Python (could not see a way to uninstall Pythonwin) 2. Installed Python again (.MSI does not provide option to run as Administrator) 3. Rebooted computer 4. Installed Pythonwin with right click option "Run as Administrator" - This was different from the last time I installed this. Copied pythoncom25.dll to C:\Windows\system32\pythoncom25.dll Copied pywintypes25.dll to C:\Windows\system32\pywintypes25.dll Registered: Python.Interpreter Registered: Python.Dictionary Registered: Python -> Software\Python\PythonCore\2.5\Help[None]=None -> Software\Python\PythonCore\2.5\Help\Pythonwin Reference[None]='C:\\Python25\\Lib\\site-packages\\PyWin32.chm' Shortcut for Pythonwin created Shortcut to documentation created The pywin32 extensions were successfully installed. This time, no errors. 5. Started up a Python script from a directory using right-click | Open With | Pythonwin.exe and it works fine. Earlier it was giving an error about not being able to locate win32ui.pyd. I did not touch UAC or Router/Rooter/Firewall ... I did not know how to. Thanks. Sandipan -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of Sandipan News Sent: Wednesday, August 29, 2007 9:41 PM To: 'M?ta-MCI (MVP)'; python-list at python.org Subject: RE: Pythonwin Install COM exceptions on Windows Vista Ultimate How do I deactivate UAC and Router? I did run as Administrator and installed both Python and Pythonwin into c:\Python25\ This is the error I got ... Here is the log at the end of the install: Copied pythoncom25.dll to C:\Outils\Python\pythoncom25.dll Copied pywintypes25.dll to C:\Outils\Python\pywintypes25.dll You do not have the permissions to install COM objects. The sample COM objects were not registered. -> Software\Python\PythonCore\2.5\Help[None]=None -> Software\Python\PythonCore\2.5\Help\Pythonwin Reference[None]='C:\\Outils\\Python\\Lib\\site-packages\\PyWin32.chm' Creating directory C:\Outils\Python\Lib\site-packages\win32com\gen_py Shortcut for Pythonwin created Shortcut to documentation created The pywin32 extensions were successfully installed. Thanks. Sandipan -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of M?ta-MCI (MVP) Sent: Wednesday, August 29, 2007 9:19 AM To: python-list at python.org Subject: Re: Pythonwin Install COM exceptions on Windows Vista Ultimate Hi! Perso, on Vista, I : - deactive UAC - deactive firewall (I have a rooter) - run all like Administrator - install all in other DIR than "Program Files" Result : no problem. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list From ldo at geek-central.gen.new_zealand Sun Sep 23 22:43:56 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 24 Sep 2007 14:43:56 +1200 Subject: An Editor that Skips to the End of a Def References: <87odfxjgjy.fsf@pobox.com> <3Md*NJqVr@news.chiark.greenend.org.uk> Message-ID: In message , Manuel Graune wrote: > Matthew Woodcraft writes: > >> Lawrence D'Oliveiro wrote:> >> >>> >> > And "cursor keys"? Please, every self respecting editor has ways for > moving around quite a bit more efficiently. > > And on top of that a use case, which no one in his right mind would > do this way. Accomplishing this task with search-and-replace would > have taken about 10 seconds. With Mouse or Keyboard. Just to reinforce the point that the above was in no way an artificial or isolated case: From aleax at mac.com Mon Sep 10 01:11:09 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 9 Sep 2007 22:11:09 -0700 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <1189020188.842700.50950@d55g2000hsg.googlegroups.com> <1189108607.080926.103650@19g2000hsx.googlegroups.com> <1189183560.572177.56930@r34g2000hsd.googlegroups.com> <13e971s8qujjm3a@corp.supernews.com> Message-ID: <1i471j8.dmtje2j20vraN%aleax@mac.com> bambam wrote: > > O(n) to find the element you wish to remove and move over > > everything after it, > > Is that how lists are stored in cPython? It seems unlikely? So-called "lists" in Python are stored contiguously in memory (more like "vectors" in some other languages), so e.g. L[n] is O(1) [independent from n] but removing an element is O(N) [as all following items need to be shifted 1 place down]. Alex From eduardo.padoan at gmail.com Fri Sep 14 20:43:38 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Fri, 14 Sep 2007 21:43:38 -0300 Subject: How to avoid overflow errors In-Reply-To: <13em8vnr527rq20@corp.supernews.com> References: <13em8vnr527rq20@corp.supernews.com> Message-ID: On 9/14/07, Steven D'Aprano wrote: > I thought that overflow errors would be a thing of the past now that > Python automatically converts ints to longs as needed. Unfortunately, > that is not the case. > > >>> class MyInt(int): > ... pass > ... > >>> MyInt(sys.maxint) > 2147483647 > >>> MyInt(sys.maxint+1) > Traceback (most recent call last): > File "", line 1, in > OverflowError: long int too large to convert to int Not totally unrelated, but in Py3k, as it seems, overflows are really things of the past: Python 3.0a1 (py3k:58061, Sep 9 2007, 13:18:37) [GCC 4.1.3 20070831 (prerelease) (Ubuntu 4.1.2-16ubuntu1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class MyInt(int): ... pass ... >>> import sys >>> MyInt(sys.maxint) 2147483647 >>> MyInt(sys.maxint+1) 2147483648 Thanks to your mail, only now I see how important this change (int/liong unification) really is! > How do I subclass int and/or long so that my class also auto-converts > only when needed? What about just subclassing long - is this not an option? > Steven. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From xah at xahlee.org Tue Sep 11 23:41:28 2007 From: xah at xahlee.org (Xah Lee) Date: Tue, 11 Sep 2007 20:41:28 -0700 Subject: need scsh in a wikip article In-Reply-To: <1189563310.268611.4550@r34g2000hsd.googlegroups.com> References: <1189563310.268611.4550@r34g2000hsd.googlegroups.com> Message-ID: <1189568488.932657.129510@o80g2000hse.googlegroups.com> On Sep 11, Xah Lee wrote: i was browsinghttp://en.wikipedia.org/wiki/Comparison_of_computer_shells quite fucking ridiculous that it contains Python shell and Ruby shell, and, there's no mentioning of scsh. Fuck the schemer morons. someone please add scsh there. ------------------ 2007-09-11, Addendum: It should be noted, that ?Python shell? and ?Ruby shell? should be removed from that page. Because, these are not command line interfaces to a OS. While, scsh, is designed, to be a shell in the traditional sense of being a command line interface to OS (unixes). Also note, from the perspective of sociology, that the fact Python and Ruby langs are added to that page, is a indication of the motherfucking computer language fanatism at play. If we were to condone or further this enthusiasm, i suggest Commond Lispers, and Emacs lispers, also added a CL Shell and Emacs Lisp shell to that page, since for all practical purposes, these langs provide the same interactive facilities as Python and Ruby. Also, Haskell enthus should add Haskell shell there too. Also note, such fanatical bias are exhibited in severe degrees in respective language's articles in wikipedia, in particular: the article on Python and Perl. (and undoubtly others too in various degrees but these 2 in particular i personally know well) To actually fix these articles to rid of bias, marketing, fanatism, is nigh impossible due to the nature of wikipedia and the army of respective lang's advocates. The inaccuracy and warring nature, is analogous to controversial articles on wikip, and perhaps it would fix itself over the years as wikipedia have matured in incredible ways in the mere few years in the past. However, the article on comparison of shell as cited in the above, could probably be fixed now without reaching a impasse or war, since the article contains multitudes of shells/langs (thus in not horded by one exclusive army faction), and the factual error of Python/Ruby there is relatively plain. Xah xah at xahlee.org ? http://xahlee.org/ From martin at v.loewis.de Sat Sep 1 02:25:25 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 Sep 2007 08:25:25 +0200 Subject: How to find out if the interpreter is a debug build? In-Reply-To: <1188609417.273513.74450@i13g2000prf.googlegroups.com> References: <1188609417.273513.74450@i13g2000prf.googlegroups.com> Message-ID: <46d905d5$0$26151$9b622d9e@news.freenet.de> llothar schrieb: > How can i find out if a selected python interpreter (i only know the > path name under which i should start it) is a debug build? I tried > > sys.api_version, sys.platform, sys.version, sys.version_info > > and there is no difference between "python.exe" and "python_d.exe". Sure there is: if sys.executable.endswith("_d.exe"): print "Debug version" If relying on the executable name is too unsafe, you can also look at imp.get_suffixes(), which includes "_d.pyd" in a debug build on Windows. If you want it cross-platform, you can check whether sys.getobjects is available. That, of course, is also unsafe because there isn't a single "debug build" on Unix, but instead, several debugging features can be enabled and disabled separately, so you would have to specify first what precisely a debug build is. Regards, Martin From kyosohma at gmail.com Wed Sep 12 09:10:07 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 12 Sep 2007 13:10:07 -0000 Subject: Is the wxPython list down? Message-ID: <1189602607.803546.180320@w3g2000hsg.googlegroups.com> Hi, Does anyone know if the wxPython mailing list is having issues? I subscribe to it and haven't seen anything come through since 09/06/2007. I went to ActiveState's archives and the last message there is from the 7th (http://aspn.activestate.com/ASPN/Mail/Browse/ Threaded/wxPython-users). Thanks, Mike From jcd at sdf.lonestar.org Wed Sep 12 11:20:01 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Wed, 12 Sep 2007 11:20:01 -0400 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189608231.151112.147550@y42g2000hsy.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> Message-ID: <20070912152001.GA20494@sdf.lonestar.org> On Wed, Sep 12, 2007 at 07:43:51AM -0700, Charles Fox wrote regarding Re: newbie: self.member syntax seems /really/ annoying: > > Thanks guys -- yeah these two stategies (short s.varname; and explicit > rescoping, a=self.a etc) are more or less what I was using. That's > still kind of annoying though. > > The s.varname approach still makes numerical code much harder to read. > For what it's worth, if you stick with python for a while, you will stop noticing the self, and be able to see what you're looking for quite clearly. Moreso if you use s. Cheers, Cliff From jwrweatherley at gmail.com Mon Sep 3 09:39:46 2007 From: jwrweatherley at gmail.com (jwrweatherley at gmail.com) Date: Mon, 03 Sep 2007 06:39:46 -0700 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <7x4picthpb.fsf@ruckus.brouhaha.com> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> <13dmctogeh19410@corp.supernews.com> <7x4picthpb.fsf@ruckus.brouhaha.com> Message-ID: <1188826786.674057.158020@d55g2000hsg.googlegroups.com> Thanks for all the answers to my question. I think what I need to take away from this is that xrange is an object - I thought it was just some loop construct, and that maths is slow in python - so avoid pathological looping.I remember the first time I tried Objective-C on OS X I used the NSNumber class for arithmetic - the results that time were pretty awful too! From KingShivan at gmail.com Fri Sep 7 21:51:34 2007 From: KingShivan at gmail.com (KingShivan at gmail.com) Date: Fri, 07 Sep 2007 18:51:34 -0700 Subject: subprocess.communicate messes things up Message-ID: <1189216294.958415.289400@r29g2000hsg.googlegroups.com> please could you take a look at this piece of code ? what I'd like is typically a sound boc : press one key, and get the associated sound. for this I place the sound files in different directories (easy to move and modify) and when a key is pressed I grab the first file of the corresponding directory. problem is that the first time I press a key, it works, but after it just print the keys I press, the annoying line being the one with communicate, any idea of what is happening ? thank you for reading import os,subprocess, tty, termios,sys,time FNULL = open('/dev/null', 'w') def getkey(): file = sys.stdin.fileno() mode = termios.tcgetattr(file) try: tty.setraw(file, termios.TCSANOW) ch = sys.stdin.read(1) finally: termios.tcsetattr(file, termios.TCSANOW, mode) return ch def main(): child1 = subprocess.Popen("/usr/bin/mplayer -slave -quiet - idle",stdin=subprocess.PIPE,stdout=FNULL,stderr=FNULL,shell=True) while 1: ch=getkey() name=os.listdir("/home/shivan/"+ch) file_to_load = "/home/shivan/"+ch+"/"+name[0] print "loadfile "+file_to_load output, errors = child1.communicate("loadfile "+file_to_load+" \n") main() From jstroud at mbi.ucla.edu Wed Sep 26 15:28:51 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 26 Sep 2007 12:28:51 -0700 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190829592.800804.242260@50g2000hsm.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190829592.800804.242260@50g2000hsm.googlegroups.com> Message-ID: Raymond Hettinger wrote: > As one who was submitted many PEPs, I can advise that the quickest way > to irrevocably kill an idea is to submit a PEP to early (we almost > didn't get genexps because the PEP was submitted pre-maturely). Maybe its the PEP killers who act prematurely because I friggin' love genexps and the little generators they generate. LC can be crude by comparison and is usually the construct that requires a compelling reason for usage. James From edgrsprj at ix.netcom.com Sat Sep 1 00:13:27 2007 From: edgrsprj at ix.netcom.com (E.D.G.) Date: Fri, 31 Aug 2007 22:13:27 -0600 Subject: Important Research Project References: <13ddcvm1bsu3s94@corp.supernews.com> Message-ID: <13dhm7uec5sp855@corp.supernews.com> "E.D.G." wrote in message news:13ddcvm1bsu3s94 at corp.supernews.com... > Important Research Project (Related to computer programming) > > Posted by E.D.G. on August 30, 2007 edgrsprj at ix.netcom.com This effort was not successful. And I am returning to trying to slowly make progress with the computer program I have been developing. I was hoping that there might be some people who had Perl chart and .exe generation programs running on their own computer who could say, "Here is how to merge them with Perl; here is how to use them; this is what they will do, etc." Or, I was hoping that someone would respond and say that although they are using Fortran or Basic etc. instead of Perl, they would be interested in getting a copy of Perl running, determine how to get those routines running, and then pass along the information. That would have saved some time. I work on these projects all the time. And it has been my experience that the world of science does not have the type of organized structure at this time to enable people to easily obtain that type of assistance. I have established an organization which will hopefully help with that problem. It might be going public at a Web site some time in the next year. There were some questions regarding the computer program I discussed. This is what it does: It provides researchers with the a certain amount of ability to determine if different events are somehow linked with one another. For example, it can be used to compare two or more earthquakes, earthquakes and electromagnetic pulses, tornados and electromagnetic pulses, and even earthquakes and tornados etc. It makes it possible for people to study events taking place deep in the Earth by evaluating electromagnetic pulse data associated with those events. Under the right conditions it can be used to forecast earthquakes. That is the reason it was developed in the first place. You can see the type of data it generates at the following Web page: http://www.freewebz.com/eq-forecasting/Data.html The plan is that when it has chart and standalone .exe program file generation capabilities, program copies will be circulated within the earthquake forecasting community in the People's Republic of China. It was discussed in detail there at a scientific conference in December of 2003. At that time it was too complex for widespread use. After the chart feature becomes operational etc. I am also planning to contact U.S. government officials to see if one or more lectures can be organized regarding the basic technology and theories, and the program's capabilities. These are personal opinions. From http Sat Sep 8 23:33:57 2007 From: http (Paul Rubin) Date: 08 Sep 2007 20:33:57 -0700 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> Message-ID: <7xhcm4pl5m.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > Except that the NSA's reputation has taken a dent since they failed to > anticipate the attacks on MD5 and SHA-1. NSA had nothing to do with MD5, and it's to NSA's credit that SHA-1 held up for as long as it did. From bj_666 at gmx.net Sat Sep 15 07:59:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Sep 2007 11:59:26 GMT Subject: int('\x23') != 0x23 (a.k.a convert char to integer of its byte representation) References: <1189857328.342615.105660@g4g2000hsf.googlegroups.com> Message-ID: <5l1vouF5umvcU1@mid.uni-berlin.de> On Sat, 15 Sep 2007 11:55:28 +0000, Boris Du?ek wrote: > I am looking for the best way to convert a string of length 1 (= 1 > character as string) to integer that has the same value as numeric > representation of that character. Background: I am writing functions > abstracting endianness, e.g. converting a string of length 4 to the > appropriate integer value (e.g. '\x01\x00\x00\x00' = 2**24 for big > endian memory, 2**0 for little endian memory). For this, I need to > know the numeric value of each byte and sum them according to > endianness. So you are looking for the `struct` module in the standard library instead of doing this yourself. :-) If you insist on doing it yourself take a look at the built-in `ord()` function. Ciao, Marc 'BlackJack' Rintsch From aafshar at gmail.com Tue Sep 4 10:30:37 2007 From: aafshar at gmail.com (Ali) Date: Tue, 04 Sep 2007 07:30:37 -0700 Subject: problem with TreeView + ListStore In-Reply-To: References: Message-ID: <1188916237.284124.323320@o80g2000hse.googlegroups.com> On Sep 4, 10:43 am, Guillermo Heizenreder wrote: > Hi list > I'm developing a application for learn pygkt, and I need to know when a > user selected or clicked one determinate row of my TreeView for shot > another signal . Hi, Well, ignoring the rest of the post, I can tell you that the usual way of doing this is to connect the changed signal of the treeview's selection. This explains it better than I would: http://faq.pygtk.org/index.py?req=show&file=faq13.011.htp Now to complete your actual use case: def on_selection_changed(selection, *args): model, paths = selection.get_selected_rows() if paths: hbox.show() treeView = gtk.TreeView() selection = self.treeView.get_selection() selection.connect('changed', on_selection_changed) There are some situations where you may want to actually connect the mouse click event, and we can discuss them further if you require. I should of course mention kiwi.ui.objectlist.ObjectList. It is an easier to use abstraction over TreeView, and has helped me in every situation where I would use a TreeView. Ali > Study the tutorial [1] I began to see the explanation that I see in the > chapter 14.7. TreeView Signal and found one in particular > "select-cursor-row", but I don't understood how implementing. > > Something like that. > if user_selected_row: > self.hbox_118.show() > print "YES" > > NOTE: self.hbox_118 = wTree.get_widget("hbox118") > > Thank and Regard > > [1]http://www.pygtk.org/pygtk2tutorial/sec-TreeViewSignals.html > > P/D: my English it to bad, I'm a novice. > -- > Heizenreder Guillermohttp://code.google.com/u/gheize/ From zentraders at gmail.com Sat Sep 8 17:47:20 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 08 Sep 2007 14:47:20 -0700 Subject: How to insert in a string @ a index In-Reply-To: <1189274564.462664.131240@22g2000hsm.googlegroups.com> References: <1189274564.462664.131240@22g2000hsm.googlegroups.com> Message-ID: <1189288040.775913.8090@g4g2000hsf.googlegroups.com> Same solution as above, but if you just want "Hello" and to not include words containing "Hello", i.e. "Helloing" or "Unhello", then you want to include a leading and/or trailing space. lit=" hello" ## note added space t1="nothello world hello. hello \nwhy world hello" start = t1.find(lit) t2 = t1[:start+1] + " XYZ" + t1[start+1:] print "t1 =", t1 print "t2 =", t2 start = t2.rfind(lit) t3 = t2[:start+1] + " XYZ" + t2[start+1:] print "t3 =", t3 From rrr at ronadam.com Sun Sep 23 19:34:20 2007 From: rrr at ronadam.com (Ron Adam) Date: Sun, 23 Sep 2007 18:34:20 -0500 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <13fdmdmsaasak91@corp.supernews.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <13f8unjjeqs5p97@corp.supernews.com> <13faa66cb1phre1@corp.supernews.com> <13fdmdmsaasak91@corp.supernews.com> Message-ID: <46F6F7FC.1050208@ronadam.com> Scott David Daniels wrote: > Ron Adam wrote: >> Scott David Daniels wrote: >>> Ron Adam wrote: >>>> .... How about this? >>>> def integrate(fn, x1, x2, n=100):... >>> The point was a pedagogic suggestion, ... >> I understood your point. I just found it interesting since I've been >> trying to extend my math (for use with python) skills in this area. > > Ah, sorry. I had realized I wasn't explicit in my first message. Yes, I wasn't trying to correct you. I'm sorry if it came across that way. > Yes, a perfectly fine integration. There's still something about it that bothers me. I think it may be the n=100 rather than delta='.0001', or some other way to specify the minimal error. (Yes, it's a bit off topic.) > You can then (and this is a major jump to get used to): > import functools > > Sine = functools.partial(integrate, math.cos, 0.0, n=100) I haven't played around with .partial yet. I wonder if it could be used in dispatching situations where the function signatures differ? > Similarly, you can define a derivative that will behave fairly well, > all without examining the definition of the function being operated > upon. I'll get around to doing that at some point. ;-) I also have a class that solves equations that takes a function in a similar way. It uses the same method used by HP calculators to solve TVM equations. Cheers, Ron From steve at REMOVE-THIS-cybersource.com.au Sat Sep 15 20:56:15 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 00:56:15 -0000 Subject: How to avoid overflow errors References: <13em8vnr527rq20@corp.supernews.com> <13emslk6n80mmf6@corp.supernews.com> Message-ID: <13eovpf7ongmrda@corp.supernews.com> On Sat, 15 Sep 2007 02:45:10 -0700, James Stroud wrote: > Steven D'Aprano wrote: >> On Fri, 14 Sep 2007 18:19:45 -0700, James Stroud wrote: >> >>>> How do I subclass int and/or long so that my class also auto-converts >>>> only when needed? >>>> >>> Use __new__. >> >> The disadvantage of that is that your example code requires me to >> duplicate my methods in the long version and the int version. It's easy >> enough to work around that (class factory function) but it just seems >> all rather untidy... > > > The __new__ method is where you implement such decisions. There is no > "tidier" way for one class "auto-convert" to another class, which is > what you asked for (it says so right up there ^). So, if you don't like > the answer, don't ask the question. How am I supposed to know if I will like the answer until I ask the question? If I knew the answer I wouldn't need to ask the question. Anyway, don't be so cranky and defensive. I was just pointing out that having to duplicate code between two different classes was untidy, not that __new__ is untidy. I thought that maybe I could inherit from both long and int, but Python doesn't like that: TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict > The way to avoid duplicating methods (which is what you are asking for, > no?) while still allowing your classes to maintain their identities is > by using mixins: [snip code] I've never come to grips with mixins. It's probably high time I do. Thanks for the example. -- Steven. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 12 03:50:13 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 12 Sep 2007 09:50:13 +0200 Subject: __getattr__ and static vs. instantiated In-Reply-To: <1189554607.559487.224410@b32g2000prf.googlegroups.com> References: <1189554607.559487.224410@b32g2000prf.googlegroups.com> Message-ID: <46e79a2f$0$28082$426a74cc@news.free.fr> tvaughan a ?crit : > Hi, > > Let's say I have: > > class Persistable(object): > > __attrs__ = {} > > def __getattr__(self, name): > if name in self.__attrs__: > return self.__attrs__[name]['value'] > else: > return Object.__getattr__(self, name) > > def __setattr__(self, name, value): > if name in self.__attrs__: > self.__attrs__[name]['value'] = value > else: > Object.__setattr__(self, name, value) > > And the I have: > > class Person(Persistable): > > __storm_table__ = 'person' > > id = Int(primary=True) > > __attrs__ = { > 'name': { > 'lang': 'en', > 'value': Unicode(), > }, > } > > def __init__(self): > self.id = int(random.random() * 1000) > > I can do this: > > person = Person() > person.name = 'Jane Smith' > > But I cannot do: > > Person.name = 'Jane Smith' yes, you can. But it won't do the same thing. > or use Person.name in a Storm query like: > > Person.name == 'Jane Smith' It will obviously raise an AttributeError if the class Person doesn't have a 'name' attribute. > __getattr__ is only called when using an instantiated class, A class's '__getattr__' method is only triggered when looking up attributes on an instance of the class, yes. > and > never, it seems, in a static case. Why? How do I work around this? Since classes are instances of their type, the obvious solution would be to define a custom metaclass implementing __getattr__. I didn't try, but it might work. Now is this the best thing to do is another question. You seems not to be aware of the descriptor protocol - which is used to implement methods and properties. This lets you define 'smart' attributes. You'll find relevant documentation here: http://docs.python.org/ref/descriptors.html and here: http://users.rcn.com/python/download/Descriptor.htm Also, you seem to be trying to roll your own ORM. There are already quite a few existing ones - SQLAlchemy being probably the best one already, and also a good base (no pun) for building your own solutions. HTH From gnn at neville-neil.com Sat Sep 22 14:06:38 2007 From: gnn at neville-neil.com (George V. Neville-Neil) Date: Sat, 22 Sep 2007 19:06:38 +0100 Subject: Properties and Objects... Message-ID: I have been reading the mailing list and I am unfortunately going to open up discussion I've seen twice in the last two years but which still bugs me, so please accept my apologies in advance. I have been working on a set of modules that make objects which look like network packets (http://pcs.sf.net) in that you can set up a class, say ipv4, which when instantiated has the following properties: >>> from pcs.packets.ipv4 import * >>> ip = ipv4() >>> ip.bytes '@\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>> ip.ttl 64 >>> ip.ttl=32 >>> ip.bytes '@\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>> Note that setting the ttl in the packet changes the underlying bytes. Doing this makes writing network tests, and other networking code, extremely easy. This is done by having Field classes which are collected into a list in a Packet class (the layout) and by doing special setattr/getattr calls. I have been trying to switch this over to using properties, which seem at first glance to be cleaner, but which I am having a lot of problems with. In particular I want to add a property to an object, not a class. The field list in a class is actually relatively static but I wind up with ugly code like: class ethernet(pcs.Packet): """Ethernet""" __layout__ = pcs.Layout() _map = ethernet_map.map src = pcs.StringField("src", 48) dst = pcs.StringField("dst", 48) type = pcs.Field("type", 16) def __init__(self, bytes = None, timestamp = None): """initialize an ethernet packet""" src = pcs.StringField("src", 48) dst = pcs.StringField("dst", 48) type = pcs.Field("type", 16) pcs.Packet.__init__(self, [dst, src, type], bytes = bytes) self.description = inspect.getdoc(self) and assigning the properties at class time means that it's hard to have variations, packets with the same name but with slightly varying field lists. So, is there a way to assign a property to an object, like this: def __init__(.... self.src = property() or something like that? And, failing that, is there a clean way to modify the class in it's __init__() method so I don't have to call the Field objects twice, once for the property effect and once to put into the list in the base Packet class? With my somewhat convoluted setattr/getattr implementation the Ethernet class looked like this: class ethernet(pcs.Packet): """Ethernet""" __layout__ = pcs.Layout() _map = ethernet_map.map def __init__(self, bytes = None, timestamp = None): """initialize an ethernet packet""" src = pcs.StringField("src", 48) dst = pcs.StringField("dst", 48) type = pcs.Field("type", 16) pcs.Packet.__init__(self, [dst, src, type], bytes = bytes) self.description = inspect.getdoc(self) which was much more straightforward for someone to understand and to code. Since one of the project goals is to have the creation of new packets classes be as easy as possible I would like to be able to do something closer to the above. Best, George From paul at boddie.org.uk Wed Sep 26 06:28:46 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 26 Sep 2007 03:28:46 -0700 Subject: setuptools without unexpected downloads In-Reply-To: <5lumarFae888U1@mid.uni-berlin.de> References: <87ejgmklep.fsf@benfinney.id.au><878x6ukkvq.fsf@benfinney.id.au> <5luhb0Faal8aU1@mid.uni-berlin.de> <874phhlupi.fsf@benfinney.id.au> <5lumarFae888U1@mid.uni-berlin.de> Message-ID: <1190802526.695391.326220@n39g2000hsh.googlegroups.com> On 26 Sep, 11:16, "Diez B. Roggisch" wrote: > > Generally speaking, I think the real problem here is the clash > between "cultures" of dependency-handling. But it's certainly beyond > setuptools scope to cope with every imaginable package management system > out there, and provide means to trigger an installation of say e.g. debian > packages that are needed. If you look at PEP 345... http://www.python.org/dev/peps/pep-0345/ ...you'll see that the dependency information described is quite close to how such information is represented in Debian packages and with other dependency management systems. This isn't an accident because the authors were surely already familiar with such representations, which have been around for quite some time. Admittedly, it isn't easy to make a system which observes the rules of all the different existing systems; for example, can .deb metadata and .rpm metadata be interpreted in the same way and be taken to mean the same thing? However, the argument that a dependency manager cannot deal with different system packages is a weak one: apt and Smart have shown that dependency management can be decoupled from package management. Of course, I've already pointed out that despite being written in Python, there's apparently no interest in the setuptools community to look at what Smart manages to do, mostly due to spurious licensing "concerns", and there's always the "argument zero" from people who choose to ignore existing dependency management solutions: that Windows doesn't provide such solutions - which is apparently not entirely true, either. [...] > For example - what if there is no debian package that provides module XY in > the required version? Do you rather install it into the global > site-packages, or do you rather keep it private to the program requiring > it? I'd say the latter is better in mostly all circumstances, as it will > not disrupt the workings of other programs/modules. For what it's worth, it is possible to use Debian dependency/package management as a non-root user with a local site-packages directory, but it isn't particularly elegant. See this proof of concept for details: http://www.boddie.org.uk/paul/userinstall.html It's a fairly heavy solution which installs a lot of the administrative toolchain just for local package installations, but you do get dependency integration with the packages providing the libraries that may be required by various Python extension modules. Paul From skulka3 at gmail.com Thu Sep 27 12:45:24 2007 From: skulka3 at gmail.com (skulka3 at gmail.com) Date: Thu, 27 Sep 2007 16:45:24 -0000 Subject: True of False In-Reply-To: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> Message-ID: <1190911524.400966.101550@n39g2000hsh.googlegroups.com> On Sep 27, 11:33 am, kou... at hotmail.com wrote: > I tried writing a true and false If statement and didn't get > anything? I read some previous posts, but I must be missing > something. I just tried something easy: > > a = ["a", "b", "c", "d", "e", "f"] > > if "c" in a == True: > Print "Yes" > > When I run this, it runs, but nothing prints. What am I doing wrong? > Thanks. > > Kou , You may want to include paren around ("c" in a) and a lower case p for Print, i.e. print, and it should work so eg: a = ["a", "b", "c", "d", "e", "f"] if ("c" in a) == True: print "Yes" From steve at holdenweb.com Thu Sep 27 16:00:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 16:00:33 -0400 Subject: ValueError: too many values to unpack,>>> In-Reply-To: <46FC0244.4010803@comcast.net> References: <5m24sfFatlbuU1@mid.uni-berlin.de> <46FBED79.6070207@comcast.net> <46FC0244.4010803@comcast.net> Message-ID: Shawn Minisall wrote: > Fredrik Lundh wrote: >> Shawn Minisall wrote: >> >> >>> Sorry, it looks like it's on the fourth line with the 3 values on line >>> 4...its reading line 3 fine >>> >>> Traceback (most recent call last): >>> File "", line 1, in >>> main() >>> File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line 33, >>> in main >>> deposit1, deposit2, deposit3 = string.split(line, "\t") >>> ValueError: too many values to unpack >>> >> instead of fumbling around in the dark, try inserting a print statement >> before the offending line, so you can see what you're trying to unpack: >> >> print string.split(line, "\t") # see what it is >> deposit1, deposit2, deposit3 = string.split(line, "\t") >> >> >> > I did and it printed everything up until the 3rd line with 3 numbers for > deposits. I have since figured it out...the teacher put in an extra tab > after the last value so python thought it was 4 values for three. I > went back into the file and deleted the extra tab after the 3rd number > and saved it...now it's working fine. > > I'm going to kill her... > > ;) > Alternatively you could use the additional argument to split() that tells is the maximum number of splits to [erforms, then strip any trailing whitespace off before using the values. That way tou might get an extra mark for not amending the data file. It's called "defensive programming", and you need t take it seriously (as does everyone who programs). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From Shawn at Milochik.com Fri Sep 7 14:53:12 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Fri, 7 Sep 2007 14:53:12 -0400 Subject: why should I learn python In-Reply-To: References: Message-ID: <2dc0c81b0709071153j619c5e94kbabedd5d90416e7c@mail.gmail.com> I wholeheartedly second the recommendation of this article: http://www.linuxjournal.com/article/3882 From steve at holdenweb.com Sun Sep 16 12:07:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Sep 2007 12:07:08 -0400 Subject: (curses) issue about inch() In-Reply-To: <1189955232.216664.167840@19g2000hsx.googlegroups.com> References: <1189955232.216664.167840@19g2000hsx.googlegroups.com> Message-ID: Jimmy wrote: > hi, all > I attempt to use the function inch() to get the character at the > current position, and compare it with a particular character like : > if screen.inch(x,y) == 'F' > but this method doesn't seem work, can anyone tell me the reason and > how to corrent it > thanks > The reason is because something is wrong, and yo fix it by correcting that issue. In other words, if you could be a bit more specific about *how* it doesn't work (like, show us the code you are running,a nd any error messages or evidence of incorrect results) you will be able to get some help that actually helps you. Would you go to a car repair shop with faulty brakes and just tell them "my car isn't working"? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From mridula.ccpl at gmail.com Tue Sep 18 03:23:35 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Tue, 18 Sep 2007 12:53:35 +0530 Subject: adodb with mysql - connection string syntax for filepath In-Reply-To: <33dffc910709162342x49657895t938fb1f8af2834de@mail.gmail.com> References: <33dffc910709162342x49657895t938fb1f8af2834de@mail.gmail.com> Message-ID: <33dffc910709180023w42471f33n5bd76f8b02f40930@mail.gmail.com> Hi. Firstly, thank you both very much for the response! Cliff, I did some more reading up about it after you corrected me re MySQL not being a _language_ but another means of storing data (would you believe NONE of the connection tutorials actually said that?!) Anyway, now I have MySQL on my machine, and it's installed - if I say "import MySQLdb" in python prompt, it does that, but I can't see any exe in the program's folder itself: does that mean tables can only be created by code? *puzzled* Steve, thank you too, I looked up the link you had given, but I do not yet know which part of that site may help me... And I am now going to struggle with Dive Into Python before attempting much else! This is a nice, helpful mailing group! Thanks again. On 17/09/2007, Mridula Ramesh wrote: > > Dear all, > > Hi. I am not very tech-savvy so please pardon me if this is a stupid > question: so far I have been googling for about 4 days to find help for > this, so now I am desperate! :) > > How do you use adodb with mysql to connect to a file that is on your > machine? > > Also, could you please recommend to me a good resource to learn more about > classes and modules from? i don't understand half of the _init_ business > that many sites mention. (This *is* something even a newbie needs to learn, > right?) > > Thank you! > > M.R.S. > -- CONSUL CONSOLIDATED PVT LTD. 9/6 1st street Venkateshwara Nagar Adyar Madras 600 020 Ph : 91 - 44 - 24468117 Fax : 91 - 44 - 24468082. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tuomas.vesterinen at pp.inet.fi Fri Sep 7 04:49:29 2007 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Fri, 07 Sep 2007 08:49:29 GMT Subject: interesting puzzle......try this you will be rewarded... In-Reply-To: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> Message-ID: To save your time: http://ilikeit.desiblogz.com/363/ojofuffo,+ojofuffo,+ojofuffo+-+Solutions+to+the+Hacking+puzzle++by+freestuffhotdeals.com.html Renu wrote: > Hi, > > Just click on this link n use ur common sence to navigate. > > It has 23 pages one after the other, starting from this first > > Page. > The trick is to find a way to go to the next page. > > If u can really go to the 23rd page ur a genius in ur own respect :) > > So best of luck n keep clicking, tik tik.... > > http://iamhere.50webs.com > From steve at holdenweb.com Tue Sep 25 11:55:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 25 Sep 2007 11:55:30 -0400 Subject: What is a good way of having several versions of a python module installed in parallell? In-Reply-To: <5ls95aF9pq3gU1@mid.uni-berlin.de> References: <5ls95aF9pq3gU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Joel Hedlund wrote: > >> Hi! >> >> I write, use and reuse a lot of small python programs for variuos purposes >> in my work. These use a growing number of utility modules that I'm >> continuously developing and adding to as new functionality is needed. >> Sometimes I discover earlier design mistakes in these modules, and rather >> than keeping old garbage I often rewrite the parts that are >> unsatisfactory. This often breaks backwards compatibility, and since I >> don't feel like updating all the code that relies on the old (functional >> but flawed) modules, I'm left with a hack library that depends on halting >> versions of my utility modules. The way I do it now is that I update the >> programs as needed when I need them, but this approach makes me feel a bit >> queasy. It seems to me like I'm thinking about this in the wrong way. >> >> Does anyone else recognize this situation in general? How do you handle >> it? >> >> I have a feeling it should be possible to have multiple versions of the >> modules installed simultaneously, and maybe do something like this: >> >> mymodule/ >> + mymodule-1.1.3/ >> + mymodule-1.1.0/ >> + mymodule-0.9.5/ >> - __init__.py >> >> and having some kind of magic in __init__.py that let's the programmer >> choose version after import: >> >> import mymodule >> mymodule.require_version("1.1.3") >> >> Is this a good way of thinking about it? What would be an efficient way of >> implementing it? > > Use setuptools. It can exactly do that - install different versions parallel > as eggs, and with a pre-import require-statment you require the desired > one. > > Diez Of course a much simpler, less formal solution, is to install the libraries required by a program along with that program in its own directory. This more or less guarantees you will get out of sync. Otherwise, three words: test driven development regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From tdelaney at avaya.com Tue Sep 25 00:46:54 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 25 Sep 2007 12:46:54 +0800 Subject: sorting a list numbers stored as strings In-Reply-To: <1190635761.5618.2.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > On Mon, 2007-09-24 at 19:58 +0800, Delaney, Timothy (Tim) wrote: >> I'm sure that in some version of Python it would have given a >> ValueError (due to the default radix being 0) but it appears to have >> changed to a default radix of 10 somewhere along the way. > > Not even Python 1.5.2 seems to have a problem with leading zeroes: > > Python 1.5.2 (#1, Nov 6 1999, 14:53:40) [C] on sco_sv3 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>>> int("08") > 8 Yep - appears I must have been misremembering from another language (dunno which) or I misinterpreted the docs. In any case, the docs have been made explicit about the situation now. Tim Delaney From cai.haibin at gmail.com Fri Sep 14 02:56:17 2007 From: cai.haibin at gmail.com (james_027) Date: Fri, 14 Sep 2007 06:56:17 -0000 Subject: mass editing for keys in a dictionary Message-ID: <1189752977.078417.291770@57g2000hsv.googlegroups.com> hi, How could I transform something like this dict_1 = {'customer_id':1, 'item_id':3, amount:100} into dict_2 = {'customer':1, 'item':3, amount:100} thanks james From chris.olekas at gmail.com Mon Sep 10 10:27:46 2007 From: chris.olekas at gmail.com (Chris) Date: Mon, 10 Sep 2007 07:27:46 -0700 Subject: How do I read and write to the same CSV file Message-ID: <1189434466.001109.313060@d55g2000hsg.googlegroups.com> I want to update one field in a row for a csv file. So far my code looks something like this cf_stream = open("\\config.csv","r+") csv_file = csv.DictReader(cf_stream, ['Algorithm','LastModified']) and then I know I can do something like this for row in csv_file name = row["Algorithm"] date = row["LastModified"] now what I want is something like this if date == 0: date = os.getmtime() # now this is where I want to write into the row of the same csv file but only updating that one field How can I do this? From eternalsquire at comcast.net Sun Sep 2 14:16:31 2007 From: eternalsquire at comcast.net (The Eternal Squire) Date: Sun, 02 Sep 2007 11:16:31 -0700 Subject: Would like to perform unpaid research work at a CS graduate school or center Message-ID: <1188756991.988083.34770@k79g2000hse.googlegroups.com> To all, About twenty years ago, I was admitted to a Ph.D. program for computer science. It was also around that time that I was diagnosed for chronic depression, which forced me out of that program into the working word. I had done my best since then as a software engineer, until late 2005, when I was laid off by my most recent workplace. I have now been out of work for 2 years, with no hope of finding anything further. I have been on medication for my depression since 1998, which moderates it somewhat. Until that time the disease has played havoc with my interpersonal and employment relationships, I had always done my best to compensate by immersing myself in the actual work. Most ironically, I am now as strong as I ever was for being a researcher, even more so for my practical experience, and so long as I avoid a punishing work and study load I believe I could do better on a second attempt for a doctorate than I ever did on my first. The problem is obtaining research related references. I would like to find a graduate CS department or university research center that would allow me to perform unpaid research work on a remote basis. I have some interests in parallel computing, from an architecture, programming language, and applications point of view. I will also consider other topics. I hold a bachelor's degree in electrical engineering and a master's degree in computer science, with about 12 to 15 years of practical software experience in systems programming and embedded programming. I also hold an Amateur Extra ticket and have my own electronics laboratory. Please, this is a sincere request. Interested parties please send email to eternalsquire at hotmail.com I hold a bachelor's degree in electrical engineering and a master's degree in computer science, with about 12 to 15 years of practical software experience in systems programming and embedded programming. I also hold an Amateur Extra ticket and have my own electronics laboratory. Please, this is a sincere request. Interested parties please send email to eternalsquire at hotmail.com I hold a bachelor's degree in electrical engineering and a master's degree in computer science, with about 12 to 15 years of practical software experience in systems programming and embedded programming. I also hold an Amateur Extra ticket and have my own electronics laboratory. Please, this is a sincere request. Interested parties please send email to eternalsquire at hotmail.com From wizzardx at gmail.com Thu Sep 20 17:04:28 2007 From: wizzardx at gmail.com (David) Date: Thu, 20 Sep 2007 23:04:28 +0200 Subject: cannot create my own dict In-Reply-To: References: <46f17c26$0$26298$426a74cc@news.free.fr> Message-ID: <18c1e6480709201404o3ba69cdfrc8ccef5172cc836e@mail.gmail.com> > The reason for this problem is that we are busy re-structuring a large Python > program, and we want to ensure nobody is messing up our data structures (at > least not until we are finished). python-egenix-mxproxy (Debian package name) may be useful. http://www.egenix.com/products/python/mxBase/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Sep 12 07:43:38 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 12 Sep 2007 13:43:38 +0200 Subject: Compiler Python References: <000001c7f4a2$307fa720$917ef560$@com> <5kod78F3udmuU1@mid.individual.net> <46e7045d$0$3290$426a74cc@news.free.fr> Message-ID: <5kq1naF4r90oU2@mid.individual.net> Bruno Desthuilliers wrote: > Bjoern Schliessmann a ?crit : >> I'm not really about the syntax of your question, ^(sure) > > lol !-) ;) It wasn't mean ironically, I really forgot the "sure". Regards, Bj?rn -- BOFH excuse #322: Your Pentium has a heating problem - try cooling it with ice cold water.(Do not turn of your computer, you do not want to cool down the Pentium Chip while he isn't working, do you?) From ldo at geek-central.gen.new_zealand Sat Sep 1 03:49:17 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 19:49:17 +1200 Subject: advice about `correct' use of decorator References: Message-ID: In message , Gerardo Herzig wrote: > @is_logued_in > def change_pass(): > bla > bla > > And so on for all the other functions who needs that the user is still > loged in. My suspicion is that most of the methods in your session object (with the obvious exception of the login method) will require the user to be logged in, right? So the trouble with an extra decorator like this, is that you have to remember to put it on nearly _all_ your methods. Wouldn't it be simpler and safer to default the other way? Have some way of saying "doesn't require user to be logged in", and require a valid logged-in session on all methods where this is not specified? From DustanGroups at gmail.com Mon Sep 24 06:09:48 2007 From: DustanGroups at gmail.com (Dustan) Date: Mon, 24 Sep 2007 10:09:48 -0000 Subject: scope, modyfing outside object from inside the method In-Reply-To: References: Message-ID: <1190628588.220275.119360@50g2000hsm.googlegroups.com> On Sep 24, 2:13 am, Peter Otten <__pete... at web.de> wrote: > @property > def value(self): > return self._resultset[self._row][self._col] I remember a thread where someone created a version of property that worked like this, but it's not in the standard python release, unless it is in python 3000. From martin at v.loewis.de Tue Sep 4 00:34:26 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 04 Sep 2007 06:34:26 +0200 Subject: FCGI app reloading on every request In-Reply-To: <46DCDE59.8060109@animats.com> References: <46DCDE59.8060109@animats.com> Message-ID: <46DCE052.40708@v.loewis.de> John Nagle schrieb: > I'm converting a web app from CGI to FCGI. The application works fine > under FCGI, but it's being reloaded for every request, which makes FCGI > kind of pointless. I wrote a little FCGI app which prints when the > program is loaded and when it gets a request. And indeed, the program > gets reloaded for > each HTTP request. Something is probably misconfigured. But what? The most likely reason is that your FastCGI server voluntarily choses to exit after one request. Can you share the mainloop of your application? Regards, Martin From michele.simionato at gmail.com Sun Sep 2 13:49:46 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sun, 02 Sep 2007 17:49:46 -0000 Subject: Google spreadsheets In-Reply-To: <1i3t5mo.lopt711vavlbwN%aleax@mac.com> References: <1188564051.726895.288860@y42g2000hsy.googlegroups.com> <1188578994.210244.70800@i13g2000prf.googlegroups.com> <1i3t5mo.lopt711vavlbwN%aleax@mac.com> Message-ID: <1188755386.841482.27590@19g2000hsx.googlegroups.com> On Sep 2, 7:13 pm, al... at mac.com (Alex Martelli) wrote: > iapain wrote: > > On Aug 31, 5:40 pm, Michele Simionato > > wrote: > > > I would like to upload a tab-separated file to a Google spreadsheet > > > from Python. Does anybody > > > have a recipe handy? TIA, > > > > Michele Simionato > > > Probably its irrelevant to python. Use should see Google Spreadsheet > > API and use it in your python application. > > >http://code.google.com/apis/spreadsheets/ > > For Python-specific use, you probably want to get the Python version of > the GData client libraries, > ; an example of using it > with a spreadsheet is at > s/spreadsheetExample.py> . > > Alex Thanks Alex, that's exactly what I was looking for. Michele From dnhkng at googlemail.com Tue Sep 11 13:18:16 2007 From: dnhkng at googlemail.com (Dr Mephesto) Date: Tue, 11 Sep 2007 17:18:16 -0000 Subject: creating really big lists In-Reply-To: <46e5b1b4$0$30530$426a74cc@news.free.fr> References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> <46e5b1b4$0$30530$426a74cc@news.free.fr> Message-ID: <1189531096.198401.76590@50g2000hsm.googlegroups.com> On Sep 8, 8:06 pm, Bruno Desthuilliers wrote: > Dr Mephesto a ?crit : > > > Hi! > > > I would like to create a pretty big list of lists; a list 3,000,000 > > long, each entry containing 5 empty lists. My application will append > > data each of the 5 sublists, so they will be of varying lengths (so no > > arrays!). > > > Does anyone know the most efficient way to do this? > > Hem... Did you consider the fact that RAM is not an unlimited resource? > > Let's do some simple math (please someone correct me if I'm going off > the road): if a Python (empty) list object required 256 bits (if I refer > to some old post by GvR, it's probably more - 384 bytes at least. Some > Python guru around ?), you'd need (1 + (3000000 * 5)) * 256 bits just to > build this list of lists. Which would make something around 3 Gb. Not > counting all other needed memory... > > FWIW, run the following code: > > # eatallramthenswap.py > d = {} > for i in xrange(3000000): > d[i] = ([], [], [], [], []) > > And monitor what happens with top... Unused ram is wasted ram :) I tried using MySQL, and it was to slow. and I have 4gb anyway... From bdesth.quelquechose at free.quelquepart.fr Fri Sep 21 20:21:29 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 22 Sep 2007 02:21:29 +0200 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190419720.811685.145880@r29g2000hsg.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <1190419720.811685.145880@r29g2000hsg.googlegroups.com> Message-ID: <46f6eb3d$0$32060$426a34cc@news.free.fr> Cristian a ?crit : > On Sep 21, 4:47 pm, "Sean Tierney" wrote: > >>Just tell him that "functions are like all other variables and can >>therefore be passed by other functions or returned by other functions. >>" >> > > > > > I could """Just tell him that "functions are like all other variables > and can > therefore be passed by other functions or returned by other functions. > " """ but wouldn't it be great if Python did this for me? It seems to > me that the ability for Python to explicitly state that functions-are- > like-other-variables is there so why not expose it? Ok, then what about classes ? They also are objects-like-any-other, after all. So should we have this syntax too ? MyClass = class(ParentClass): __init__ = function (self, name): self.name = name ?-) From steve at holdenweb.com Sat Sep 1 08:38:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Sep 2007 08:38:12 -0400 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> Message-ID: <46D95D34.9010906@holdenweb.com> Bryan Olson wrote: > Steve Holden wrote: > [...] >> If I can blow my own trumpet briefly, two customers (each using over 25 >> kLOC I have delivered over the years) ran for two years while I was away >> in the UK without having to make a single support call. One of the >> systems was actually locked in a cupboard all that time (though I have >> since advised that client to at least apply OS patches to bring it up to >> date). > >> This was achieved by defensive programming, understanding the user >> requirements and just generally knowing what I was doing. > > On the one hand, nice work. Made your customers happy and kept > them happy. Can't argue with success. On the other hand, 25K lines > is tiny by software engineering standards. If a support call would > have to go to you, then the project must be small. Software > engineering is only a little about an engineer knowing or not > knowing what he or she is doing; the bigger problem is that > hundreds or thousand of engineers cannot possibly all know what > all the others are doing. > I agree that programming-in-the-large brings with it problems that aren't experienced in smaller scale projects such as the ones I mentioned. > I work on large and complex systems. If I screw up -- O.K., face > facts: *when* I screw up -- the chance of the issue being assigned > to me is small. Other engineers will own the problems I cause, > while I work on defects in code I've never touched. I wish I could > own all my own bugs, but that's not how large and complex systems > work. Root-cause analysis is the hard part. By the time we know > what went wrong, 99.99% of the work is done. > This is the kind of realism I like to see in engineering. I am always suspicious when any method is promoted as capable of reducing the error rate to zero. > > Design-by-contract (or programming-by-contract) shines in large > and complex projects, though it is not a radical new idea in > software engineering. We pretty much generally agree that we want > strong interfaces to encapsulate implementation complexity. > That's what design-by-contract is really about. > > There is no strong case for adding new features to Python > specifically for design-by-contract. The language is flexible > enough to support optionally-executed pre-condition and > post-condition checks, without any extension. The good and bad > features of Python for realizing reliable abstraction are set > and unlikely to change. Python's consistency and flexibility > are laudable, while duck-typing is a convenience that will > always make it less reliable than more type-strict languages. > Python's dynamic nature certainly makes it more difficult to reason about programs in any formal sense. I've always thought of it as a pragmatist's language, and we need to be pragmatic about the downside as well as the upside. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From http Sat Sep 8 01:57:41 2007 From: http (Paul Rubin) Date: 07 Sep 2007 22:57:41 -0700 Subject: pdb question - spew out "steps" until crash needed References: Message-ID: <7xbqcd4s2y.fsf@ruckus.brouhaha.com> James Stroud writes: > How do I get pdb to just run my program and spew out what's happening > until it crashes/freezes? (This is a malloc error in a library > somewhere and I can't figure out where--no exceptions thrown, etc.) Maybe you want: http://docs.python.org/lib/module-trace.html However, the malloc problem has probably already screwed things up long before the application actually freezes. Your best bet is to recompile Python with malloc debugging enabled and/or run Python itself under a debugger. From grante at visi.com Mon Sep 10 17:01:09 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 10 Sep 2007 21:01:09 -0000 Subject: How do I disable warnings? References: <13eb71tjns922f9@corp.supernews.com> <1189457423.063659.127690@57g2000hsv.googlegroups.com> Message-ID: <13ebc4lci7ov217@corp.supernews.com> On 2007-09-10, attn.steven.kuo at gmail.com wrote: >> I'd like to disable this warning: >> >> Warning: 'with' will become a reserved keyword in Python 2.6 >> >> AFAICT, the following should work. But, it doesn't. >> >> import warnings >> warnings.filterwarnings('ignore',".*'with' will become a reserved keyword.*") >> >> What am I doing wrong? > > That looks to be a compile-time warning. Doh! Of course it's a compile-time warning. > Refer to a previous discussion here: > > http://groups.google.com/group/comp.lang.python/msg/9f604b477ad31ef3 Thanks. -- Grant Edwards grante Yow! The Osmonds! You are at all Osmonds!! Throwing up visi.com on a freeway at dawn!!! From david at nospam.spam Tue Sep 11 06:58:24 2007 From: david at nospam.spam (david) Date: Tue, 11 Sep 2007 20:58:24 +1000 Subject: /dev/null as a file-like object, or logging to nothing In-Reply-To: References: <87k5r1jdzq.fsf@wilson.homeunix.com> <5kg48jF33dv5U3@mid.uni-berlin.de> <87fy1pjbpl.fsf@wilson.homeunix.com> Message-ID: <13ect6ffo9h2ufa@corp.supernews.com> Lawrence D'Oliveiro wrote: > In message , Sion Arrowsmith wrote: > >> Torsten Bronger wrote: >>> Marc 'BlackJack' Rintsch writes: >>>> `os.devnull`? >>> Yes, but I wasn't really sure how portable it is, in particular, on >>> Windows. >> Windows has a NUL: device which behaves like /dev/null . > > It's not a device, it's a reserved file name. Or rather, a reserved file > name prefix: any attempt to open a file name beginning with NUL, e.g. > NUL.DAT, will cause your output to disappear into a black hole. > > This has bitten Windows users more than once. copy myfile to NULL copy myfile to NULfilename copy myfile to NULprefix.txt All work correctly creating files. "Prefix" and "beginning with" are a bit misleading, only a problem with file name NUL(.extension) (not case sensitive unless case sensitive property is enabled) Not sure why you are calling it a reserved file name instead of device, did not used to be, but many years since I looked. Of course 'reserved file name' is a bit misleading: you wouldn't copy bits to a reserved file name. Note NUL device used to be very very slow, again, years since I looked. From brown at esteem.com Thu Sep 13 18:24:20 2007 From: brown at esteem.com (Tom Brown) Date: Thu, 13 Sep 2007 15:24:20 -0700 Subject: How to Start In-Reply-To: References: Message-ID: <200709131524.20845.brown@esteem.com> On Thursday 13 September 2007 14:59, Michael R. Copeland wrote: > I've decided that Python is a language/environment I'd like to learn > (I've been a professional programmer for 45+ years), but I really don't > know where and how to start! I have a number of books - and am buying > some more - but because of the bewildering number of after-market > packages, environments, and add-ons, I am really quite perplexed about > starting. 8<{{ > Yes, I could fire up the interactive mode and play with some > statements...but I consider that sort of thing for programming neophytes > or experimenting with specific issues. First, I want to develop a > simple Windows application, and because of the plethora of "stuff" the > Python world offers, I don't know where to begin. > For example, what basic, easy-to-use interface might I start with to > build a simple text file parsing and analysis program? That is, I'd > like to start with a simple Windows shell that prompts for a file name, > processes it, and then displays some result. > I am certainly impressed with the apparent experience and openness of > the regular players here, but the discussions here (and in > c.l.p.announce) truly presume knowledge and experience with Python I > don't yet have. Yes, for even a very experienced programmer, entering > the Python world is very daunting - but I want to get started. > Please advise. TIA A good book, a link to the module index, a good text editor and a command prompt will get you started. Sounds like you have some books. Those should help a lot. A good text editor is a matter of taste. I prefer gvim. However, gvim has a steep learning curve to become productive. There is eric4, which is an IDE. I has a debugger. That may be the place to start. Good luck, Tom From stefan.arentz at gmail.com Thu Sep 6 05:26:05 2007 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 06 Sep 2007 11:26:05 +0200 Subject: How to do python and RESTful References: <1189022079.403495.175800@g4g2000hsf.googlegroups.com> <1189070287.239501.70270@k79g2000hse.googlegroups.com> Message-ID: <873axs16xe.fsf@kip.sateh.com> Michele Simionato writes: > On Sep 5, 9:54 pm, MarkyMarc wrote: > > Hi all, > > > > I want to make a web service application in python and keywords are > > RESTful, python and nice urls(urls mapped to python objects). > > > > I don't want a big framework but a nice small one, that can just do > > the things I want. > > > > I have be looking at quixote, but is this uptodate? "plain" > > mod_python, can this make url to http put,get,delete and post? > > > > Can some one here point me some where I can read about python and > > RESTful or have some experiences with other? > > > > Any help is apricieted. > > > > Regards Marc > > For the client part, there is an easy_installable library called > restclient (which > I tested very little but it seems to work). For the server part, I am > sure there are > many available, Another good option is Twisted. The Twisted book from O'Reilly has examples of using the twisted HTTP client as a REST client. I'm using that fairly succesful. S. From basilisk96 at gmail.com Thu Sep 6 22:09:52 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Fri, 07 Sep 2007 02:09:52 -0000 Subject: interesting puzzle......try this you will be rewarded... In-Reply-To: <1189130241.529344.52950@57g2000hsv.googlegroups.com> References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> <46e04138$0$16377$88260bb3@free.teranews.com> <1189130241.529344.52950@57g2000hsv.googlegroups.com> Message-ID: <1189130992.654172.295660@50g2000hsm.googlegroups.com> Woody! :)) From kasimmominov at gmail.com Sun Sep 23 19:13:54 2007 From: kasimmominov at gmail.com (kasim) Date: Sun, 23 Sep 2007 23:13:54 -0000 Subject: http://www.agloco.com/r/BBFR2592 Message-ID: <1190589234.941754.273680@22g2000hsm.googlegroups.com> http://kgsm.websitesiekle.com/ Thanks 1. Hi everyone, For all of you that are asking for caculations for how much pay, just consider this. There is truly no way anyone can calculate with all variables. The pay is dependent upon the advertisers paying agloco, the search engines paying agloco, the merchants paying agloco the commissions on the sales to agloco members, and any other sources of income. This money all goes into a pool, of which agloco management gets 10% and the rest is divided among the owners/members. There you have it. income is variable, percentages for management and the owners ia fixed. membership is variable. These variable parts will change by the minute. No reasonable mathmatician will attempt to arrive at meaningful calculations with two massive variables and one fixed quantity. All the mathmatician can do at this point is offer statistical possibilities. In the short view, every person you sponsor now cuts down on the value of the cash pool individually. In the longer term, more members means agloco can charge more for the ads and make the cash pool larger. As far as clicking the ads, That will create cash pool money when the few make purchases and the merchant pays agloco the commission on the sale. In at least some cases, the member will immediately benefit from any discounts that are given to the agloco membership. Regards searches, I do not know what deal agloco has with google or the other search engines at this time, but I do know that as the membership goes up, so does the price google and the others will pay agloco for each search performed. Google currently pays aol 10 cents per search performed. Best I can tell you is the per hour pay will fall into a range somewhere between .00001 cents and 1,000.00 dollars per hour.( both top and bottom values estimated with the fact that everyone is so desparate for promises that poor Brian cannot say anything without it being considered a set in concrete promise.) I intentionally used extremes. Try to keep your shirt on and wait and see what materializes. From kwmsmith at gmail.com Mon Sep 17 12:49:16 2007 From: kwmsmith at gmail.com (Kurt Smith) Date: Mon, 17 Sep 2007 11:49:16 -0500 Subject: How to assign a function to another function In-Reply-To: <20070917182359.600c6837.stefano.esposito87@gmail.com> References: <20070917182359.600c6837.stefano.esposito87@gmail.com> Message-ID: On 9/17/07, Stefano Esposito wrote: > Hi all > > what i'm trying to do is this: > > >>>def foo (): > ... return None > ... > >>>def bar (): > ... print "called bar" > ... > >>>def assigner (): > ... foo = bar > ... You need to tell "assigner()" that foo doesn't belong to the local (function) namespace, but rather comes from the global namespace: In [1]: def foo(): ...: return None ...: In [2]: def bar(): ...: print "called bar" ...: ...: In [3]: def assigner(): ...: global foo ...: foo = bar ...: ...: In [4]: assigner() In [5]: foo() called bar Kurt From marek.rocki at wp.pl Sun Sep 16 07:18:30 2007 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sun, 16 Sep 2007 04:18:30 -0700 Subject: generate list of partially accumulated values In-Reply-To: <1189938119.469599.171960@w3g2000hsg.googlegroups.com> References: <1189936564.932553.148800@50g2000hsm.googlegroups.com> <1189936979.276166.103080@w3g2000hsg.googlegroups.com> <1189937183.100462.175070@o80g2000hse.googlegroups.com> <1189938119.469599.171960@w3g2000hsg.googlegroups.com> Message-ID: <1189941510.325769.98490@o80g2000hse.googlegroups.com> Those methods of computing partial sums seem to be O(n^2) or worse. What's wrong with an ordinary loop? for i in xrange(1, len(l)): l[i] += l[i - 1] And as for the list of objects: ll = [l[i - 1].method(l[i]) for i in xrange(1, len(l))] + l[-1] From m.n.summerfield at googlemail.com Wed Sep 26 09:44:23 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Wed, 26 Sep 2007 13:44:23 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> <1190799759.367001.106400@r29g2000hsg.googlegroups.com> <87fy11lo22.fsf@mulj.homelinux.net> <1190804538.469582.96950@22g2000hsm.googlegroups.com> Message-ID: <1190814263.104358.158090@n39g2000hsh.googlegroups.com> On 26 Sep, 13:22, Antoon Pardon wrote: > On 2007-09-26, Mark Summerfield wrote: > > > > > On 26 Sep, 11:27, Hrvoje Niksic wrote: > >> Mark Summerfield writes: > >> > On 26 Sep, 09:51, Hrvoje Niksic wrote: > >> >> Duncan Booth writes: > >> >> > I that's the point though: you can't write one implementation > >> >> > that has good performance for all patterns of use > > >> >> An implementation of sorted dict using a balanced tree as the > >> >> underlying data structure would give decent performance in all the > >> >> mentioned use cases. For example, red-black trees search, insert, and > >> >> delete in O(log n) time. > > >> > Basically, as implemented, I have to invalidate if there is any > >> > change [...] > > >> No argument here, as long as the limitation is understood to be a > >> consequence of the current implementation model. Seriously proposing > >> a sorteddict that is a mere syntactic sugar over dict dooms the PEP to > >> rejection. > > > On the Py3K list GvR made it clear that sorteddict wouldn't be in > > Python until an implementation had been in popular use for some > > time... so I will not put forward a PEP for it. > > >> Major programming language libraries have included sorted mapping and > >> set types for a while now, making the performance and complexity > >> constraints generally well understood. We should make use of that > >> knowledge when designing sorteddict. > > > I know! I use Python and C++ and Qt, so what with the STL and Qt's > > containers I'm used to having far more containers to choose from than > > Python offers. I think Python could do with both sorteddict and > > sortedset in the collections module, but to get decent performance > > will require a balanced tree (or a skiplist) implementation, and I > > don't have the time to do that. Apart from Antoon Pardon's AVL tree, > > there's also Chris Gonnerman's RBTree, also pure Python, with a dict > > API and that seems to accept a cmp function, but again, I don't know > > whether it could be adapted to the sorteddict((mapping | sequence | > > nothing), cmp=None, key=None, reverse=None) API that Paul Hankin > > described. > > Well you should decide what you want. In a previous exchange one of the > things that was wanted was that you could already seed a tree by using > key word arguments so that you could do the following: > > t=Tree(a=15, b=30) > > which would be equivallent to: > > t=Tree() > t.update(a=15,b=30) > > But with the above proposal > > t=Tree(cmp=cmp) > > is not equivallent to > > t=Tree() > t.update(cmp=cmp) > > So it seems the API needs some more sorting out. I think you missed some of the previous postings. The sorteddict API that has emerged so far is (1) apart from the constructor, everything is identical to dict, (2) the constructor takes the same args as sorted(), so if you want to seed with a dict or with keywords you write sorteddict(dict(a=1,b=2), ...), (or you could create a sorteddict and use update() since that takes the same args as dict's constructor). Could your AVLTree support cmp and keys and reverse? From joemystery123 at gmail.com Fri Sep 21 17:04:40 2007 From: joemystery123 at gmail.com (crybaby) Date: Fri, 21 Sep 2007 14:04:40 -0700 Subject: newb: Simple regex problem headache Message-ID: <1190408680.273525.209270@w3g2000hsg.googlegroups.com> import re s1 =' 25000 ' s2 = ' 5.5910 ' mypat = re.compile('[0-9]*(\.[0-9]*|$)') rate= mypat.search(s1) print rate.group() rate=mypat.search(s2) print rate.group() rate = mypat.search(s1) price = float(rate.group()) print price I get an error when it hits the whole number, that is in this format: s1 =' 25000 ' For whole number s2, mypat catching empty string. I want it to give me 25000. I am getting this error: price = float(rate.group()) ValueError: empty string for float() Anyone knows, how I can get 25000 out of s2 = ' 5.5910 ' using regex pattern, mypat = re.compile('[0-9]*(\.[0-9]*|$)'). mypat works fine for real numbers, but doesn't work for whole numbers. thanks From grante at visi.com Thu Sep 20 12:33:49 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Sep 2007 16:33:49 -0000 Subject: Python and RTF References: <1190271676.160077.99270@w3g2000hsg.googlegroups.com> <13f51i4adkseae5@corp.supernews.com> <1190301666.417426.13320@r29g2000hsg.googlegroups.com> <13f57rhcoh575ea@corp.supernews.com> Message-ID: <13f587d9kvoln40@corp.supernews.com> On 2007-09-20, Grant Edwards wrote: > I'm really sure how the LGPL applies to Python applications. That should have read I'm _not_ really sure how the LGPL applies to Python applications. There are clauses about providing a way for the user to replace the library and whatnot. I think that simply defining the API and allowing the user to replace the .pyc file would be sufficient. -- Grant Edwards grante Yow! ... or were you at driving the PONTIAC that visi.com HONKED at me in MIAMI last Tuesday? From hat at se-162.se.wtb.tue.nl Wed Sep 5 04:22:36 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 05 Sep 2007 10:22:36 +0200 Subject: Parse or Pass? References: <1188917032.271543.236420@d55g2000hsg.googlegroups.com> <46DD916E.4000201@v.loewis.de> <46de108a$0$29358$e4fe514c@dreader19.news.xs4all.nl> Message-ID: On 2007-09-05, Martin P. Hellwig wrote: > Martin v. L?wis wrote: > Eingeben = Input: (A bit of) data from outside the function > Ausgeben = Output: (A bit of) data to display, network > connection or file > Zur?ckgeben = Return: (altered)(bits of) data (from Input) > to Output > > Can I assume that Return in general always means that the particular > function has exited with that? If not what is the difference then > between Output and Return? It depends on your point of view imho. You can describe a function call from 'outside', ie I give it values for its parameters, and it returns me a computed return value. You can describe the same thing from 'inside', ie I get values from my caller, compute a result, and output the result. > And then we have "?bergeben" which translates to throughput (giving > over), which in my view is just something that gets data in and puts it > out, contextually unaltered. But would that do that with exiting the I would consider this yet another view, namely performance. Function calls are stil happening, but you focus more on the #calls/second, ie throughput. So depending on what one is interested in, I think, one structures and describes what is happening in a different way. Wouldn't that be a possible explanation for all the subtle different ways of describing the same thing? Albert From m.n.summerfield at googlemail.com Tue Sep 25 04:53:22 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Tue, 25 Sep 2007 08:53:22 -0000 Subject: sorteddict PEP proposal [started off as orderedict] Message-ID: <1190710402.481693.5110@50g2000hsm.googlegroups.com> Hi, Below is a PEP proposal for a sorteddict. It arises out of a discussion on this list that began a few weeks ago with the subject of "An ordered dictionary for the Python library?", and a similar one on the P3K mailing list with the subject "ordered dict for p3k collections?". If there is positive feedback I will submit the PEP to the reviewers, so if you think it is a good idea please say so. (I'm sure that if you _don't_ like it you'll tell me anyway:-) PEP: XXX Title: Sorted Dictionary Version: $Revision$ Last-Modified: $Date$ Author: Mark Summerfield Status: Draft Type: Standards Track Content-Type: text/plain Created: 25-Sep-2007 Python-Version: 2.6 Post-History: Abstract This PEP proposes the addition of a sorted dictionary class to the standard library's collections module. Rationale When handling collections of key-value data, it is often convenient to access the data in key order. One way to do this is to use an unsorted data structure (e.g., a Python dict), and then sort the keys as needed. Another way is to use a sorted data structure (e.g., a sorteddict as proposed in this PEP), and simply access the keys, knowing that they are always in sorted order. Both approaches make sense in the right circumstances, but Python currently only supports the first approach out of the box. A sorteddict never needs sorting and is ideal for creating indexes to data where the keys are based on some property of the data. Adding a sorteddict to the collections module would not add significantly to the size of Python's standard library, but would provide a very useful data structure. Specification The proposed sorteddict has the same API to the builtin dict, so can be used as a drop-in replacement. The only behavioural difference being that any list returned by the sorteddict (whether of keys, values, or items) will be in key order, and similarly any iterator returned will iterate in key order. In addition, the keys() method has two optional arguments: keys(firstindex : int = None, secondindex : int = None) -> list of keys The parameter names aren't nice, but using say "start" and "end" would be misleading since the intention is for the parameters to work like they do in range(), e.g. sd.keys() # returns a list of all the sorteddict's keys sd.keys(10) # returns a list of the first 10 keys sd.keys(19, 35) # returns a list of the 19th-34th keys inclusive If an out of range index is given, an IndexError exception is raised. Since the sorteddict's data is always kept in key order, indexes (integer offsets) into the sorteddict make sense. Five additional methods are proposed to take advantage of this: key(index : int) -> value item(index : int) -> (key, value) value(index : int) -> key set_value(index : int, value) delete(index : int) Items and values can still be accessed using the key, e.g., sd[key], since all the dict's methods are available. Examples To keep a collection of filenames on a case-insensitive file system in sorted order, we could use code like this: files = collections.sorteddict.sorteddict() for name in os.listdir("."): files[name.lower()] = name We can add new filenames at any time, safe in the knowledge that whenever we call files.values(), we will get the files in case-insensitive alphabetical order. To be able to iterate over a collection of data items in various predetermined orders, we could maintain two or more sorteddicts: itemsByDate = collections.sorteddict.sorteddict() itemsByName = collections.sorteddict.sorteddict() itemsBySize = collections.sorteddict.sorteddict() for item in listOfItems: itemsByDate["%s\t%17X" % (item.date, id(item))] = item itemsByName["%s\t%17X" % (item.name, id(item))] = item itemsBySize["%s\t%17X" % (item.size, id(item))] = item Here we have used the item IDs to ensure key uniqueness. Now we can iterate in date or name order, for example: for item in itemsByDate: print item.name, item.date Implementation A pure Python implementation is available at: http://pypi.python.org/pypi/sorteddict Copyright This document has been placed in the public domain. From steve at REMOVE-THIS-cybersource.com.au Mon Sep 17 09:36:55 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 17 Sep 2007 13:36:55 -0000 Subject: generating list of sub lists References: <1189931217.415065.102820@w3g2000hsg.googlegroups.com> <46ee5c5e$0$32487$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <13et0nnj3qjlr5e@corp.supernews.com> On Mon, 17 Sep 2007 20:52:14 +1000, Ross Wilson wrote: > cesco wrote: >> Hi, >> >> is there a one-liner to accomplish the following task? >>>From the list >> l = ['string1', 'string2', 'string3'] generate the list of lists >> l = [['string1'], ['string1', 'string2'], ['string1', 'string2', >> 'string3']] >> >> Any help would be appreciated. >> >> Thanks >> Francesco >> >> > l = [l, l] > > Ross Did you *try* your suggestion before posting? >>> l = ['string1', 'string2', 'string3'] >>> assert [l, l] == [['string1'], ['string1', 'string2'], ... ['string1', 'string2', 'string3']] Traceback (most recent call last): File "", line 1, in AssertionError What you've suggested doesn't even come close to what the Original Poster is asking for. -- Steven From bj_666 at gmx.net Sun Sep 16 10:45:12 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Sep 2007 14:45:12 GMT Subject: Needless copying in iterations? References: <5l3ab6F5v20uU3@mid.uni-berlin.de> <13eourdrne86e61@corp.supernews.com> <874phv42to.fsf@benfinney.id.au> <13epv3fnb6bak15@corp.supernews.com> <5l4ghuF655kfU2@mid.uni-berlin.de> <13eqc2daojgho03@corp.supernews.com> Message-ID: <5l4trnF655kfU3@mid.uni-berlin.de> On Sun, 16 Sep 2007 13:31:57 +0000, Steven D'Aprano wrote: > On Sun, 16 Sep 2007 10:58:07 +0000, Marc 'BlackJack' Rintsch wrote: > >> On Sun, 16 Sep 2007 09:50:39 +0000, Steven D'Aprano wrote: >> >>> The point is rather moot, since CPython (and probably other Pythons) do >>> almost no optimizations. But just because Python is a dynamic language >>> doesn't mean there are no optimizations possible: Haskell is a dynamic >>> language, and there are optimizing compilers for it. Of course, it is >>> much simpler for Haskell, because of the type system it uses. >> >> What do you mean by Haskell is a dynamic language? It is statically and >> strict typed and the compiler usually knows all the functions. No >> "surprises", no side effects, no duck typing. > > Haskell's IO monad (and possibly the do monad?) allows side effects. It > would be a pretty poor programming language that didn't allow input or > output! Those side effects stay in the IO monad and don't "leak" into other areas so the compiler still knows much more about the possible data flow than the compilers of most other languages. > Haskell uses type inference, and has a "maybe" type for those cases where > it can't tell what the type will be. Haskell is statically typed, the compiler must know the type of every name otherwise it stops with an error message. The `Maybe` type is for functions that may return something (typed) or `Nothing`. For example a `lookup` function can have the signature: lookup :: Eq a => a -> [(a,b)] -> Maybe b lookup key assocList = ... The compiler infers the concrete types of `a` and `b` at compile time. > If you still don't accept that Haskell is a dynamic language, for > whatever definition of dynamic language you use, I'll withdraw the claim > for the sake of not getting bogged down in long arguments over something > that was really just a minor point. You said it must be possible to optimize a dynamic language because there are optimizing compilers for a dynamic language like Haskell. That's a minor point now? The main problem with optimizing Python code is that the language is dynamically typed -- the types of objects bound to names are only checked at runtime and can change at nearly every point in time while executing. Haskell is statically typed, the types are all inferred at compile time so it's possible to optimize the code for those types. The compiler knows the exact type of every name. By what definition is that a dynamic language!? Ciao, Marc 'BlackJack' Rintsch From zzbbaadd at aol.com Wed Sep 12 01:15:25 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 11 Sep 2007 22:15:25 -0700 Subject: Get the complete command line as-is In-Reply-To: <1189573229.875265.250340@d55g2000hsg.googlegroups.com> References: <1189566000.793354.308420@19g2000hsx.googlegroups.com> <1189567985.089215.108250@k79g2000hse.googlegroups.com> <1189573229.875265.250340@d55g2000hsg.googlegroups.com> Message-ID: <1189574125.024273.119770@o80g2000hse.googlegroups.com> > > It seems that \" will retain the quote marks but then the spaces get > gobbled. > > But if you replace the spaces with another character: > > python.exe test.py \"abc#def\"#123 > > then: > > import sys > commandLine = "".join(sys.argv[1:]) > > prints commandLine.replace('#',' ') > > gives: > > "abc def" 123 > > Don't know if you can use that technique or not. Came back for a second try and found out that: python.exe test.py "\"abc def\" 123" import sys commandLine = "".join(sys.argv[1:]) print commandLine gives: "abc def" 123 From gary.thrapp at navy.mil Wed Sep 12 20:07:30 2007 From: gary.thrapp at navy.mil (grt) Date: Wed, 12 Sep 2007 17:07:30 -0700 Subject: Search path for python script In-Reply-To: <1189638360.283791.273910@50g2000hsm.googlegroups.com> References: <1189633230.265179.58780@19g2000hsx.googlegroups.com> <1189638360.283791.273910@50g2000hsm.googlegroups.com> Message-ID: <1189642050.346119.152410@w3g2000hsg.googlegroups.com> On Sep 12, 4:06 pm, BartlebyScrivener wrote: > On Sep 12, 4:40 pm, grt wrote: > > > > > I'm trying to run a script by typing: > > > python test.py > > What happens if you just type: > > test.py or test > > and hit Enter? > > rd test gives the error: command not found. test.py gives the error: no such file. From bdesth.quelquechose at free.quelquepart.fr Fri Sep 21 20:07:42 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 22 Sep 2007 02:07:42 +0200 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> Message-ID: <46f6e802$0$31736$426a74cc@news.free.fr> Cristian a ?crit : (snip) > To me, the biggest setback for new programmers is the different syntax > Python has for creating functions. Instead of the common (and easy to > grasp) syntax of foo = bar It's actually a mostly *un*common syntax when it comes to functions. The only "mainstream" language I know allowing such a syntax is javascript. Now given python's parsing rules, I wonder how this could be implemented... > Python has the def foo(): syntax. So, when > a new programmer is first introduced to functions they are immediately > confronted with the notion that functions are "different". Which is the case in most non functional languages. > After all, > they have their own special syntax. This seems to only further the > separation newbies make between "data" and "functions" or "stuff" and > "actions". Now, the vast majority of us learned this dichotomy when we > first began to program, so we are ingrained to assume and even expect > a different syntax for function declaration, but in a program like > Python there doesn't seem to be any other reason to have it. Technically, I'd say "patsing rules". From a more conceptual POV, Python was meant to be the missing link between shell scripts and C - and some design choices clearly (IMHO) came from the desire to look familiar enough to C programmers. Even if Python ended up with some (restricted) support for functional programming, it's still has it's roots in procedural programming. > Furthermore, I think it actually inhibits the learning of the > uninitiated. We can, of course, keep the current syntax as sugar. > > To someone who's learning to program wouldn't a syntax like the > further give them all they need and also reinforces the idea that > functions are data just like everything else? Python's functions are *objects* like anything else. And objects are more than data. My 2 cents: show your friend that Python's functions are objects, and that other objects can be callable too... > my_function = function(foo, bar): pass > an_instance_method = function(self, foo): pass > a_method_declaration = method(self, foo): pass > > The last one is mostly my pet peeve of having Python "magically" > create methods out of (what is essentially) a function declaration. There's not much magic in this. What's stored as an attribute of the class *is* a function. It's only wrapped in a method object when looked up. And FWIW, it's the function object itself that takes care of this, thanks to the descriptor protocol (all relevant doc is on python.org). > When I first learned it, it felt wrong but you had to press through it > because there was really no other way of declaring methods. Truth is that you do *not* "declare" methods in Python. From mingliang2000 at gmail.com Wed Sep 19 09:39:55 2007 From: mingliang2000 at gmail.com (Leon) Date: Wed, 19 Sep 2007 06:39:55 -0700 Subject: Find the ID, but how to select/copy the whole string by ID? Message-ID: <1190209195.493784.133340@q3g2000prf.googlegroups.com> Hi everybody, I am a beginer for Python, hope can get help from you guys. What I want to do is : Input an ID -> find the ID in the file -> copy the whole string yyyyy stringID = str(raw_input('Enter the string ID : ')) file = open('strings.txt') sourcefile = file.read() file.close() sourcefile.find (stringID) but how can I select and copy the specific string from to with id I input? Thanks!!! From stodge at gmail.com Tue Sep 18 09:36:09 2007 From: stodge at gmail.com (Stodge) Date: Tue, 18 Sep 2007 06:36:09 -0700 Subject: Saving parameters between Python applications? In-Reply-To: <1190060967.696332.113190@n39g2000hsh.googlegroups.com> References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> <1190060967.696332.113190@n39g2000hsh.googlegroups.com> Message-ID: <1190122569.509673.41420@57g2000hsv.googlegroups.com> os.path.expanduser isn't an option; I need each console/window to maintain different values which I wouldn't get from saving to a user's home directory. Unless I used a different file for each console/window but that just gets me into the same situation I'm already in. I think the only option is to set environment variables using another script. I'm really surprised and disapponited by this. One option I thought of but haven't investigated, is the ability to get the parent (i.e. console's) process id and use that to create a file somewhere. Not sure if this is even possible. On Sep 17, 4:29 pm, bryanjugglercryptograp... at yahoo.com wrote: > On Sep 17, 6:39 am, Laurent Pointal > > > May use simple file in known place: > > $HOME/.myprefs > > $HOME/.conf/myprefs > > > Or host specific configuration API: > > WindowsRegistry HKEY_CURRENT_USER\Software\MySociety\MyApp\myprefs > > > See os.getenv, and _winreg Windows specific module. > > See also standard ConfigParser module > > Also, os.path offers expanduser(). The following is reasonably > portable: > > import os > > user_home_dir = os.path.expanduser("~") > > -- > --Bryan From ivonet at gmail.com Tue Sep 11 17:26:07 2007 From: ivonet at gmail.com (Ivo) Date: Tue, 11 Sep 2007 23:26:07 +0200 Subject: Python Database Apps In-Reply-To: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> Message-ID: <46e70716$0$28777$e4fe514c@dreader12.news.xs4all.nl> darien.watkins at gmail.com wrote: > Kindof a poll, kindof curiosity... > > What is your favorite python - database combination? I'm looking to > make an app that has a local DB and a server side DB. I'm looking at > python and sqlite local side and sql server side. > > Any suggestions???? > > Darien > If you like to make a kind of stand alone app with a database, SQLite a good choice. It is easy to embed into your app. If you keep to ANSI SQL there should be no trouble changing databases at a later date. I use SQLite for my WebSite http://IvoNet.nl and it performs great. The whole database is less than 1Mb including the SQLite module for python. No 50Mb install needed if you just want a simple database. It makes my website very portable and easy to install. MySQL works great to. I have used it a lot and it is very available. Just about every provider can provide you one. Ivo. From steve at holdenweb.com Thu Sep 27 13:11:14 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 13:11:14 -0400 Subject: True of False In-Reply-To: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> Message-ID: koutoo at hotmail.com wrote: > I tried writing a true and false If statement and didn't get > anything? I read some previous posts, but I must be missing > something. I just tried something easy: > > a = ["a", "b", "c", "d", "e", "f"] > > if "c" in a == True: > Print "Yes" > > When I run this, it runs, but nothing prints. What am I doing wrong? > Thanks. You are unnecessarily adding a comparison with True. The correct way to write that is if "c" in a: print "yes" Bu of course you haven't actually told us what you really did, because the code you represent has syntax errors. >>> a = ["a", "b", "c", "d", "e", "f"] >>> "c" in a True >>> if "c" in a == True: ... print "found it" ... >>> if ("c" in a) == True: ... print "At last!" ... At last! >>> -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From http Fri Sep 7 21:32:31 2007 From: http (Paul Rubin) Date: 07 Sep 2007 18:32:31 -0700 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> <87wsv2ox5t.fsf@benfinney.id.au> Message-ID: <7xhcm67xhs.fsf@ruckus.brouhaha.com> Ben Finney writes: > > http://docs.python.org/lib/module-uuid.html > I second this recommendation. If you want arbitrary unique IDs that > are not a function of the data they identify, the simplest solution is > a monotonically-increasing serial number. If you want more than that, > you might as well go straight to the standard UUIDs. The standard UUID's as described in that url don't make any serious attempt to be unguessable. It's better to use a string from os.urandom(). To Stephen: double oops, I was thinking of hex digits rather than bytes when I suggested reading 32 (length of an md5 hash) or 40 (length of an sha1 hash) from os.urandom. That should have said 16 or 20 bytes. If k is the number of unique id's you'll actually use, and N is the number of possible random uid's (so for 16 bytes, N=2**128 since 16 bytes is 128 bits), the probability of a collision occuring is approximately exp(-k**2 / (2*N)), assuming k is small compared with sqrt(N). From danfolkes at gmail.com Mon Sep 17 09:50:18 2007 From: danfolkes at gmail.com (danfolkes) Date: Mon, 17 Sep 2007 13:50:18 -0000 Subject: Web Programming thru python In-Reply-To: <1190027654.008396.326100@57g2000hsv.googlegroups.com> References: <1190027654.008396.326100@57g2000hsv.googlegroups.com> Message-ID: <1190037018.743304.142700@19g2000hsx.googlegroups.com> I have been wondering the same thing. I know you have to load the mod_python into apache. But I failed on setting that up. I run an ubuntu server. But I would check out a site like this: http://webpython.codepoint.net/mod_python -Daniel On Sep 17, 7:14 am, python_lover wrote: > HI, > > Please help how to execute a py file with xitami. > > I installed xitami , downloaded lrwp file. > > accessing the first web application program > > import urllib > # Get a file-like object for the Python Web site's home page. > f = urllib.urlopen("http://www.python.org") > # Read from the object, storing the page's contents in 's'. > s = f.read() > f.close() > > through browser like "http://localhost/first.py > > it is dispaying the source code of the first.py. > > Please help me how to execute the file. > > thank you. From m.n.summerfield at googlemail.com Wed Sep 26 05:42:39 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Wed, 26 Sep 2007 09:42:39 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <87sl51lshd.fsf@mulj.homelinux.net> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> Message-ID: <1190799759.367001.106400@r29g2000hsg.googlegroups.com> On 26 Sep, 09:51, Hrvoje Niksic wrote: > Duncan Booth writes: > > I that's the point though: you can't write one implementation that has good > > performance for all patterns of use > > An implementation of sorted dict using a balanced tree as the > underlying data structure would give decent performance in all the > mentioned use cases. For example, red-black trees search, insert, and > delete in O(log n) time. Basically, as implemented, I have to invalidate if there is any change to a key _or_ to a value because if cmp or key functions are specified they could be using the key, the value, or even both. (If key and cmp were both None and reverse was False, I could use the bisect module and maintain the keys in sorted order at all times in that case, but then performance would vary considerably depending on use which I think would be v. confusing for users.) You are quite right that using a balanced tree (red-black, AVL, or b*tree) would provide decent performance in all the use cases. There appear to be two on PyPI (rbtree and pyavl), but both seem to be C extensions. Antoon Pardon has a pure Python AVL tree, but whether he could or would produce a version that had the sorteddict API, I don't know. From gagsl-py2 at yahoo.com.ar Thu Sep 6 23:20:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Sep 2007 00:20:55 -0300 Subject: why should I learn python References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> <13e1e52cfb1u505@corp.supernews.com> Message-ID: En Thu, 06 Sep 2007 23:34:10 -0300, Grant Edwards escribi?: > On 2007-09-06, Torsten Bronger wrote: >> Hall?chen! >> >> Tom Brown writes: >> >>> [...] Python has been by far the easiest to develop in. Some >>> people might say it is not "real programming" because it is so >>> easy. >> >> I can't believe this. Have you really heard such a statement? > > Maybe it's a allusion to that fake Stroustrup interview where > he supposedly explains that C++ was meant to be a difficult > language to use as a means to keep more programmers employed at > higher salaries? I always thought the only goal of the C++ standard comittee was to devise the most intrincate and convoluted rule ever imaginable. It's like playing AD&D: the basic manual says something, but The Book Of The Perfect And Sublime Elf says that in this case this other rule applies, but a warrior Elf can read in The Ultimate And Most Complete Warrior Companion a totally different rule, but the character's alignment forbids all the three possibilities... -- Gabriel Genellina From zzbbaadd at aol.com Fri Sep 28 11:25:22 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 08:25:22 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <5m4126FbgjabU1@mid.uni-berlin.de> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> Message-ID: <1190993122.979034.305060@50g2000hsm.googlegroups.com> On Sep 28, 2:49 am, "Diez B. Roggisch" wrote: > TheFlyingDutchman wrote: > > >> The fact that you compare and criticise the simple annotations like > >> static or abstract with the much more powerful decorator concept shows > >> that, despite being the maintainer of a > >> soon-to-be-ruling-the-python-world Python 3 fork, lack understanding of > >> even the most basic language features. Which isn't exactly news.[1] > > > Don't you mean "lack appreciation for the non-basic language > > features"? static, class and abstract > > are basic language features that I appreciate. "decorators" have been > > in Python for only a small part of its existence, they aren't in the > > vast majority of languages (if any other language even has them) which > > means people write all kinds of software without them. Or rather, most > > of the software ever written didn't use decorators. Doesn't sound > > basic at all. > > People did write all kinds of software in Assembler. And large portions of > these people complained about every feature that some new language > introduced. > > All serious languages are turing-complete. So can we put away with this > non-sense argument right away, please? You said it was a most basic language feature. I still haven't heard anything that leads me to believe that statement is correct. What languages implemented decorators as a most basic language feature? Python didn't have them for over a decade so it doesn't qualify. > > >> Maybe you should start using python more and _then_ start discussions > >> about it's features, when you have good grounds and can provide viable > >> alternatives? But I guess that's a wish that won't be granted.... > > > static and abstract keywords would seem to be very viable > > alternatives. Viable enough that several language designers used them. > > As I said - you don't get it. The decorators (in conjunction with the > descriptor protocol - ever heard of that?) are very powerful yet lead as an > artifact to simple, declarative implementations of features you like, > namely static and abstract methods. You said I had to provide a viable alternative. I did that. I haven't heard of the descriptor protocol. One of the problems with "getting" decorators is that they are not in older books at all and newer books like Beginning Python from Novice to Professional (c) 2005 Magnus Lie Hetland, that I own, devote almost nothing to them. Out of 640 pages they are only mentioned in one paragraph that is in a section titled "Static Methods and Class Methods",(and followed by a class example with @staticmethod and @classmethod). So it seems like Magnus Lie Hetland didn't think they were very important and he had Professional in his book title. > > And as you seem being so reluctant to let new features creep into the > language, the introduction of new keywords you like? I'm not against additions on principle. > > Besides, those 'several language designers' seem to think that the > introduction of keywords isn't enough, but a general purpose annotation > scheme seems to be viable - or how do you explain e.g. JDK 1.5 Annotations? I certainly wouldn't call them a basic language feature. Java 1.0 came out in January 1996, Java 1.5 in September 2004. It doesn't appear that the language designer of Java, James Gosling, is still at the wheel or BDFL. But yes, Java is showing signs of "complexity creep". You'll be happy to know that I really dislike the C++ template syntax and Java has decided to add something similar. From grue at mail.ru Wed Sep 12 05:32:41 2007 From: grue at mail.ru (Timofei Shatrov) Date: Wed, 12 Sep 2007 09:32:41 GMT Subject: need scsh in a wikip article References: <1189563310.268611.4550@r34g2000hsd.googlegroups.com> <1189568488.932657.129510@o80g2000hse.googlegroups.com> <1189588209.836060.46920@50g2000hsm.googlegroups.com> Message-ID: <46e7b20d.4115317@news.readfreenews.net> On Wed, 12 Sep 2007 02:10:09 -0700, "cmr.Pent at gmail.com" tried to confuse everyone with this message: >> someone please add scsh there. > >Why can't YOU add scsh or I am missing something?? > Maybe he is banned? -- |Don't believe this - you're not worthless ,gr---------.ru |It's us against millions and we can't take them all... | ue il | |But we can take them on! | @ma | | (A Wilhelm Scream - The Rip) |______________| From mcknight0219 at gmail.com Sat Sep 8 14:13:02 2007 From: mcknight0219 at gmail.com (Jimmy) Date: Sat, 08 Sep 2007 11:13:02 -0700 Subject: wxpython automate progress bar Message-ID: <1189275182.954315.16090@19g2000hsx.googlegroups.com> Hi, I want a progress bar to increase automatically, so I wrote code like this: current = 0 while True: if current == 100: current = 0 self._gauge.SetValue(current) time.sleep(0.1) current = current + 1 I put this in the __init__ section, however, the window will never show! and there are error message like this: ** (python:28543): CRITICAL **: clearlooks_style_draw_handle: assertion `width >= -1' failed can anyone tell me why this happen?Thanks :) From harlinseritt at yahoo.com Thu Sep 13 16:50:51 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: Thu, 13 Sep 2007 13:50:51 -0700 Subject: Decimal formatting Message-ID: <1189716651.810481.260850@y42g2000hsy.googlegroups.com> Cant believe I have to post this and get help... and can't believe I couldnt Google it reasonably well enough... I need to take a float variable and have it display as a string to always have two decimal places: 12.3333 -> 12.33 1.0 -> 1.00 etc... Anyone willing to help with this one? thanks, Harlin From dnhkng at googlemail.com Wed Sep 5 06:40:22 2007 From: dnhkng at googlemail.com (Dr Mephesto) Date: Wed, 05 Sep 2007 10:40:22 -0000 Subject: creating really big lists In-Reply-To: <5k7eacF2g23sU2@mid.uni-berlin.de> References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> <87ejhd2zzt.fsf@rudin.co.uk> <5k7eacF2g23sU2@mid.uni-berlin.de> Message-ID: <1188988822.903881.244480@d55g2000hsg.googlegroups.com> yep, thats why I'm asking :) On Sep 5, 12:22 pm, "Diez B. Roggisch" wrote: > Paul Rudin wrote: > > Dr Mephesto writes: > > >> Hi! > > >> I would like to create a pretty big list of lists; a list 3,000,000 > >> long, each entry containing 5 empty lists. My application will append > >> data each of the 5 sublists, so they will be of varying lengths (so no > >> arrays!). > > >> Does anyone know the most efficient way to do this? I have tried: > > >> list = [[[],[],[],[],[]] for _ in xrange(3000000)] > > >> but its not soooo fast. Is there a way to do this without looping? > > > You can do: > > > [[[],[],[],[],[]]] * 3000000 > > > although I don't know if it performs any better than what you already > > have. > > You are aware that this is hugely different, because the nested lists are > references, not new instances? Thus the outcome is most probably (given the > gazillion of times people stumbled over this) not the desired one... > > Diez From zzbbaadd at aol.com Wed Sep 19 15:01:52 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 19 Sep 2007 12:01:52 -0700 Subject: Google and Python Message-ID: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> Around 2000 I heard that Google was using Python to some extent. Now I see that Guido Van Rossum works for them as well as Alex Martellis who has the title "Uber Technical Lead" which seems to imply some fairly heavy Python usage there. I was wondering what is done at Google with Python and which Python "environments/applications" (Zope, TurboGears, mod_python ...) are in use, and what is done with other languages, and which other languages are they using. From joerg.rech at gmail.com Tue Sep 25 14:28:13 2007 From: joerg.rech at gmail.com (Joerg Rech) Date: Tue, 25 Sep 2007 11:28:13 -0700 Subject: Survey about Visual Annotations for Software Models Message-ID: <1190744893.192073.163320@22g2000hsm.googlegroups.com> Dear software practitioner, During software development, we often experience problems regarding the compilability, quality (e.g., maintainability), or conformance of our software. With a model-driven approach such as MDSD (Model-Driven Software Development), we might work on a higher abstraction level ( i.e., software models), but we (will) still experience similar problems during the development of our software models. Therefore, in the context of the VIDE project, we are conducting a survey about how software modeling environments should annotate software models in order to provide additional information about these problems. Our goal is to get feedback from you on several annotation concepts and your opinion about other characteristics of defect annotations. Hence, we would like to invite you and members of your organization to participate in the survey at http://www.online-poll.de/uc/vide-ma/. Answering the survey should take about 20-30 minutes. The survey will close on 1 October 2007. We will draw five winners from all participants who finalized the survey; they will get an Amazon gift certificate (either amazon.com or from a local site) for $50. Please pass information about this survey on to your colleagues and managers as well as other contacts who might be interested in this topic. Many thanks in advance, Joerg Rech and Axel Spriestersbach --- Joerg Rech Project Manager and Scientist Speaker of the GI-Workgroup on Architecture and Design Patterns Fraunhofer Institute for Experimental Software Engineering (IESE) Tel.: +49 (0) 631/6800-2210 email: joerg.rech (at) iese.fraunhofer.de XING: http://www.xing.com/profile/Joerg_Rech/ LinkedIn: http://www.linkedin.com/in/joergrech From manuel.graune at koeln.de Sun Sep 23 12:38:22 2007 From: manuel.graune at koeln.de (Manuel Graune) Date: Sun, 23 Sep 2007 18:38:22 +0200 Subject: An Editor that Skips to the End of a Def References: <87odfxjgjy.fsf@pobox.com> <3Md*NJqVr@news.chiark.greenend.org.uk> Message-ID: Matthew Woodcraft writes: > Lawrence D'Oliveiro wrote:> > >> > > An interesting story. They say they picked a test for the express > purpose of proving that in some circumstances cursor keys can be faster > than the mouse, but came up with an exercise in which, unusually, the > keyboard part can be performed with one hand, so eliminating the bit > where the other hand moves from the keyboard to the mouse and back. > > -M- > It's quite funny, that what the author proposes as "to make it even harder" actually speeds up the test for the mouse-users quite a bit. And "cursor keys"? Please, every self respecting editor has ways for moving around quite a bit more efficiently. And on top of that a use case, which no one in his right mind would do this way. Accomplishing this task with search-and-replace would have taken about 10 seconds. With Mouse or Keyboard. Regards, Manuel -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 From pydecker at gmail.com Sun Sep 16 08:43:10 2007 From: pydecker at gmail.com (Peter Decker) Date: Sun, 16 Sep 2007 08:43:10 -0400 Subject: Python statements not forcing whitespace is messy? In-Reply-To: References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> <1189890755.870694.29790@r29g2000hsg.googlegroups.com> <46ec6826$1@news.eftel.com.au> Message-ID: On 9/15/07, Steve Holden wrote: > John Machin wrote: > > On 16/09/2007 8:11 AM, James Stroud wrote: > >> Steve Holden wrote: > >>> I don't know why you have a bug up your ass about it, as the > >>> Americans say. > >> I think most Americans say "wild hare up your ass". > > > I guess I got the metaphor wrong? Maybe it's a Southern US thing. I've always heard "bug" used; somehow it doesn't seem that a wild hare would fit! -- # p.d. From mattheww at chiark.greenend.org.uk Sat Sep 22 12:57:43 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 22 Sep 2007 17:57:43 +0100 (BST) Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> Message-ID: Cristian wrote: > To me, the biggest setback for new programmers is the different > syntax Python has for creating functions. Instead of the common (and > easy to grasp) syntax of foo = bar Python has the def foo(): syntax. [...] > in a program like Python there doesn't seem to be any other reason to > have it. One reason for the different syntax is that functions, unlike most other objects, know their own names (which can be shown in tracebacks and the like). -M- From lolu999 at gmail.com Sun Sep 9 22:15:26 2007 From: lolu999 at gmail.com (a.m.) Date: Mon, 10 Sep 2007 02:15:26 -0000 Subject: How to insert in a string @ a index In-Reply-To: <46e4153a$0$32052$426a74cc@news.free.fr> References: <1189274564.462664.131240@22g2000hsm.googlegroups.com> <46e4153a$0$32052$426a74cc@news.free.fr> Message-ID: <1189390526.723534.153390@d55g2000hsg.googlegroups.com> Thanks guys for you help. I ended up doing this way (for the records)... t1 = "hello world hello. hello. \nwhy world hello" while index Message-ID: Shriphani wrote: > If I have a function that loops over a few elements and is expected to > throw out a few tuples as the output, then what should I be using in > place of return ? Use a generator and have it /yield/ rather than /return/ results: >>> def f(items): ... for item in items: ... yield item.isdigit(), item.isupper() ... >>> for result in f("AAA bbb 111".split()): ... print result ... (False, True) (False, False) (True, False) This is a very memory-efficient approach, particularly if the input items are created on the fly, e. g. read from a file one at a time. Peter From steve at holdenweb.com Tue Sep 11 08:26:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 08:26:52 -0400 Subject: Mac OSX sqlite problem. Missing? In-Reply-To: <1189513075.665508.245570@50g2000hsm.googlegroups.com> References: <1189455305.994439.107100@r34g2000hsd.googlegroups.com> <5klocbF498ruU1@mid.uni-berlin.de> <1189457469.285055.212670@r29g2000hsg.googlegroups.com> <1189489594.584753.312330@g4g2000hsf.googlegroups.com> <1189513075.665508.245570@50g2000hsm.googlegroups.com> Message-ID: scottishguy wrote: > On Sep 11, 2:46 am, "attn.steven.... at gmail.com" > wrote: >> On Sep 10, 1:51 pm, ricardo.turp... at gmail.com wrote: >> >> >> >>> Diez B. Roggisch wrote: >>>> Are you by any chance using the python 2.3 when issuing that import >>>> statement? >>>> Diez >>> Unfortunately not :( >>> ibook:~/project1$ python -V >>> Python 2.5 >>> ibook:~/project1$ python >>> Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) >>> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin >>> Type "help", "copyright", "credits" or "license" for more information.>>> import sqlite >>> Traceback (most recent call last): >>> File "", line 1, in >>> ImportError: No module named sqlite >> Isn't it sqlite3 (instead of sqlite)? >> >> Python 2.5.1c1 (r251c1:54692, Apr 17 2007, 21:12:16) >> [GCC 4.0.0 (Apple Computer, Inc. build 5026)] on darwin >> Type "help", "copyright", "credits" or "license" for more information.>>> import sqlite3 >>>>> sqlite3.Connection >> >>> sqlite3.Connection.__doc__ >> >> 'SQLite database connection object.' >> >> >> >> I also see it under that name in the repository: >> >> http://svn.python.org/view/python/trunk/Lib/sqlite3/ >> >> -- >> Hope this helps, >> Steven > > The problem is that the user is trying to install the turbogears > framework, and 'tg-admin' tries to import sqlite (not sqlite3) > > He's getting this error: > 'import sqlite. ImportError: No module named sqlite'. > > Without changing the turbogears code, what should he do? Set up a > symbolic link from 'sqlite3' to 'sqlite' ? > An alternative would be to create a local sqlite.py (importable by tg) containing from sqlite3 import * though this may not work with an extension module if namespace tricks are invoked. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From XX.XmcX at XX.XmclaveauX.com Mon Sep 3 01:05:18 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Mon, 03 Sep 2007 07:05:18 +0200 Subject: [python-win32] How can I get the parentWindow.document object? References: <1188695505.993750.180020@19g2000hsx.googlegroups.com> Message-ID: Re! Sorry! The good exemple is : ie = win32com.client.Dispatch("InternetExplorer.Application") window=ie.Document.parentWindow print window.name another : window.alert("Aalleerrtt") -- @-salutations Michel Claveau From Shawn at Milochik.com Thu Sep 6 12:39:31 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Thu, 6 Sep 2007 12:39:31 -0400 Subject: Text processing and file creation In-Reply-To: <46DFE8B9.400@ehas.org> References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> <1189024097.175349.221210@w3g2000hsg.googlegroups.com> <1189027060.889829.282510@r34g2000hsd.googlegroups.com> <46DFE8B9.400@ehas.org> Message-ID: <2dc0c81b0709060939w60152e17q41ec59ac41b27057@mail.gmail.com> Here's my solution, for what it's worth: #!/usr/bin/env python import os input = open("test.txt", "r") counter = 0 fileNum = 0 fileName = "" def newFileName(): global fileNum, fileName while os.path.exists(fileName) or fileName == "": fileNum += 1 x = "%0.5d" % fileNum fileName = "%s.tmp" % x return fileName for line in input: if (fileName == "") or (counter == 5): if fileName: output.close() fileName = newFileName() counter = 0 output = open(fileName, "w") output.write(line) counter += 1 output.close() From deets at nospam.web.de Wed Sep 12 08:48:04 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Sep 2007 14:48:04 +0200 Subject: SIP examples References: <1189598762.360580.119240@22g2000hsm.googlegroups.com> Message-ID: <5kq5g4F50t62U1@mid.uni-berlin.de> Srijit Kumar Bhadra wrote: > I am trying to learn SIP (http://www.riverbankcomputing.co.uk/sip/) > these days. I do not see any examples similar to SWIG. > http://www.swig.org/doc.html has lots of examples. But for SIP, all I see > is a reference guide > (http://www.riverbankcomputing.com/Docs/sip4/sipref.html). Examples help. > Where can I get examples for SIP 4.7? Download pyqt, and look into it. Together with the reference, that's pretty sufficient. Diez From http Thu Sep 27 22:26:43 2007 From: http (Paul Rubin) Date: 27 Sep 2007 19:26:43 -0700 Subject: cute use of lambda References: <1190945901.551940.165240@k79g2000hse.googlegroups.com> Message-ID: <7xejgjmsnw.fsf@ruckus.brouhaha.com> Simon Forman writes: > class FakeQueue(list): > put = list.append > get = lambda self: self.pop(0) from collections import deque class FakeQueue(deque): put = deque.append get = deque.popleft From pyth0nc0d3r at gmail.com Thu Sep 13 15:01:20 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 13 Sep 2007 14:01:20 -0500 Subject: Quick Modules question Message-ID: How do you import modules that aren't in the main python Lib folder? Is it possible to keep it in the same file as the script thats being ran? -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman.barker at gmail.com Thu Sep 20 19:44:07 2007 From: norman.barker at gmail.com (Norm) Date: Thu, 20 Sep 2007 16:44:07 -0700 Subject: Zope review Message-ID: <1190331847.514475.284200@22g2000hsm.googlegroups.com> Hi, without meaning to start a flame war between the various python web tools, I was wondering if anyone had a review of the status of Zope. For example, is it being used for new projects or just maintenance? I really like the look of Zope 3, and the interface/schema pattern for defining objects looks very useful - but if the general feeling is to use a different tool since Zope 3 isn't being used in the community then I would prefer to start with that as I get to grips with Python again. My reason for this is that looking at zope.org, the articles section seems a little old. thanks, Norman From bj_666 at gmx.net Mon Sep 10 04:14:23 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2007 08:14:23 GMT Subject: Python syntax wart References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> <5ki2sdF3nr68U1@mid.individual.net> <5kk8p0F3vfqqU1@mid.uni-berlin.de> Message-ID: <5kkcmvF3vfqqU3@mid.uni-berlin.de> On Mon, 10 Sep 2007 19:54:49 +1200, Lawrence D'Oliveiro wrote: > In message <5kk8p0F3vfqqU1 at mid.uni-berlin.de>, Marc 'BlackJack' Rintsch > wrote: > >> On Mon, 10 Sep 2007 15:02:58 +1200, Lawrence D'Oliveiro wrote: >> >>> In message <5ki2sdF3nr68U1 at mid.individual.net>, Bjoern Schliessmann >>> wrote: >>> >>>> Lawrence D'Oliveiro wrote: >>>>> But then you can no longer use indentation to display the >>>>> two-dimensional structure of the statement. >>>> >>>> How can a statement be two-dimensional? >>> >>> Like this (from C++ code, but the idea is the same): >>> >>> if >>> ( >>> ThisCh >= 'A' and ThisCh <= 'Z' >>> or >>> ThisCh >= '0' and ThisCh <= '9' >>> or >>> ThisCh == '_' >>> or >>> ThisCh == '.' >>> ) >>> ... >> >> I still down see the second dimension. > > Horizontal + vertical = 2 dimensions. Wow I wrote two dimensional programs all the time without knowing it. > A more complicated example: > > if > ( > TheProduct == JobSettings.Product.end() > or > TheProduct->second.PerType != ProductPerPerson > and > TheProduct->second.PerType != ProductPerNone > ) > ... Sorry I still don't understand how this could be called a 2D statement. Or is this already 3D!? I see a tree structure here, but still no table. And this is also easily written that way in Python if you don't insist on the line break after the ``if`` or can live with backslashes. Ciao, Marc 'BlackJack' Rintsch From netizen at gmx.de Sun Sep 30 15:15:05 2007 From: netizen at gmx.de (Michael Fesser) Date: Sun, 30 Sep 2007 21:15:05 +0200 Subject: which language allows you to change an argument's value? References: <1191149233.346818.246170@22g2000hsm.googlegroups.com> <1191170989.227928.252880@g4g2000hsf.googlegroups.com> Message-ID: <04tvf317vuo9kf6fi2mdfoglrsg57g2tas@4ax.com> .oO(Summercool) >I think in Pascal and C, we can never have an >argument modified unless we explicitly allow it, by passing in the >pointer (address) of the argument. Pascal also allows passing by reference, which is done with the keyword 'var' when declaring the function parameters. Object Pascal also allows const parameters. Micha From unews at onlinehome.de Tue Sep 11 05:35:17 2007 From: unews at onlinehome.de (Uwe Grauer) Date: Tue, 11 Sep 2007 11:35:17 +0200 Subject: Python Database Apps In-Reply-To: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> Message-ID: darien.watkins at gmail.com wrote: > Kindof a poll, kindof curiosity... > > What is your favorite python - database combination? I'm looking to > make an app that has a local DB and a server side DB. I'm looking at > python and sqlite local side and sql server side. > > Any suggestions???? > > Darien > http://dabodev.com/ From gagsl-py2 at yahoo.com.ar Mon Sep 17 17:51:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Sep 2007 18:51:23 -0300 Subject: Extracting xml from html References: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> Message-ID: En Mon, 17 Sep 2007 17:31:19 -0300, escribi?: > I am attempting to extract some XML from an HTML document that I get > returned from a form based web page. For some reason, I cannot figure > out how to do this. I thought I could use the minidom module to do it, > but all I get is a screwy traceback: > > Traceback (most recent call last): > File "C:\Python24\lib\xml\dom\expatbuilder.py", line 207, in > parseFile > parser.Parse(buffer, 0) > ExpatError: mismatched tag: line 1, column 357 So your HTML is not a well formed XML document, as many html pages, and you can't use an XML parser. (even a valid HTML document may not be valid XML). Let's try with some mismatched tags: py> text = ''' ... ...

lots of

screwy text including divs and spans

... ... 1126264 ... Mitsubishi ... Mirage DE ... ... ... ''' py> py> import xml.dom.minidom py> doc = xml.dom.minidom.parseString(text) Traceback (most recent call last): ... xml.parsers.expat.ExpatError: mismatched tag: line 3, column 60 You will need a more robust parser, like BeautifulSoup py> from BeautifulSoup import BeautifulSoup py> soup = BeautifulSoup(text) py> for row in soup.findAll("row"): ... print row.recordnum, row.make.contents, row.model.string ... 1126264 [u'Mitsubishi'] Mirage DE Depending on your document, you may prefer to extract the XML blocks using BeautifulSoup, and then parse each one using BeautifulStoneSoup (the XML parser) or xml.etree.ElementTree -- Gabriel Genellina From mark at streamservice.nl Tue Sep 11 18:05:36 2007 From: mark at streamservice.nl (Stream Service || Mark Scholten) Date: Wed, 12 Sep 2007 00:05:36 +0200 Subject: Python.org mirror In-Reply-To: <011a01c7f4bc$b9230ee0$0300a8c0@HPPAVILION> References: <011a01c7f4bc$b9230ee0$0300a8c0@HPPAVILION> Message-ID: Hello, Thank you for the information, I will also contact them. With kind regards, Met vriendelijke groet, Mark Scholten Stream Service Web: http://www.streamservice.nl/ E-mail: mark at streamservice.nl NOC: http://www.mynoc.eu/ NOC e-mail: noc at streamservice.nl Tel.: +31 (0)642 40 86 02 Fax: +31 (0)20 20 101 57 KVK: 08141074 BTW: NL104278274B01 Stream Service ondersteund de opensource gemeenschap met de gratis hosting van http://nl.php.net/ . Stream Service is supporting the opensource community by hosting http://nl.php.net/ for free. ----- Original Message ----- From: "Terry Reedy" To: Sent: Tuesday, September 11, 2007 11:42 PM Subject: Re: Python.org mirror > |Could you inform me about the options to become an officiel python.org > mirror? > > The main python.org site maintainers do not necessarily read this > group/list. > > If no response here, try webmaster at python.org > > > > From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Sep 6 05:51:02 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Sep 2007 11:51:02 +0200 Subject: We need PIGs :) In-Reply-To: <87hcm81dot.fsf@kip.sateh.com> References: <46d74472$0$402$426a34cc@news.free.fr> <87hcm81dot.fsf@kip.sateh.com> Message-ID: <46dfcd87$0$5618$426a34cc@news.free.fr> Stefan Arentz a ?crit : > Bruno Desthuilliers writes: > > ... > >> The problem with Java is that it makes it very painfull to bridge two >> APIs together, while Python usually makes it a breeze (easy >> delegation, no dumb-ass psycho-rigid type system). So Java's solution >> (hyper-formalization) isn't necessary here. > > Interesting. I find Java much more predictable with APIs than Python > actually. I'm not going to debate on this because it's absolutely not what I'm talking about. My point is that Python has: - duck typing, so you don't need one class subclassing another just to satisfy the compiler - as long as the object you send respects the expected protocol, everything's ok - good support for delegation (via the __getattr__/__setattr__ magic methods), so you don't have to go thru the pain of hand-writing all the delegate methods - only the ones for which there's more to be done than straightforward delegation. > Java has pretty strict rules for style and API design, Java has pretty strict rules for almost anything. From zzbbaadd at aol.com Fri Sep 28 17:07:47 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 14:07:47 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> <1191008702.579795.141180@r29g2000hsg.googlegroups.com> <1191009608.985644.271160@50g2000hsm.googlegroups.com> Message-ID: <1191013667.777259.206110@22g2000hsm.googlegroups.com> On Sep 28, 1:09 pm, Steve Holden wrote: > That's because the tutor list doesn't offer a newsgroup. He was probably > just trying to get rid of you. > > Now at 98.75% ... Not sure if that's the reading on your trollmeter or on the meter that measures what percentage of your posts you get huffy. From steve at holdenweb.com Tue Sep 4 10:51:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Sep 2007 07:51:17 -0700 Subject: Parse or Pass? In-Reply-To: <1188917032.271543.236420@d55g2000hsg.googlegroups.com> References: <1188917032.271543.236420@d55g2000hsg.googlegroups.com> Message-ID: frenchy64 wrote: > I'm very confused...I want to describe passing variables to functions > and I've seen these two words used in very similar contexts. > > Is there a difference between them? > In general, "parsing" is analyzing the grammatical structure of a string. People sometimes talk loosely about "parsing the command line". but I don't think that's normally applied to providing the actual arguments (corresponding to the definition's "formal parameters") when a function is called - that's argument passing. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From mail at timgolden.me.uk Thu Sep 6 07:45:04 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 06 Sep 2007 12:45:04 +0100 Subject: Nudge needed for rst to html In-Reply-To: <46DFE68E.2080906@strank.info> References: <46DFE179.40003@timgolden.me.uk> <46DFE68E.2080906@strank.info> Message-ID: <46DFE840.7000607@timgolden.me.uk> Stefan Rank wrote: > on 06.09.2007 13:16 Tim Golden said the following: >> I'm a bit embarrassed about this, but I've scoured >> the docutils docs and I can't seem to work out how >> to take a block of ReStructuredText and output a >> raw HTML fragment, ideally without a surrounding >> document or embedded/linked css etc. (I'm trying >> to allow rst in our helpdesk system which can render >> nicely on the web version and be readable in text). > try this:: > > import docutils.core > > parts = docutils.core.publish_parts("Hello!", writer_name="html") > html = parts['body'] > > tfm: http://docutils.sourceforge.net/docs/api/publisher.html Exactly the nudge I needed. Thanks very much, Stefan. TJG From govisathish at gmail.com Mon Sep 17 07:14:14 2007 From: govisathish at gmail.com (python_lover) Date: Mon, 17 Sep 2007 11:14:14 -0000 Subject: Web Programming thru python Message-ID: <1190027654.008396.326100@57g2000hsv.googlegroups.com> HI, Please help how to execute a py file with xitami. I installed xitami , downloaded lrwp file. accessing the first web application program import urllib # Get a file-like object for the Python Web site's home page. f = urllib.urlopen("http://www.python.org") # Read from the object, storing the page's contents in 's'. s = f.read() f.close() through browser like "http://localhost/first.py it is dispaying the source code of the first.py. Please help me how to execute the file. thank you. From wink at saville.com Thu Sep 27 00:43:32 2007 From: wink at saville.com (wink) Date: Thu, 27 Sep 2007 04:43:32 -0000 Subject: Asynchronous Messaging In-Reply-To: References: <1190807252.731074.141450@k79g2000hse.googlegroups.com> <1190819912.344267.52680@50g2000hsm.googlegroups.com> Message-ID: <1190868212.383316.20990@57g2000hsv.googlegroups.com> Fredrik, You are most correct, but Queue is slow compared to deque but not for the reason I guessed. Apparently it's because deque is implemented in C while Queue is in python. Using the program below it looks there is about a 35:1 speed difference. 100 d.append 0.000011s 0.1097us per 100 d.popL 0.000011s 0.1097us per 100 q.put 0.000429s 4.2892us per 100 q.get 0.000391s 3.9077us per So someday it _might_ warrant adding Queue to collections. #!/usr/bin/python import timeit import Queue from collections import deque setupD = """ from collections import deque d=deque() cnt = %d for x in xrange(cnt): d.append(x) """ setupQ = """ import Queue q=Queue.Queue() cnt = %d for x in xrange(cnt): q.put(x) """ def main(): cnt = 100 t = timeit.Timer(setup=setupD % cnt, stmt="d.append(0)") time = min(t.repeat(10000, cnt)) print " %9d d.append %fs %7.4fus per" % \ (cnt, time, (time/cnt) * 1000000.0) t = timeit.Timer(setup=setupD % cnt, stmt="d.popleft()") time = min(t.repeat(10000, cnt)) print " %9d d.popL %fs %7.4fus per" % \ (cnt, time, (time/cnt) * 1000000.0) t = timeit.Timer(setup=setupQ % cnt, stmt="q.put(0)") time = min(t.repeat(10000, cnt)) print " %9d q.put %fs %7.4fus per" % \ (cnt, time, (time/cnt) * 1000000.0) t = timeit.Timer(setup=setupQ % cnt, stmt="q.get()") time = min(t.repeat(10000, cnt)) print " %9d q.get %fs %7.4fus per" % \ (cnt, time, (time/cnt) * 1000000.0) if __name__ == "__main__": main() From steve at REMOVE-THIS-cybersource.com.au Thu Sep 13 12:21:36 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Sep 2007 16:21:36 -0000 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189666095.727426.135170@o80g2000hse.googlegroups.com> <1189685403.306218.13270@22g2000hsm.googlegroups.com> <13eigagsuk74l55@corp.supernews.com> <46e94623$0$30375$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <13eiosgssjkt3dd@corp.supernews.com> On Thu, 13 Sep 2007 16:16:03 +0200, Wildemar Wildenburger wrote: > I see merit in using > > (_.foo + _.bar) * _.baz > > instead of > > (s.foo + s.bar) * s.baz > > because I'm trained to interpret the underscore as a synonym for one > space. It's not particularly beautiful, but that is probably a matter of > habituation. And that exact word is probably the reason why I'd still > use self or s (explained by a comment, because I can get very dumb if I > have to). > > It's a matter of taste, so there is no point in bashing a valid > suggestion. It's not just a matter of taste. Reading comprehensibility is an objective, measurable quantity, and I would bet that "(self.foo + self.bar) * self.baz" would be measurably more readable on average than either of your two alternatives _even for those people who claim to hate it_. But what do I care? If people are writing code that only they will see, they can use any conventions they feel like. It's no skin off my nose. But if you're writing code that is going to be seen by others in the wider community, perhaps because it's open source, or because you're working in a team of coders, or even because you're posting snippets to comp.lang.python asking for assistance, then it is wise to write using conventions that others use. The harder you make it for people to read your code, the fewer people will be willing or able or bothered to read it. -- Steven. From jstroud at mbi.ucla.edu Mon Sep 17 04:08:43 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 17 Sep 2007 01:08:43 -0700 Subject: adding a static class to another class In-Reply-To: References: Message-ID: James Stroud wrote: > Nathan Harmston wrote: >> And also preventing more than one Manager instance instantiated at one >> time. > > Forgot to answer this. You want the singleton pattern: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558 But not really a singleton now that I think about it... class Singletonish(object): """ A python singletonish """ class __impl(object): """ Implementation of the singletonish interface """ def spam(self): """ Test method, return singletonish id """ return id(self) # storage for the instance reference __instance = None def __init__(self): """ Create singletonish instance """ Singletonish.__instance = Singletonish.__impl() def __getattr__(self, attr): """ Delegate access to implementation """ if attr == '__id__': return id(Singletonish.__instance) return getattr(Singletonish.__instance, attr) def __setattr__(self, attr, value): """ Delegate access to implementation """ return setattr(Singletonish.__instance, attr, value) In action: py> class Singletonish(object): ... """ A python singletonish """ ... class __impl(object): ... """ Implementation of the singletonish interface """ ... def spam(self): ... """ Test method, return singletonish id """ ... return id(self) ... # storage for the instance reference ... __instance = None ... def __init__(self): ... """ Create singletonish instance """ ... Singletonish.__instance = Singletonish.__impl() ... def __getattr__(self, attr): ... """ Delegate access to implementation """ ... return getattr(Singletonish.__instance, attr) ... def __setattr__(self, attr, value): ... """ Delegate access to implementation """ ... return setattr(Singletonish.__instance, attr, value) ... py> s = Singletonish() py> print s.spam() 18727248 py> py> t = Singletonish() py> print t.spam() 18682480 py> print s.spam() 18682480 Of course t and s are not /really/ the same: py> print id(t) 18727056 py> print id(s) 18727280 py> assert t is s ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in But this shouldn't matter unless you have a special use case because the implementation to all Singletonish objects are delegated to to the latest __impl object and so behave identically. James From gagsl-py2 at yahoo.com.ar Mon Sep 10 05:29:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 10 Sep 2007 02:29:15 -0700 Subject: concise code (beginner) In-Reply-To: <13e99756io95p66@corp.supernews.com> References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> <13e99756io95p66@corp.supernews.com> Message-ID: <1189416555.067037.244350@k79g2000hse.googlegroups.com> "Lawrence D'Oliveiro" wrote in message news:fbqo83$8fd$1 at lust.ihug.co.nz... Why not just build a new list? E.g. newdevs = [] for dev in devs : ... if not removing_dev : newdevs.append(dev) #end if #end for devs = newdevs En Sun, 09 Sep 2007 22:58:54 -0300, bambam escribi?: I can try that, but I'm not sure that it will work. The problem is that devList is just a pointer to a list owned by someone else. Making devList point to a new list won't work: I need to make the parent list different. I could do this by adding an extra level of indirection, but I think at the risk making the call environment more complex. Then use [:] to *replace* all the old list items, do not merely rebind the name. That last statement should be, instead: devs[:] = newdevs (Please don't top-post) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Sep 26 01:25:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Sep 2007 02:25:54 -0300 Subject: Best way to do attribute docstrings? References: <1189195567.238990.54440@57g2000hsv.googlegroups.com> <1189540345.260656.115760@q5g2000prf.googlegroups.com> <1190770891.044084.123540@50g2000hsm.googlegroups.com> Message-ID: En Tue, 25 Sep 2007 22:41:31 -0300, Ken Kuhlman escribi?: > Replying to myself in case someone finds this interesting. > > Anyway, I took another shot at this with a little fresher mind, and it > was quickly obvious that I was trying to force attributes to behave > more like classes. It was a small step from there to creating a > factory function to return instances of the appropriate class. I'm > much happier with the result than either of the two previously posted > kludges. Still there is something I don't understand on your design. You appear to be always concerned about *class* attributes. *Instance* attributes are far more comon, and usually they change their value many times. > class Animal(object): > four_legs = attr(value = True, doc = "Animal has four legs") > favorite_food = attr('cheese', doc = "Animal's favorite food") > has_fur = attr(False) > has_fur.__doc__ "Animal has fur" As an example, how would you annotate attributes on a hierarchy like this? class Animal(object): can_fly = False # no Animal can fly unless explicitely noted lives = 1 # most Animals have a single life def __init__(self, color, legs, favorite_food): self.color = color self.legs = legs self.favorite_food = favorite_food class Mammal(Animal): pass class Cat(Mammal): def __init__(self, color): Mammal.__init__(self, color=color, legs=4, favorite_food='mice') self.lives = 7 # a cat starts with 7 lives class Mouse(Mammal): def __init__(self, color, personality): Mammal.__init__(self, color=color, legs=4, favorite_food='cheese') self.personality = personality class Bird(Animal): can_fly = True def __init__(self, color): Animal.__init__(self, color=color, legs=2, favorite_food='seed') tweety = Bird('yellow') sylvester = Cat('black') tom = Cat('blue') jerry = Mouse('brown', 'nice') itchy = Mouse('blue', 'sadist') scratchy = Cat('black') scratchy.lives = 7**7 # or so... print tweety.legs print scratchy.color print scratchy.lives -- Gabriel Genellina From m.n.summerfield at googlemail.com Sat Sep 15 01:10:02 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Fri, 14 Sep 2007 22:10:02 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> <1189753968.917636.310120@19g2000hsx.googlegroups.com> <1189800045.642278.313860@o80g2000hse.googlegroups.com> Message-ID: <1189833002.694934.284960@57g2000hsv.googlegroups.com> On 14 Sep, 21:23, James Stroud wrote: > Mark Summerfield wrote: > > I guess I'll have to rename my module (although unfortunately, my book > > has just gone into production and I have a (simpler) example of what I > > considered to be an ordered dict, so I will be adding to the > > terminology confusion). That notwithstanding, given that it is a > > sorteddict, how is the API? > > I must think the API good because I have been implementing, in parallel > with this discussion, my own "OrderedDict" with a very similar API (this > is part of a larger project where I recently found the need to have a > well-implemented ordered dict). The only real omission I see is to allow > instantiating a "sorted dict" with an optional cmp function--to allow > the generalization of such features as case-independence, etc. I tend to create different orderings by munging the keys rather than by having optional cmp functions (as you'll see in the sorteddict.py docstring). I've now put sorteddict on PyPI (with docs & tests): http://pypi.python.org/pypi/sorteddict I'm going offline for a week, so I'll see if there's any consensus or progress when I'm back online, and then decide whether to do a PEP or not. From mcknight0219 at gmail.com Sat Sep 8 13:27:27 2007 From: mcknight0219 at gmail.com (Jimmy) Date: Sat, 08 Sep 2007 10:27:27 -0700 Subject: wxPython unexpected exit In-Reply-To: <1189172540.784080.231440@22g2000hsm.googlegroups.com> References: <1189152617.169438.296630@d55g2000hsg.googlegroups.com> <1189172540.784080.231440@22g2000hsm.googlegroups.com> Message-ID: <1189272447.892980.282380@r29g2000hsg.googlegroups.com> On Sep 7, 9:42 pm, kyoso... at gmail.com wrote: > On Sep 7, 3:10 am, Jimmy wrote: > > > > > Hi, wxPython is cool and easy to use, But I ran into a problem > > recently when I try to write a GUI. > > The thing is I want to periodically update the content of StatixText > > object, so after create them, I pack them into a list...the problem > > comes when I later try to extract them from the list! I don't know > > why? > > my code is as following: > > > import wx, socket > > import thread > > > class MyFrame(wx.Frame): > > > firstrun = 0 > > def __init__(self): > > wx.Frame.__init__(self, None, -1, 'Notifier') > > self.panel = wx.Panel(self, -1) > > self.length = 50 > > self.scale = 0.6 > > self.count = 5 > > self.size = wx.Frame.GetSize(self) > > self.distance = self.size[1] / self.count > > self.labellist = [] > > self.gaugelist = [] > > > def ParseAndDisplay(self, data): > > print "Successful access to main Frame class" > > print 'And receive data: ', data > > if MyFrame.firstrun == 0: > > print 'First time run' > > items = 3 > > for i in range(items): > > self.labellist.append(wx.StaticText(self.panel, -1, data+str(i), > > (150, 50+i*20), (300,30))) > > MyFrame.firstrun = 1 > > else: > > self.labellist[0].SetLabel('AAA')//PROGRAM WILL ABORT HERE!!! > > self.labellist[1].SetLabel("Guo") > > self.labellist[2].SetLabel("Qiang") > > > class NetUdp: > > > def __init__(self): > > self.port = 8081 > > self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > > self.s.bind(("", self.port)) > > print "Listening on port", self.port > > > def recvdata(self): > > data, addr = self.s.recvfrom(1024) > > return data > > > def netThread(): > > netudp = NetUdp() > > while True: > > data = netudp.recvdata() > > frame.ParseAndDisplay(data) > > > if __name__ == '__main__': > > firstrun = 0 > > app = wx.PySimpleApp() > > frame = MyFrame() > > frame.Show() > > # start network thread first > > id = thread.start_new_thread(netThread, ()) > > # main wxpython loop begins > > app.MainLoop() > > > I know the code is ugly, but can anyone really save me here! > > If you use threads that update the GUI, you need to take a look at the > following wiki page:http://wiki.wxpython.org/LongRunningTasks > > I've used the techniques therein and they *just work*. I'm not sure if > you can set values on items in a list or not. I've tried that sort of > thing and sometimes it works and sometimes it doesn't. > > The wxPython group is probably the best place to ask these questions > anyway:http://www.wxpython.org/maillist.php > > Mike Thanks for your help! It seems work! Another question: I create a progress bar, and on creation, it will be displayed, How can I invisualize it when later I no longer need it? From tedpottel at gmail.com Sat Sep 22 11:44:38 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Sat, 22 Sep 2007 15:44:38 -0000 Subject: can I run pythons IDLE from a command line?? Message-ID: <1190475878.971841.253140@k79g2000hse.googlegroups.com> Hi, Is their a version of pythons IDLE that will run in a dos command line? The reason is that I would like to be able to run python code interactively from my parable by connecting to my desktop using remote command line or a telnet program. From shaileshk at gmail.com Sun Sep 30 23:18:00 2007 From: shaileshk at gmail.com (shailesh) Date: Sun, 30 Sep 2007 20:18:00 -0700 Subject: Creating a custom python python distribution Message-ID: <1191208680.221428.11880@50g2000hsm.googlegroups.com> Hi, I wish to create a Python distribution includind Python and some other libraries (Zope 3, PyWin32, numpy, lxml, etc.) which are required for my applications. e.g. there are Enthough and ASPN distributions of Python. Unfortunately, I have not been able to find the right documentation for this purpose. Could some one give an overview of what needs to be done for this purpose? With regards, -Shailesh From sysfault at gmail.com Thu Sep 20 12:20:09 2007 From: sysfault at gmail.com (Anthony Greene) Date: Thu, 20 Sep 2007 12:20:09 -0400 Subject: os.path.getmtime() and compare with a date type In-Reply-To: <1190302285.127448.288010@22g2000hsm.googlegroups.com> References: <1190302285.127448.288010@22g2000hsm.googlegroups.com> Message-ID: <46F29DB9.90102@gmail.com> junchi.tang at gmail.com wrote: > Hi, > I am new to python and are tryint to write a simple program delete log > files that are older than 30 days. > > So I used os.path.getmtime(filepath) and compare it with a date but it > does not compile. > > threshold_time = datetime.date.today() - datetime.timedelta(days=30) > mod_time = os.path.getmtime(file_path) > > if( mod_time < threshold_time): > #delete file > > However the interpreter complains at the if line, say "can't comapre > datetime.date to int > > How can I covert one of them to make it work? > > Thank you! > > You are looking for datetime.datetime.fromtimestamp(mod_time) From ivonet at gmail.com Fri Sep 21 16:29:37 2007 From: ivonet at gmail.com (Ivo) Date: Fri, 21 Sep 2007 22:29:37 +0200 Subject: Resolving windows shortcut to url In-Reply-To: <46f422d8$0$3030$e4fe514c@dreader31.news.xs4all.nl> References: <46f422d8$0$3030$e4fe514c@dreader31.news.xs4all.nl> Message-ID: <46f428ce$0$3030$e4fe514c@dreader31.news.xs4all.nl> Ivo wrote: > Richard Townsend wrote: >> If I have a windows shortcut to a URL, is there a way to get the URL >> in a Python app? >> >> I found some code that uses pythoncom to resolve shortcuts to local >> files, but I haven't found any examples for URLs. >> >> The PyWin32 help mentions the PyIUniformResourceLocator Object, but I >> couldn't find an example of how to use it. >> > do you mean a *.lnk file or a *.url file? for a link (*.lnk) file: from win32com.shell import shell import pythoncom import os, sys class PyShortcut(object): def __init__(self): self._base = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) def load(self, filename): self._base.QueryInterface(pythoncom.IID_IPersistFile).Load(filename) def save(self, filename): self._base.QueryInterface(pythoncom.IID_IPersistFile).Save(filename, 0) def __getattr__(self, name): if name != "_base": return getattr(self._base, name) if __name__=="__main__": lnk = PyShortcut() lnk.load("path to your shortcut file including the .lnk extention even if you don't see it in windows") print "Location:", lnk.GetPath(shell.SLGP_RAWPATH)[0] From marcsgbrevkonto at gmail.com Wed Sep 5 15:54:39 2007 From: marcsgbrevkonto at gmail.com (MarkyMarc) Date: Wed, 05 Sep 2007 19:54:39 -0000 Subject: How to do python and RESTful Message-ID: <1189022079.403495.175800@g4g2000hsf.googlegroups.com> Hi all, I want to make a web service application in python and keywords are RESTful, python and nice urls(urls mapped to python objects). I don't want a big framework but a nice small one, that can just do the things I want. I have be looking at quixote, but is this uptodate? "plain" mod_python, can this make url to http put,get,delete and post? Can some one here point me some where I can read about python and RESTful or have some experiences with other? Any help is apricieted. Regards Marc From steve at holdenweb.com Fri Sep 21 12:11:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Sep 2007 12:11:49 -0400 Subject: calling extension's autoconf/make from distutils In-Reply-To: <1190386224.536371.136640@q3g2000prf.googlegroups.com> References: <1190349834.894931.128050@q3g2000prf.googlegroups.com> <1190386224.536371.136640@q3g2000prf.googlegroups.com> Message-ID: Gary Jefferson wrote: > On Sep 20, 10:43 pm, Gary Jefferson > wrote: >> I've got a python extension that comes with its own standard autoconf/ >> automake system, and I can "python setup.py build" just fine with it >> as long as I have previously done "./configure" in that directory. >> >> However, 'python setup.py bdist_rpm' can't hope to have done './ >> configure' first, as it untars and tries to build the extension there. >> >> Is there a hook for bdist_rpm (and friends) that will allow me to >> insert a './configure' in the build process, sometime before it tries >> to build the extension? >> >> Thanks, >> Gary > > > I ended up simply subclassing 'Extension' and having it os.system('./ > configure') before proceeding. > > This isn't perfect, as it does the './configure' everytime, but it > works. > If it really is a one-off thing, you only need to ruin configure if config-status doesn't exist. That isn't a difficult check ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From michele.simionato at gmail.com Wed Sep 19 22:48:13 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 20 Sep 2007 02:48:13 -0000 Subject: super() doesn't get superclass In-Reply-To: References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> Message-ID: <1190256493.827576.139470@r29g2000hsg.googlegroups.com> On Sep 19, 8:14 pm, Ed Leafe wrote: > On Sep 19, 2007, at 6:52 AM, Michele Simionato wrote: > > > Well, I am personally *against* multiple inheritance (i.e. IMO it > > gives more troubles than advantages) > > For the sorts of examples that have been used in this thread, it > isn't MI that's problematic; it's the poor quality of the design. > > Mixing two complete classes to create a multiply-inherited class is > almost always the sign of poor design. OTOH, mixin-style classes are > a wonderful way to ensure consistency across several different > classes that all need a common behavior added to them. We use mixins > extensively throughout Dabo, and they allow us to give several > classes the desired behaviors, while only having one mixin class to > maintain. I am not against mixins (even if I am certainly very much against the *abuse* of mixins, such as in Zope 2). What I would advocate (but I realize that it will never happen in Python) is single inheritance + mixins a la Ruby. Michele Simionato From deets at nospam.web.de Sun Sep 2 18:29:01 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Sep 2007 00:29:01 +0200 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <5k0rppF1l48jU1@mid.uni-berlin.de> Wildemar Wildenburger schrieb: > Martin v. L?wis wrote: >>>> (2) it is a interpretation language >>> Not quite. It's compiled to byte-code - just like Java (would you call >>> Java an 'interpreted language' ?) >> >> Python is not implemented like Java. In Java (at least in HotSpot), >> the byte code is further compiled to machine code before execution; >> in Python, the byte code is interpreted. >> > OK, good. Naive question now comming to mind: Why doesn't Python do the > latter as well? because of the dynamic nature of it. Java is statically typed, so the JIT can heavily optimize. OTH psyco IS a JIT-compiler to optimize certain calculations which are mostly of a numerical nature. But this can't be done to the extend it is possible in java. Diez From dimonb at gmail.com Tue Sep 25 15:32:21 2007 From: dimonb at gmail.com (Dmitry Balabanov) Date: Tue, 25 Sep 2007 23:32:21 +0400 Subject: [ANN] Release 0.65.1 of Task Coach In-Reply-To: <67dd1f930709231355h16b2954clc219f5fb59eddc9f@mail.gmail.com> References: <67dd1f930709231355h16b2954clc219f5fb59eddc9f@mail.gmail.com> Message-ID: <9550150c0709251232k75da2f10nc1472af7dfc4d869@mail.gmail.com> 2007/9/24, Frank Niessink : > Hi, > > I'm happy to announce release 0.65.1 of Task Coach. This release fixes > one critical bug and two minor bugs. Since the critical bug may lead > to data loss, I recommend users of release 0.65.0 to upgrade. > > Bugs fixed: > > * Saving a task file after adding attachments via the 'add attachment' > menu or context menu fails. > * Tooltip windows steals keyboard focus on some platforms. > * Taskbar icon is not transparent on Linux. > > > What is Task Coach? > > Task Coach is a simple task manager that allows for hierarchical > tasks, i.e. tasks in tasks. Task Coach is open source (GPL) and is > developed using Python and wxPython. You can download Task Coach from: > > http://www.taskcoach.org > > In addition to the source distribution, packaged distributions are > available for Windows XP, Mac OSX, and Linux (Debian and RPM format). > > Note that Task Coach is alpha software, meaning that it is wise to back > up your task file regularly, and especially when upgrading to a new > release. > > Cheers, Frank > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > -- Regards, Dmitry. From ndoe_JTK_05 at yahoo.co.id Wed Sep 19 02:06:14 2007 From: ndoe_JTK_05 at yahoo.co.id (ndoe) Date: Tue, 18 Sep 2007 23:06:14 -0700 Subject: Drag image Message-ID: <1190181974.468405.126430@z24g2000prh.googlegroups.com> i want show image from button? and the image can be drag and rezise ? any body help me!!! i try to make it but is not sucsseful yet From oliviermigeon at gmail.com Mon Sep 3 03:32:22 2007 From: oliviermigeon at gmail.com (olivier) Date: Mon, 03 Sep 2007 00:32:22 -0700 Subject: PYTHONPATH not working on Windows XP (?) In-Reply-To: References: Message-ID: <1188804742.738490.50470@19g2000hsx.googlegroups.com> Hi, > Any suggestions for adding my path to sys.path permanently? You can write a file in Lib/site-packages with a 'pth' extension (the name itself doesn't matter) containing the path you want to add. Example: MyCustomLib.pth: C:/docs/utils And be careful with path separator on win32. It should be "/" or "\\", never "\". Regards, Olivier From prince9919 at gmail.com Thu Sep 6 05:56:16 2007 From: prince9919 at gmail.com (Renu) Date: Thu, 06 Sep 2007 09:56:16 -0000 Subject: interesting puzzle......try this you will be rewarded... Message-ID: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> Hi, Just click on this link n use ur common sence to navigate. It has 23 pages one after the other, starting from this first Page. The trick is to find a way to go to the next page. If u can really go to the 23rd page ur a genius in ur own respect :) So best of luck n keep clicking, tik tik.... http://iamhere.50webs.com From larry.bates at websafe.com Tue Sep 25 12:17:47 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 25 Sep 2007 11:17:47 -0500 Subject: HTTPS request In-Reply-To: <1190730718.341771.215970@19g2000hsx.googlegroups.com> References: <1190730718.341771.215970@19g2000hsx.googlegroups.com> Message-ID: Johny wrote: > If I need to log in to a site using https protocol must I use > certification file and key file? > The class HTTPSConnection syntax is > class HTTPSConnection( host[, port, key_file, cert_file]) > > and I do not know if it is nescessary or not. > Thanks for help. > L. > Depends on what the server requires. You can do basic authenticate to a https: site if it supports it. -Larry From jimrthomas at gmail.com Thu Sep 13 07:51:36 2007 From: jimrthomas at gmail.com (Philem) Date: Thu, 13 Sep 2007 11:51:36 -0000 Subject: Python+Expect+Win32 = Not Possible? In-Reply-To: <1189657637.539038.317280@k79g2000hse.googlegroups.com> References: <1189657637.539038.317280@k79g2000hse.googlegroups.com> Message-ID: <1189684296.283237.286220@g4g2000hsf.googlegroups.com> On Sep 13, 12:27 am, gamename wrote: > Hi, > > Is it still the case there is no practical Expect-like module for > win32? I know that cygwin can support pexpect, but that isn't an > option here --- I have to use a native win32 Python version. > > Are there alternatives, or is it simply not an option to replicate > Expect on win32 with python? > > All I'm trying to do is start a couple processes, wait for each to say > "done" on stdout and then quit (or timeout if something went wrong). > > TIA, > -T You could try this link: http://www.activestate.com/Products/activetcl/features.plex and see if that gives you what you need. Luck! -J From alperkanat at gmail.com Mon Sep 10 14:38:26 2007 From: alperkanat at gmail.com (T-u-N-i-X) Date: Mon, 10 Sep 2007 11:38:26 -0700 Subject: PIL Error: "cannot read interlaced PNG files" Message-ID: <1189449506.496986.88290@y42g2000hsy.googlegroups.com> Hey There, I'm developing an application that lets the user to upload JPG and PNG files. I'm using PIL to check the images after the upload (like checking it storage size, width and height). But PIL raises an error: "cannot read interlaced PNG files" It says that interlaced PNG files are not supported in the PIL documentation. I'm using PIL 1.1.6-2 on Arch Linux.. I can check all images with: from PIL import Image im = Image.open('image.png') im.info which returns a dictionary about the image. If the dict has 'interlace' key with the value 1, then I reject the event that's being send with a validation error. But I don't think this is a good idea since this could be very annoying for the users. From sjmachin at lexicon.net Sat Sep 15 08:41:31 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Sep 2007 05:41:31 -0700 Subject: int('\x23') != 0x23 (a.k.a convert char to integer of its byte representation) In-Reply-To: <1189857328.342615.105660@g4g2000hsf.googlegroups.com> References: <1189857328.342615.105660@g4g2000hsf.googlegroups.com> Message-ID: <1189860091.937055.284120@n39g2000hsh.googlegroups.com> On Sep 15, 9:55 pm, Boris Du?ek wrote: > Hi, > > I am looking for the best way to convert a string of length 1 (= 1 > character as string) to integer that has the same value as numeric > representation of that character. Background: I am writing functions > abstracting endianness, e.g. converting a string of length 4 to the > appropriate integer value (e.g. '\x01\x00\x00\x00' = 2**24 for big > endian memory, 2**0 for little endian memory). For this, I need to > know the numeric value of each byte and sum them according to > endianness. > > I thought that something like int('\x01') might work, provided the > argument is string of length 1, but that throws an error: > > >>> int('\x12') > > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for int(): > > The code I want to write looks like this: > > mem = '\x11\x22\x33\x44' > factor = 1 > sum = 0 > for byte in mem: > sum += int(byte) * factor > factor *= 2**8 > > Could you please tell me how to achieve what I want in Python? (it > would be straightforward in C) > 'BlackJack' has already sent you looking for the docs for ord() and the struct module but a few other clues seem necessary: 1. Don't "think that something like int() might work", read the docs. 2. "factor *= 2 **8"?? Python compiles to bytecode; don't make it work any harder than it has to. "factor" is quite unnecessary. That loop needs exactly 1 statement: sum = (sum << 8) + ord(byte) 3. Don't use "sum" as a variable name; it will shadow the sum() built- in function. 4. Read through the docs for *all* the built-in functions -- all kinds of interesting and useful gadgets to be found there. 5. In a dark corner there lives a strange beast called the array module: >>> import array >>> array.array('I', '\x01\x00\x00\x00')[0] 1L >>> array.array('I', '\x00\x00\x00\x01')[0] 16777216L >>> 2**24 16777216 >>> HTH, John From steve at holdenweb.com Thu Sep 20 05:59:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 20 Sep 2007 05:59:06 -0400 Subject: Sets in Python In-Reply-To: <1190260923.243865.312190@z24g2000prh.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <13f3m15igkstq2e@corp.supernews.com> <1190260923.243865.312190@z24g2000prh.googlegroups.com> Message-ID: Karthik Gurusamy wrote: > On Sep 19, 7:17 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 19 Sep 2007 20:58:03 +0000, Karthik Gurusamy wrote: >>> While it's easy to explain the behavior, I think the decision to dis- >>> allow mutable items as keys is a bit arbitrary. There is no need for >>> dict to recompute hash >> What??? >> >> Of course it does. How else can it look up the key? Because it (somehow) >> just recognizes that it has seen the key before? How? By magic? > > You answered it yourself later. For a mapping service, hash is just > one way to do things. What you need is for each item in the > collection, a unique key. > How you go from the key to the value is not something a programmer > needs to know. > Your mind is set on thinking on hash alone and hence you don't see > beyond it. > There's a reason for that: the developers (and particularly Tim Peters) have, to use a phrase Tim is fond of "optimized the snot" out of dict, and the mechanism is fundamental to much of Python's internals. So don't expect to be able to tamper wiht it without adversely affectinf performance. >>> (first of all, a user doesn't even need to know >>> if underneath 'hashing' is used -- the service is just a mapping between >>> one item to another item). >> The user doesn't need to know the mechanism, but the dict does. Dicts are >> implemented as hash tables. I suppose they could be implemented as >> something else (what? linear lists? some sort of tree?) but the same >> considerations must be made: > > Oh yes. If the keys are all integers (or any set of items that can be > ordered), why not an avl. It has guaranteed O(log N) while a hash in > worst case is O(N). Why you want to tie yourself to the drawbacks of > one datastructure? Understand your goal is not to provide a hash; but > to provide a mapping service. > Possibly so, but the goals also include "excellent speed" and "as wide a set of keys as is (practically) possible". How would you suggest Python avoids "[tying itself] to the drawbacks of one data structure"? Implement different strategies according to the key values used? That'll surely speed things up, not. Python provides you with plenty of tools to implement optimized data structures for your own applications. Arguing for making them language primitives merely reveals your design inexperience. > > the dict must be able to find keys it has >> seen before. How is the dict supposed to recognise the key if the key has >> changed? >> >>> Since we know hashing is used, all that is needed is, a well-defined way >>> to construct a hash out of a mutable. "Given a sequence, how to get a >>> hash" is the problem. >> Nonsense. That's not the problem. The problem is how to get exactly the >> same hash when the sequence has changed. > > Yes, if you keep thinking hash is the only tool you got. > >> In other words, if you have two mutable objects M1 and M2, then you >> expect: >> > > No. I don't expect. I expect the hash to be different. Why do you keep > thinking it's the mappings responsibility to take care of a changing > key. > Because mappings must do precisely that. Do you actually know what a mapping *is*? >> hash(M1) == hash(M2) if and only if M1 and M2 are equal >> hash(M1) != hash(M2) if M1 and M2 are unequal >> >> but also: >> >> if M1 mutates to become equal to M2, hash(M1) must remain the same while >> still being different from hash(M2). >> >> That means that hash() now is a non-deterministic function. hash([1,2,3]) >> will vary according to how the list [1,2,3] was constructed! >> >> Obviously something has to give, because not all of these things are >> mutually compatible. >> >>> If later the given sequence is different, that's >>> not the dict's problem. >> Data structures don't have problems. Programmers do. And language >> designers with sense build languages that minimize the programmers >> problems, not maximize them. > > Yes, here you talk about a different goal altogether. Here comes the > 'arbitrary' part I mentioned. > >>> So if the list changes, it will result in a different hash and we will >>> get a hash-miss. I doubt this is in anyway less intuitive than dis- >>> allowing mutable items as keys. >> The choices for the language designer are: >> >> (1) Invent some sort of magical non-deterministic hash function which >> always does the Right Thing. > > Nope, just say if the new sequence is different, you don't find the > item in the dict. > >> (2) Allow the hash of mutable objects to change, which means you can use >> mutable objects as keys in dicts but if you change them, you can no >> longer find them in the dict. They'll still be there, using up memory, >> but you can't get to them. > > In the new model, at the time of addition, you need to remember the > key at that time. If it's a list, you make a copy of the items. > Right. Simple. And completely impractical. >> (3) Simply disallow mutable objects as keys. >> >> Alternative 1 is impossible, as we've seen, because the requirements for >> the Right Thing are not mutually compatible. >> >> Alternative (2) leads to hard-to-find, hard-to-diagnose bugs where you >> store objects in a dict only for them to mysteriously disappear later. >> Worse, it could lead to bugs like the following hypothetical: > > Of course they can be reached with.. for k in dict... But that hardly provides the required mapping features. What on earth are you thinking?. >>>>> M = [1, 2, 3] >>>>> D = {M: 'parrot'} # pretend this works >>>>> D >> {[1, 2, 3]: 'parrot'}>>> M.append(4) >>>>> D >> {[1, 2, 3, 4]: 'parrot'}>>> D[[1, 2, 3, 4]] > > No, in the new way, the key still remains [1, 2, 3] > What was changed is M. Not the key given to dict at the time of > addition. > Again I'm not describing today's behavior; it's in the new way. > I doubt this new way, whatever it is, is going to have many disciples. >> Traceback (most recent call last): >> File "", line 1, in >> KeyError: [1, 2, 3, 4] >> >> Try explaining that one to programmers: they can SEE the key in the dict >> when they print it, but they can't get it or delete it because the hash >> has changed. > > No they don't. They see the key at the time of addition ([1,2,3]) >> Alternative 3 is easy to deal with: simply don't use mutable objects as >> keys. That's what Python does. Sure, the programmer sometimes needs to >> work around the lack (convert the list into a tuple, or a string, or >> pickle it, whatever...) which on rare occasions is hard to do, but at >> least there are no mysterious, hard to track down bugs. > > When I first saw key's must'be be mutable, it did appear to me to be > mysterious. There was unnecessary tighter coupling between > implementation details and the service exposed to the programmer. (As > I see it, the root cause of all this is, the dict does not make a copy > of the key at the time of item addition, it just makes a new reference > to the same object) > Light dawns. Dicts are optimized for PERFORMANCE! And for very good reasons. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From winter at biotec.tu-dresden.de Wed Sep 5 07:44:46 2007 From: winter at biotec.tu-dresden.de (Christof Winter) Date: Wed, 05 Sep 2007 13:44:46 +0200 Subject: 2 python questions! In-Reply-To: References: Message-ID: <46DE96AE.1040402@biotec.tu-dresden.de> resist_think at hushmail.com wrote: [...] > Now the second question has to do with images retrieval and > manipulation. Which libraries do you propose to work with to > retrieve and resize images from the web? urllib.urlretrieve() and Python Imaging Library (PIL) From Scott.Daniels at Acm.Org Thu Sep 6 14:00:33 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 06 Sep 2007 11:00:33 -0700 Subject: Beginners Query - Simple counter problem In-Reply-To: References: Message-ID: <13e0g0id9rlmg71@corp.supernews.com> David Barr wrote: > I am brand new to Python (this is my second day), and the only > experience I have with programming was with VBA. Anyway, I'm posting > this to see if anyone would be kind enough to help me with this (I > suspect, very easy to solve) query. > > The following code is in a file which I am running through the > interpreter with the execfile command, yet it yeilds no results. I > appreciate I am obviously doing something really stupid here, but I > can't find it. Any help appreciated. > > > def d6(i): > roll = 0 > count = 0 > while count <= i: > roll = roll + random.randint(1,6) > count += 1 > > return roll > > print d6(3) A) your direct answer: by using <=, you are rolling 4 dice, not 3. B) Much more pythonic: import random def d6(count): result = 0 for die in range(count): result += random.randint(1, 6) return result -Scott David Daniels Scott.Daniels at Acm.Org From vanrpeterson at gmail.com Fri Sep 7 09:13:13 2007 From: vanrpeterson at gmail.com (vanrpeterson at gmail.com) Date: Fri, 07 Sep 2007 06:13:13 -0700 Subject: why should I learn python In-Reply-To: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: <1189170793.413769.137670@19g2000hsx.googlegroups.com> Why use Python? 1)Easy to read, debug and think. 2)Same language for batch scripting, server programming and dynamic web page creation. 3)Libraries like wxPython for desktop and Cherrypy for web development. 4)Pythonic JavaScript Library Mochikit. 5)Engineered for reality, not corporate proprietary control (Microsoft). 6)Less code than Java the Huge. 7)Friendly with C for optimization, if necessary. 8)Works well with SQL, especially PostgreSQL. 9)Everybody is using it, even Microsoft with IronPython. 10)One of the dominant languages driving robotics. 11)Works nicely with UNICODE. 12)Liberal license. 13)And lastly, if you hate programming as I do, you will love Python. Belief is when someone else does the thinking. ~ Buckminster Fuller From steve at REMOVE-THIS-cybersource.com.au Thu Sep 13 11:32:16 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Sep 2007 15:32:16 -0000 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> Message-ID: <13eim00ha4lf356@corp.supernews.com> On Thu, 13 Sep 2007 16:30:36 +0200, BJ?rn Lindqvist wrote: > And I agree with the OP that the convention is really annoying. > > self.rect.width = self.foo(self.rect.x + self.rect.y) * self.boo() > > is much less concise than > > s.rect.width = s.foo(s.rect.x + s.rect.y) * s.boo() Y do u thnk bng cncis is lwys a gd thng? Being concise is not always a good thing. I notice that you separate terms with spaces, even when Python itself doesn't need them. You also are happy to use infix notation, which requires brackets, instead of a postfix or RPN language that doesn't. You also have attributes named "rect" and "width" instead of "r" and "w": s.r.w=s.f(s.r.x+s.r.y)*s.b() There. See how much more readable that isn't? -- Steven From jzgoda at o2.usun.pl Fri Sep 14 15:59:52 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 14 Sep 2007 21:59:52 +0200 Subject: Https conversation - debug? In-Reply-To: <1189799482.314951.238470@r34g2000hsd.googlegroups.com> References: <1189799482.314951.238470@r34g2000hsd.googlegroups.com> Message-ID: Johny napisa?(a): > Is there any good sniffer for https protocol? > How can be watched https conversation? Any packet sniffer will do. Then you have to decrypt the stream. ;) -- Jarek Zgoda http://jpa.berlios.de/ From ankitanand1986 at gmail.com Thu Sep 27 14:42:15 2007 From: ankitanand1986 at gmail.com (Ankit) Date: Thu, 27 Sep 2007 11:42:15 -0700 Subject: Creating Table using Tkinter Message-ID: <1190918535.924299.22750@k79g2000hse.googlegroups.com> Hi guys i need to make a table to store a certain data using Tkinter..I have searched on the group but i have not been able to find a solution that would work for me..The thing is that i want my table to be scrollable both horizontally and vertically and i also want to transmit the data from the table serially to a microcontroller so i also need to make sure that i am able to read all the data individually..I am writing my code on Windows..my table is dynamic that is the number of columns are fixed but the number of rows can vary that would depend on the user..Initially i ask him about the number of rows...Waiting for your replies.. Regards Ankit Anand From perl4hire at softouch.on.ca Sat Sep 15 09:39:12 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Sat, 15 Sep 2007 09:39:12 -0400 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: Bryan Olson wrote: > Amer Neely wrote: >> This seems to indicate that maybe my host needs to configure Apache to >> run python scripts? But I didn't need to do anything with mine. > > Another possibility: If it works on Windows but not Unix, check > the end-of-line characters. Windows ends each line with the two > character sequence carriage-return + newline, which in Python > is "\r\n". Unix uses newline alone, "\n". > > Most Unixies will choke on a #! line with a carriage return. > The Python interpreter will accept source files with either > end-of-line on either system, but of course you'll not get > that far unless the operating system respects the shebang line. > > Maybe you already checked that. Hmmm...other possiblities... > > Do you have shell access? Can you executing it directly from > the shell? Do you get a Python error, or some other? > > Did you: chmod ugo+rx > > Is Python in /usr/bin? What does "which python" say? > > Generally, most experts seem to prefer: > > #!/usr/bin/env python > > You might try changing the the extension of your script from .py > to .cgi. Windows uses the .py to choose the executable, but Unix > does not care; it used the shebang line. > > Hmmm. These are interesting suggestions. Especially in light of a new wrinkle pointed out by [IV]. That being the script runs fine under my Apache at home with no special modules loaded. I don't have shell access but I can run 'which python' from a Perl script, and I will try the different shebang line you suggested. Thanks for the suggestions. -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From carroll at nospam-tjc.com Sat Sep 15 01:57:18 2007 From: carroll at nospam-tjc.com (Terry Carroll) Date: Fri, 14 Sep 2007 22:57:18 -0700 Subject: (wxPython) wx.ProgressDialog - how to cancel out of? Message-ID: I'm trying to use wx.ProgressBar, and the cancel button is not responding. Here is a simple program that exhibits the problem: ######################################################### import wx import time max = 10 app = wx.PySimpleApp() dlg = wx.ProgressDialog("Progress dialog example", "variables to be shown here", maximum = max, style = wx.PD_CAN_ABORT | wx.PD_CAN_SKIP #| wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_ESTIMATED_TIME | wx.PD_REMAINING_TIME ) keepGoing = True skip = False count = 0 while keepGoing and count < max: count += 1 wx.MilliSleep(1000) #time.sleep(1) newtext = "(before) count: %s, keepGoing: %s, skip: %s " % \ (count, keepGoing, skip) print newtext (keepGoing, skip) = dlg.Update(count, newtext) newtext = "(after) count: %s, keepGoing: %s, skip: %s " % \ (count, keepGoing, skip) print newtext dlg.Destroy() ######################################################### The dialog looks right when this runs, but.... What's right: I get a progress bar; it includes "Skip" and "Cancel" buttons; it shows 10 seconds of progress, and updates once per second with the variables' values on each iteration. What's wrong is that I can't get clicking on the "Skip" or "Cancel" buttons to have any effect. Instead, as soon as the dialog displays, I get an hourglass, and it doesn't matter what I click on. Here's what the print statements display, consistently, regardless of what I try to click or whether I click nothing at all: I:\python>test1.py (before) count: 1, keepGoing: True, skip: False (after) count: 1, keepGoing: True, skip: False (before) count: 2, keepGoing: True, skip: False (after) count: 2, keepGoing: True, skip: True (before) count: 3, keepGoing: True, skip: True (after) count: 3, keepGoing: True, skip: True (before) count: 4, keepGoing: True, skip: True (after) count: 4, keepGoing: True, skip: True (before) count: 5, keepGoing: True, skip: True (after) count: 5, keepGoing: True, skip: True (before) count: 6, keepGoing: True, skip: True (after) count: 6, keepGoing: True, skip: True (before) count: 7, keepGoing: True, skip: True (after) count: 7, keepGoing: True, skip: True (before) count: 8, keepGoing: True, skip: True (after) count: 8, keepGoing: True, skip: True (before) count: 9, keepGoing: True, skip: True (after) count: 9, keepGoing: True, skip: True (before) count: 10, keepGoing: True, skip: True (after) count: 10, keepGoing: True, skip: True Two oddities here: 1) As I read the docs, the keepGoing variable should be set to True, unless I click on "Cancel," in which case it should be set to False (which would end the loop). That doesn't happen. This is really what I'm most concerned here with. 2) The variable "skip: set to False on the first iteration, and then set to True on subsequent iterations? Note that this happens even if no buttons are selected. This is just a weirdness to me, and not my main concern, but I thought I'd mention it in case it's relevant. You can see some variations in the commented-out code that I tried; they did not help. Relevant software and releases: OS: Windows XP Home Edition, Version 2002, SP2 Python: ActivePython 2.5.0.0 wxPython: 2.8.1.1 (msw-unicode) Any help appreciated. From bborcic at gmail.com Mon Sep 3 13:06:26 2007 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 03 Sep 2007 19:06:26 +0200 Subject: SOAP : ZSI error In-Reply-To: <46DBD73F.6060003@gmail.com> References: <46DBD73F.6060003@gmail.com> Message-ID: linuxprog wrote: > hello i need some help with ZSI module > i want to use the web service located here > www.ebob42.com/cgi-bin/NumberToWordsInDutch.exe/soap/IDutch > the wsdl file : > http://www.ebob42.com/cgi-bin/NumberToWordsInDutch.exe/wsdl/IDutch > that web service is very simple , the function NumToStr converts numbers > to dutch words (description > http://www.xmethods.net/ve2/ViewListing.po?key=uuid:01EF9AE1-6DD3-7317-AFA5-05A8A52FCD56) > > i have generated IDutchservice_services with wsdl2py > here is my code : > > import IDutchservice_services > soap = > IDutchservice_services.IDutchbindingSOAP("www.ebob42.com/cgi-bin/NumberToWordsInDutch.exe/soap/IDutch") > ok = IDutchservice_services.NumToStr0Request() > ok.Num=5 > print soap.NumToStr(ok) > > that prints an error RuntimeError: must specify transport or url > startswith https/http > > what's wrong in my script ? thanks Is "startswith https/http" part of the error message ? What would it refer to ? From duncan.booth at invalid.invalid Tue Sep 18 05:15:48 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Sep 2007 09:15:48 GMT Subject: super, apply, or __init__ when subclassing? References: <1190100791.740269.62880@k79g2000hse.googlegroups.com> Message-ID: "exhuma.twn" wrote: > So, knowing that in python there is one thing to do something, these > three different calls must *do* domething different. But what exactly > *is* the difference? > > ------------ Exampel 1: ----------------------------- > > class B(A): > def __init__(self, *args): > A.__init__(self, args) > > ------------ Exampel 2: ----------------------------- > > class B(A): > def __init__(self, *args): > apply( A.__init__, (self,) + args) > > ------------ Exampel 3: ----------------------------- > > class B(A): > def __init__(self, *args): > super(A,self).__init__(*args) Yes, they are all different. The first one calls B's immediate base class but packs all of the arguments together into a single tuple. Probably not what you meant. The second one passes B's positional arguments to its immediate base class without messing them up but uses a deprecated function to do it. You should use "A.__init__(self, *args)" instead unless you are concerned about multiple inheritance. The third one skips over the __init__ method in the immediate base class and calls the __init__ method in whatever class follows A in the MRO instead. Probably not what you meant either. From rcdailey at gmail.com Tue Sep 25 10:45:06 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 25 Sep 2007 09:45:06 -0500 Subject: Confused about 'positive lookbehind assertion' In-Reply-To: <59e9fd3a0709250252ja00fc7cx3927b2b19c31df01@mail.gmail.com> References: <496954360709241938k6baf1009gc7cab215ad16b12f@mail.gmail.com> <59e9fd3a0709250252ja00fc7cx3927b2b19c31df01@mail.gmail.com> Message-ID: <496954360709250745w307275a2sf2b0fd6ef8b5b536@mail.gmail.com> I think I get it... it's really just a way (so it seems) to make characters get added to the found groups as they're matched. Thanks for your help. On 9/25/07, Andrew Durdin wrote: > > On 9/25/07, Robert Dailey wrote: > > Hi, > > > > I've been reading the python documentation on 'positive lookbehind > > assertion' and I don't understand at all how it works. The python docs > give > > the following example: > > > > " (?<=abc)def will find a match in "abcdef", since the lookbehind will > back > > up 3 characters and check if the contained pattern matches." > > > > Can anyone emphasize more on what this RE operation does? Thanks. > > It ensures that the regex will only match following the string in the > lookbehind group, but without capturing that string. > > As the docs say, "(?<=abc)def" will match "abcdef"; but it will not > match "def" (as the "abc" is not there). If it does match, the 0th > group in the match object will be "def". > > In contrast, the regex "abcdef" will also match "abcdef" and not > "def", but the 0th group will be "abcdef". > > The negative lookbehind is the opposite -- e.g. "(? match "def" but not "abcdef". > > Cheers, > > Andrew > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pablo at decode.com.ar Wed Sep 26 14:13:25 2007 From: pablo at decode.com.ar (Pablo Ziliani) Date: Wed, 26 Sep 2007 15:13:25 -0300 Subject: regex with specific list of string In-Reply-To: <1190827835.3397.76.camel@dot.uniqsys.com> References: <1190821357.753909.178210@50g2000hsm.googlegroups.com> <1190827835.3397.76.camel@dot.uniqsys.com> Message-ID: <46FAA145.8050406@decode.com.ar> Carsten Haese wrote: > On Wed, 2007-09-26 at 12:49 -0400, Steve Holden wrote: >> james_027 wrote: >>> hi, >>> >>> how do I regex that could check on any of the value that match any one >>> of these ... 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', >>> 'sep', 'oct', 'nov', 'dec' >>> >>> Thanks >> >>> patr = re.compile('jan|feb|mar|apr|may|jun|jul|aug|sep|nov|oct|dec') >> >>> patr.match("jul") >> <_sre.SRE_Match object at 0x7ff28ad8> >> >>> patr.match("nosuch") > > Unfortunately, that also matches margarine, mayonnaise, and octopus, > just to name a few ;-) (and so does the solution you sent before :) This is fine IMO since the OP didn't specify the opposite. BTW in my previous post I included an example that ensures that the search month matches the beginning of a word. That was based in that maybe he wanted to match e.g. "dec" against "December" (BTW, it should have been r'\b(?:Jan|Feb|...)' instead). To always match a whole word, a trailing \b can be added to the pattern OR (much better) if the month can appear both in its abbreviated and full form, he can use the extensive set as follows (I hope this is clear, excuse my Thunderbird...): >>> pattern = r"\b(?:%s)\b" % '|'.join(calendar.month_name[1:13] + calendar.month_abbr[1:13]) >>> pattern '\\b(?:January|February|March|April|May|June|July|August|September|October|November|December|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\b' >>> target = "Unlike Julia, I like apricots with mayo in august or sep" >>> target 'Unlike Julia, I like apricots with mayo in august or sep' >>> re.findall(pattern, target, re.IGNORECASE) ['august', 'sep'] >>> re.search(pattern, target, re.IGNORECASE) <_sre.SRE_Match object at 0xb7ced640> >>> re.findall(pattern, target, re.IGNORECASE) ['august', 'sep'] Regards, Pablo From super.sgt.pepper at gmail.com Fri Sep 21 20:00:03 2007 From: super.sgt.pepper at gmail.com (Cristian) Date: Sat, 22 Sep 2007 00:00:03 -0000 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> Message-ID: <1190419203.278640.301440@g4g2000hsf.googlegroups.com> On Sep 21, 4:27 pm, "J. Cliff Dyer" wrote: > Cristian wrote: > > On Sep 21, 3:44 pm, Ron Adam wrote: > > >> I think key may be to discuss names and name binding with your friend. How > >> a name is not the object it self, like a variable is in other languages. > >> For example show him how an object can have more than one name. And discus > >> how names can be bound to nearly anything, including classes and functions. > > > I could discuss name binding but it would be great if Python said this > > itself. After all, you can even bind a module with the foo = bar > > syntax by using __import__ function. If function definitions followed > > the same pattern, I think a beginner would subconsciously (maybe even > > consciously) realize that function names are just like everything > > else. Actually, this would be helpful for many people. If you come > > from a language like Java you're used to thinking of attributes and > > methods as living in different namespaces. I think a new syntax will > > encourage seasoned programmers think in a more Pythonic way. > > However, you still have to solve the problem of using a single-line > construct (x = y) with a multi-line definition. That is the essential > difference that def is designed to solve. The __import__ trick works > because import is also a single line construct. > > The only proposal given in this thread is using consistent indentation > within the parentheses, but parentheses are already explicitly designed > to let you ignore the whitespace rules. To suddenly create a situation > in which you have significant whitespace on the right side of an > assignment statement, and *within parentheses* will break too much code, > and make the solution unnecessarily ugly. Multi-line lambdas have been > rejected because of this very problem, so unless you have a clean > solution, I think your proposal falls into the category of "would be > nice, but not in Python." > > Cheers, > Cliff http://www.artima.com/weblogs/viewpost.jsp?thread=147358 You, Guido, and I all agree that anonymous functions in expressions are ugly. There's no argument there. I wouldn't expect any self respecting programmer to do such a thing even if it was available to them (in Python that is). I suppose my question is, taking into account the potential of ugly code that could be created, and the fact that it's technically feasible, would it still be worth adding anonymous functions to explicitly show the first order nature of functions and show that functions are in the same namespace as all other variables? I suppose a solution could be to allow the my_function = function(foo, bar): ... syntax but throw a syntax error if the function isn't being bound to a variable, but that would cause other problems. From that syntax you would assume that it's possible to create an anonymous function wherever a variable is expected. That's not very intuitive either. From ldo at geek-central.gen.new_zealand Sat Sep 22 08:05:35 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 23 Sep 2007 00:05:35 +1200 Subject: xml-rpc timeout References: <2_WdnTQ86eZNY27bnZ2dnUVZ_jCdnZ2d@comcast.com> Message-ID: In message , Steve Holden wrote: > Timeouts shouldn't be a normal feature of TCP communications. On the contrary, they should. How else are you going to detect that the other side has died? From timaranz at gmail.com Mon Sep 24 19:27:54 2007 From: timaranz at gmail.com (timaranz at gmail.com) Date: Mon, 24 Sep 2007 16:27:54 -0700 Subject: execfile and function call In-Reply-To: References: Message-ID: <1190676474.317212.235710@y42g2000hsy.googlegroups.com> I'm not sure why it doesn't work, but a better way would be to use the import statement: import app_applscrip app_applscript.createOptionList(applOptions) Cheers Tim From robert.kern at gmail.com Fri Sep 21 14:05:32 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 21 Sep 2007 13:05:32 -0500 Subject: Odd files; just left behind? In-Reply-To: <46F38FBC.7090903@chamonix.reportlab.co.uk> References: <878x725ts7.fsf@pobox.com> <46F191DF.7000908@jessikat.plus.net> <46f2bd9b$0$20143$426a74cc@news.free.fr> <46F38FBC.7090903@chamonix.reportlab.co.uk> Message-ID: Robin Becker wrote: > Bruno Desthuilliers wrote: >> Robin Becker a ?crit : >>> John J. Lee wrote: >>> >>>> Robin Becker writes: >>>> >>>>> I see a folder .python-eggs in my home directory on one of our servers >>>>> with various .so files >>>>> >>>>> ~/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so >>>>> >>>>> >>>>> are these just left behind from some install process? >>>> Ah, it's about the resource extraction feature of setuptools. It's >>>> possible for zipped eggs to contain resources that have to be >>>> extracted to the filesystem. It puts them in the directory you saw >>>> (or somewhere else -- see the docstring in my other reply). >>>> >>>> http://peak.telecommunity.com/DevCenter/PkgResources#resource-extraction >>>> http://peak.telecommunity.com/DevCenter/setuptools#automatic-resource-extraction >>>> >>> ..... >>> Thanks John, but why not clean up? >>> >> Does it needs to be "cleaned up" ? .so files (shared libs) *need* to be >> extracted from the egg to be usable. Where they are extracted is IIRC >> configurable... > You're right! These files aren't temporary? They're a cache. > It seems strange that the python > files live with their associated lib/site-packages and the .so files are > somewhere entirely different. > > Python 2.3.6 (#1, Jun 7 2007, 10:44:52) > [GCC 3.4.4 [FreeBSD] 20050518] on freebsd6 > Type "help", "copyright", "credits" or "license" for more information. > >>> import MySQLdb > >>> print MySQLdb.__file__ > /myhome/PYTHON/lib/python2.3/site-packages/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg/MySQLdb/__init__.pyc > >>> import _mysql > >>> print _mysql.__file__ > /myhome/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so > >>> > > it would seem simpler to have the .so files inside the site-packages and there's > the question of why this folder has to be obfuscated (name starts with .). Even > if these files are "resources" why should they be assumed to belong to the user? Because they are unpacked at runtime by the user that imported the module. Usually, they won't have write access to site-packages. > I could make the PYTHON folder world usable, but that won't help if I make all > other things in myhome private. Surely code resources belong in the same area as > the code that uses them. Well, you can't import a .so from a zip file. Thus they need to be placed somewhere else. Don't worry about making ~/.python-eggs world readable. When other users import the package, they will have the .so's unpacked, too. -- 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 steve at REMOVE-THIS-cybersource.com.au Tue Sep 4 16:53:06 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 04 Sep 2007 20:53:06 -0000 Subject: parameter list notation References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> <1188882641.899594.212400@22g2000hsm.googlegroups.com> Message-ID: <13drhdial6p58ca@corp.supernews.com> On Mon, 03 Sep 2007 22:10:41 -0700, TheFlyingDutchman wrote: > Well I did a search on "Python variable length arguments" and found a > hit that seems to explain the *fields parameter: > > When you declare an argment to start with '*', it takes the argument > list into an array. No it doesn't. >>> def test(*args): ... import array ... assert type(args) is array.array, "Not an array" ... >>> test(1, 2, 3) Traceback (most recent call last): File "", line 1, in File "", line 3, in test AssertionError: Not an array -- Steven. From david at nospam.spam Sun Sep 2 20:55:31 2007 From: david at nospam.spam (david) Date: Mon, 03 Sep 2007 10:55:31 +1000 Subject: Getting subprocesses to be hidden on Windows In-Reply-To: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> References: <1188246076.131276.292010@r34g2000hsd.googlegroups.com> Message-ID: <13dmms2dm98dq55@corp.supernews.com> geoffbache wrote: > As part of my efforts to write a test tool that copes with GUIs > This is dead easy on UNIX with virtual displays like Xvfb. > Can someone shed any light if it's possible on Windows Configure the virtual display first: http://en.wikipedia.org/wiki/Virtual_desktop Alternatively, run the process in a separate gui. Terminal Server client is one way to do that. [david] From siona at chiark.greenend.org.uk Tue Sep 11 12:46:13 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 Sep 2007 17:46:13 +0100 (BST) Subject: printing list containing unicode string References: <1189432793.383166.156710@d55g2000hsg.googlegroups.com> <1189477580.214510.212420@22g2000hsm.googlegroups.com> Message-ID: Xah Lee wrote: > " It's very wasteful of space. In most texts, the majority of the >code points are less than 127, or less than 255, so a lot of space is >occupied by zero bytes. " > >Not true. In Asia, most chars has unicode number above 255. Considered >globally, *possibly* today there are more computer files in Chinese >than in all latin-alphabet based lang. This doesn't hold water. There are many good reasons for preferring UTF16 over UTF8, but unless you know you're only ever going to be handling scripts from Unicode blocks above Arabic, it's reasonable to assume that UTF8 will be at least as compact. Consider that transcoding a Chinese file from UTF16 to UTF8 will probably increase its size by 50% (the CJK ideograph blocks encode to 3 bytes). While transcoding a document in a Western European langauge the other way can be expected to increase its size by up to 100% (every single- byte character is doubled). You'd have to be talking about double to volume of CJK data before switching from UTF8 to UTF16 becomes even a break-even proposition space-wise. (It's curious to note that the average word length in English is often taken to be 6 letters. Similarly, in UTF8-encoded Chinese the average word length is 6 bytes....) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From torerik81 at gmail.com Mon Sep 3 15:32:04 2007 From: torerik81 at gmail.com (=?ISO-8859-1?Q?Tor_Erik_S=F8nvisen?=) Date: Mon, 3 Sep 2007 21:32:04 +0200 Subject: The reverse of encode('...', 'backslashreplace') Message-ID: <96f089100709031232q74dd6135wb3873ca9915d1504@mail.gmail.com> Hi, How can I transform b so that the assertion holds? I.e., how can I reverse the backslash-replaced encoding, while retaining the str-type? >>> a = u'?' >>> b = a.encode('ascii', 'backslashreplace') >>> b '\\xe6' >>> assert isinstance(b, str) and b == '?' Traceback (most recent call last): File "", line 1, in assert isinstance(b, str) and b == '?' AssertionError Regards, tores From wizzardx at gmail.com Tue Sep 11 17:09:34 2007 From: wizzardx at gmail.com (David) Date: Tue, 11 Sep 2007 23:09:34 +0200 Subject: Python Database Apps In-Reply-To: <1189536987.259907.68650@e34g2000pro.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> <1189536987.259907.68650@e34g2000pro.googlegroups.com> Message-ID: <18c1e6480709111409lf45217bg1a041ce40d82d933@mail.gmail.com> > It would help to get a feel of what is the most popular combination > for people to develop their apps. It's gonna be a desktop app. The > database engine is going to be the critical component. I like sqlite > so that I don't need a database server on the client side. It would > help though if there is a way to sync between multiple clients to a > central server database. That's the tough part. To give you a better > idea of what i'm trying to do, I am trying to write an app where > multiple technicians have an issue tracker that is available both > offline and online. I was looking to use sqlite as the local side > that would sync new and updated issues to a central server when > online. Any technician may work on any issue. Generally they will > not be working on the same issue at the same time. The technicians > are geographically diverse (anywhere in the southeast US, not in an > office.) If you have an offline mode then the most important thing to work out is how to handle conflicts in your data synchronization. You need a clear logic policy for this, and some means of conflict resolution. Also all parties need to be consistent and not go out of sync too badly. Maybe avoid conflicts altogether. eg define exactly what types of updates can take place offline (record insertions only). Or a policy where deletes+updates can only be made offline by the technician that "owns" the issue/has locked it. This approach has a few issues also. If the database is relatively small and your data is simple then you could get away with simple table record comparisons to do syncing (only works properly for inserts, and you need 'natural keys' for comparison - updates and deletes are more complicated). Another (really complicated) way is to use a series of log events, which your app can commit locally or to the server, and merge incoming events from the server. This is similar in principle to a SCM like CVS, subversion, git, bazaar, etc. SVK is probably the closest to your model (centralised scm, with offline commit mode). This gets complicated very quickly. From gigs at hi.t-com.hr Thu Sep 13 09:59:07 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 13 Sep 2007 15:59:07 +0200 Subject: recursion Message-ID: Can someone explain me this >>> def f(l): if l == []: return [] else: return f(l[1:]) + l[:1] # <= cant figure this, how is all sum at the end? thanks! From carsten at uniqsys.com Mon Sep 24 08:31:53 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Sep 2007 08:31:53 -0400 Subject: python variable assignement In-Reply-To: <1190635944.655293.38290@y42g2000hsy.googlegroups.com> References: <1190628822.472242.272900@19g2000hsx.googlegroups.com> <1190635944.655293.38290@y42g2000hsy.googlegroups.com> Message-ID: <1190637113.5618.9.camel@dot.uniqsys.com> On Mon, 2007-09-24 at 12:12 +0000, mihai wrote: > [...] > id = add(record) > [...] Not that this causes your problem, but I'd still like to point out that 'id' is the name of a built-in function. Shadowing built-in names can lead to surprising behavior. > Is there a way to see if the names points to the same variables or > that there are different variables with the same values? Yes. "==" tests whether two objects are equal, whereas "is" tests whether two objects are actually the same object. Examples: Two different list objects with equal contents: >>> a = [1,2,3] >>> b = [1,2,3] >>> a==b True >>> a is b False Two names for the same list object: >>> a = [1,2,3] >>> b = a >>> a==b True >>> a is b True Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From iclark at mail.ewu.edu Mon Sep 17 11:55:42 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Mon, 17 Sep 2007 08:55:42 -0700 Subject: curses: x, y positioning In-Reply-To: <1190035292.415363.22320@50g2000hsm.googlegroups.com> References: <1189891633.622313.81850@r29g2000hsg.googlegroups.com> <1190035292.415363.22320@50g2000hsm.googlegroups.com> Message-ID: 7stud wrote: > However, now I am having a problem trying to set the color of the text > that is output: import curses def example(screen): if curses.has_colors(): curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) screen.addstr(1, 1, 'Hello', curses.color_pair(1)) screen.addstr(1, 7, 'World', curses.color_pair(2)) screen.addstr(1, 12, '!!!', curses.color_pair(3) + curses.A_BOLD) else: screen.addstr(1, 1, 'You don\'t have colors enabled. :(') screen.addstr(3, 0, '') screen.refresh() screen.getch() if __name__ == '__main__': curses.wrapper(example) Ian From mccredie at gmail.com Thu Sep 20 18:36:45 2007 From: mccredie at gmail.com (Matt McCredie) Date: Thu, 20 Sep 2007 15:36:45 -0700 Subject: re question In-Reply-To: <46F27AB9.8060007@bigfoot.com> References: <46F27AB9.8060007@bigfoot.com> Message-ID: <9e95df10709201536w46b75a00gb42817b3777ff12d@mail.gmail.com> On 9/20/07, Ricardo Ar?oz wrote: > Dan Bar Dov wrote: > > I'm trying to construct a regular expression to match valid IP address, > > without leading zeroes (i.e > > 1.2.3.4 , 254.10.0.0 , but not > > 324.1.1.1, nor 010.10.10.1 ) > > > > This is what I come up with, and it does not work. > > > > r'(^[12]?\d{0,2}\.){3,3}[12]?\d{0,2}' > > > > What am I doing wrong? > > Any common knowledge IP matching RE? > > > > Thanks, > > Dan > > > > r'^[12]\d?\d?.\d{1,3}.\d{1,3}.\d{1,3}$' so 299.999.999.999 is a valid IP and 34.0.0.1 isn't? Also, the "."s need to be escaped. Otherwise they match ANY character. Matt From rcdailey at gmail.com Mon Sep 24 16:36:05 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 24 Sep 2007 15:36:05 -0500 Subject: Python script to optimize XML text Message-ID: <496954360709241336i43173947sda5245c2d7477ecb@mail.gmail.com> Hi, I'm currently seeking a python script that provides a way of optimizing out useless characters in an XML document to provide the optimal size for the file. For example, assume the following XML script: By running this through an XML optimizer, the file would appear as: Note that the following were changed: - All comments were stripped from the XML - All spaces, tabs, carriage returns, and other forms of unimportant whitespace are removed - Elements that contain no text or children that are in the form of use the short-hand method for ending an element body: Anyone know of a tool or python script that can perform optimizations like explained above? I realize I could probably do this with regular expressions in python, however I was hoping someone already did this work. -------------- next part -------------- An HTML attachment was scrubbed... URL: From basilisk96 at gmail.com Fri Sep 7 07:06:18 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Fri, 07 Sep 2007 11:06:18 -0000 Subject: interesting puzzle......try this you will be rewarded... In-Reply-To: References: Message-ID: <1189163178.673854.34580@w3g2000hsg.googlegroups.com> On Sep 7, 5:08 am, "Andreas Tawn" wrote: > > Maybe http://www.pythonchallenge.com/? That's the one, thanks! --- From mcknight0219 at gmail.com Sun Sep 16 11:07:12 2007 From: mcknight0219 at gmail.com (Jimmy) Date: Sun, 16 Sep 2007 08:07:12 -0700 Subject: (curses) issue about inch() Message-ID: <1189955232.216664.167840@19g2000hsx.googlegroups.com> hi, all I attempt to use the function inch() to get the character at the current position, and compare it with a particular character like : if screen.inch(x,y) == 'F' but this method doesn't seem work, can anyone tell me the reason and how to corrent it thanks From cokofreedom at gmail.com Thu Sep 20 08:37:05 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 20 Sep 2007 12:37:05 -0000 Subject: writing to lists within a dictionary Message-ID: <1190291825.337829.34670@19g2000hsx.googlegroups.com> I am trying to write a basic anagram system, that takes a text file line by line and by sorting the string into its alphabetical form compares it to keys within a dictionary. If it matches a key I want to add it (in its unordered form) to a list for that key. So far this is what I have import sys, string, fileinput # takes an item (string) and converts it to its basic alphabetical form def getChar( item ): item_chars = [] for i in range(len(item)): item_chars.append(item[i]) item_chars.sort() return string.join(item_chars, "") anagramDict = {} for line in fileinput.input("fakelist.txt"): myLine = line.replace("\n", "") #remove the carriage returns myString = getChar(myLine) #get the alphabetical form for k in anagramDict.items(): #iterator through the keys in the dictionary if k[0] == myString: #if the key matches our string anagramDict[k].append([myLine])#append that k and add the value this line else: anagramDict[myString] = [myLine] #else there is no key the same so make a new one print anagramDict From simon at brunningonline.net Wed Sep 5 08:52:00 2007 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 5 Sep 2007 13:52:00 +0100 Subject: Multi Heritage with slots In-Reply-To: <1188994956.570845.269250@w3g2000hsg.googlegroups.com> References: <1188982916.071976.160170@g4g2000hsf.googlegroups.com> <1188994956.570845.269250@w3g2000hsg.googlegroups.com> Message-ID: <8c7f10c60709050552p77bce48cx86d5293bd65fcd0@mail.gmail.com> On 9/5/07, Alexandre Badez wrote: > I use __slots__ not for memory optimization nor doing java. > I use __slots__ because my class are used by other lib, and in the > past, some of them misspell some attributes and involved a very > annoying comportment of the global application. > So the objective is only to prevent unwanted dynamism (but not in all > the application, just some class). Using slots to prevent the creation of new properties is what Eric *means* by "doing java". You're trying to write Java style code in Python, and it's not going to be pretty. Slots are not intended for this purpose, and they aren't very good for it. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From zentraders at gmail.com Wed Sep 12 18:07:41 2007 From: zentraders at gmail.com (Zentrader) Date: Wed, 12 Sep 2007 22:07:41 -0000 Subject: File Parsing Question In-Reply-To: References: Message-ID: <1189634861.631219.143310@57g2000hsv.googlegroups.com> I'm assuming you know that python has a file.seek(), but you have to know the number of bytes you want to move from the beginning of the file or from the current location. You could save the length of the previous record, and use file seek to backup and then move forward, but it is simpler to save the previous rec or use readlines() if the file will fit into a reasonable amount of memory. From inmmike at gmail.com Tue Sep 11 21:26:47 2007 From: inmmike at gmail.com (inmmike at gmail.com) Date: Tue, 11 Sep 2007 18:26:47 -0700 Subject: "Variable variable name" or "variable lvalue" In-Reply-To: References: <1187199722.618893.281170@r29g2000hsg.googlegroups.com> <1187541583.607550.107230@57g2000hsv.googlegroups.com> Message-ID: <1189560407.455008.151080@r34g2000hsd.googlegroups.com> On Aug 19, 1:10 pm, Gary Herron wrote: > inmm... at gmail.com wrote: > > On Aug 15, 1:42 pm, mfglinux wrote: > > >> Hello to everybody > > >> I would like to know how to declare in python a "variable name" that > >> it is in turn a variable > >> In bash shell I would wrote sthg like: > > >> for x in `seq 1 3` > >> do > >> M$i=Material(x) #Material is a python class > >> done > > >> Why I need this? Cause I have a python module that obliges me to build > >> a variable called Period, which should have a variable name of > >> summands (depends on the value of x) > > >> #Let's say x=3, then Period definition is > >> Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a > >> python class > > >> I dont know how to automatize last piece of code for any x > > >> thank you > > >> Marcos > > > Regardless of whether or not this is a "best practice" sometimes it is > > necessary. For example, I am looping through a dictionary to set some > > class properties. Anyway, here is what I finally came up with: > > > exec "self.%s = '%s'" % (item, plist[item]) > > Yuck! Not at all necessary. Use setattr instead: > > setattr(self, item, plist[item]) > > That's much cleaner then an exec or eval. You may also find getattr and > hasattr useful. > > Gary Herron > > > A more simple example for setting a variable outside of a class... > > > exec '%s = '%s'" % ('variableName', 'variable value') > > > Cheers! > > Mike Thanks! I'm still getting used to Python's nifty features. From david at asdf.asdf Sun Sep 9 21:42:25 2007 From: david at asdf.asdf (bambam) Date: Mon, 10 Sep 2007 11:42:25 +1000 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com><13dv4uqqb806ff0@corp.supernews.com> <13dvvgk96amhhec@corp.supernews.com><13e1cbetihma1d6@corp.supernews.com> Message-ID: <13e9880q8m0mse9@corp.supernews.com> I'm testing a series of scripts. The scripts are testing a series of hardware devices. The scripts are a sequence of device commands. The scripts have sequence numbers. I am adding exception handling to the to the 'inner platform' that executes sequences. I am doing this because testing of error cases has demonstrated that the 'inner platform' is fragile. http://worsethanfailure.com/Articles/The_Inner-Platform_Effect.aspx on the other hand: http://www.amazon.com/gp/cdp/member-reviews/A2M9XZ2UD8ZM40?ie=UTF8&display=public&sort_by=MostRecentReview&page=5 and http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/207645 In any case, the hardware test instruments are not programmable in python, and most of them do not have loop constructs in the platform language. I'm not sure how you are reading these messages. Can you see the thread history? Steve. "Steven D'Aprano" wrote in message news:pan.2007.09.07.03.42.06 at REMOVE.THIS.cybersource.com.au... > On Fri, 07 Sep 2007 12:03:26 +1000, bambam wrote: > >> Hi Steven. >> >> Looking at your code, why are you naming the value __all__? It looks >> like a built-in variable? > > When you say: > > from module import * > > Python looks in the module for a list of names called "__all__", and > imports only the names in that list. It is recommended that your modules > take advantage of that feature. I'm just using the same name. > > >> Unless there is an automatic way to correctly get the function list, I >> will probably be better off giving the lines sequence numbers, and >> generating the function list from that. > > I don't understand what you mean by "giving the lines sequence numbers". > Where do they come from? How do you go from sequence numbers to functions? > > As far as I am concerned, the right behavior is for the module containing > the functions to define which functions need to be tested. Since modules > aren't actually intelligent, that means some person needs to list the > functions. Why list the function NAME when you can list the function > itself? > From http Fri Sep 14 21:08:00 2007 From: http (Paul Rubin) Date: 14 Sep 2007 18:08:00 -0700 Subject: How to avoid overflow errors References: <13em8vnr527rq20@corp.supernews.com> Message-ID: <7xmyvoag7j.fsf@ruckus.brouhaha.com> "Eduardo O. Padoan" writes: > Not totally unrelated, but in Py3k, as it seems, overflows are really > things of the past: > > > Python 3.0a1 (py3k:58061, Sep 9 2007, 13:18:37) > [GCC 4.1.3 20070831 (prerelease) (Ubuntu 4.1.2-16ubuntu1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> class MyInt(int): > ... pass > ... > >>> import sys > >>> MyInt(sys.maxint) > 2147483647 > >>> MyInt(sys.maxint+1) > 2147483648 I'd be interested in knowing what happens in 3.0a1 with a = itertools.count(sys.maxint) print a.next() print a.next() From rodney.maxwell at gmail.com Thu Sep 13 12:02:25 2007 From: rodney.maxwell at gmail.com (Rodney Maxwell) Date: Thu, 13 Sep 2007 16:02:25 -0000 Subject: Extended slicing and Ellipsis - where are they used? Message-ID: <1189699345.436400.233460@g4g2000hsf.googlegroups.com> The following are apparently legal Python syntactically: L[1:3, 8:10] L[1, ..., 5:-2] But they don't seem to work on lists: >>> l = [0,1,2,3] >>> l[0:2,3] Traceback (most recent call last): File "", line 1, in TypeError: list indices must be integers >>> l[...] Traceback (most recent call last): File "", line 1, in TypeError: list indices must be integers So where is this extended slicing used? -- Rodney From paddy3118 at googlemail.com Wed Sep 19 18:06:48 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 19 Sep 2007 22:06:48 -0000 Subject: Sets in Python In-Reply-To: <1190235483.412972.81280@v23g2000prn.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> Message-ID: <1190239608.835359.51150@22g2000hsm.googlegroups.com> On Sep 19, 9:58 pm, Karthik Gurusamy wrote: > > Since we know hashing is used, all that is needed is, a well-defined > way to construct a hash out of a mutable. "Given a sequence, how to > get a hash" is the problem. If later the given sequence is different, > that's not the dict's problem. > Oh it is possible to construct a hash from a mutable. What is difficult is creating the same hash when the mutable mutates. Or indeed working out what it means when a hash key mutates and you access the dictionary. Ignoring this gives the programmer a big problem hence the limitation. I don't think you have a better solution. - Paddy. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 19 07:58:45 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 13:58:45 +0200 Subject: lambda-funcs problem In-Reply-To: <1190201984.062329.182460@k79g2000hse.googlegroups.com> References: <1190201984.062329.182460@k79g2000hse.googlegroups.com> Message-ID: <46f10ee8$0$22308$426a34cc@news.free.fr> dmitrey.kroshko at scipy.org a ?crit : > hi all, > I need to create a Python list of lambda-funcs that are dependent on > the number of the ones, for example > > F = [] > for i in xrange(N): > F.append(lambda x: x + i) > > however, the example don't work - since i in end is N-1 it yields x+ > (N-1) for any func. > > So what's the best way to make it valid? It's a FAQ. The answer is (using list-comp instead of a for loop): funcs = [lambda x, i=i : x + i for i in xrange(n)] From carsten at uniqsys.com Sat Sep 29 11:43:04 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 29 Sep 2007 11:43:04 -0400 Subject: Program inefficiency? In-Reply-To: <1191079347.192272.240540@22g2000hsm.googlegroups.com> References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> Message-ID: <1191080584.3253.6.camel@localhost.localdomain> On Sat, 2007-09-29 at 15:22 +0000, hall.jeff at gmail.com wrote: > [...] > def replacecycle(starttext): > p1= re.compile('(href=|HREF=)+(.*)(#)+(.*)( )+(.*)(">)+') > p2= re.compile('(name=")+(.*)( )+(.*)(">)+') > p3= re.compile('(href=|HREF=)+(.*)(#)+(.*)(\')+(.*)(">)+') > p4= re.compile('(name=")+(.*)(\')+(.*)(">)+') > p5= re.compile('(href=|HREF=)+(.*)(#)+(.*)(-)+(.*)(">)+') > p6= re.compile('(name=")+(.*)(-)+(.*)(">)+') > p7= re.compile('(href=|HREF=)+(.*)(#)+(.*)(<)+(.*)(">)+') > p8= re.compile('(name=")+(.*)(<)+(.*)(">)+') > p7= re.compile('(href=|HREF=")+(.*)(#)+(.*)(:)+(.*)(">)+') > p8= re.compile('(name=")+(.*)(:)+(.*)(">)+') > p9= re.compile('(href=|HREF=")+(.*)(#)+(.*)(\?)+(.*)(">)+') > p10= re.compile('(name=")+(.*)(\?)+(.*)(">)+') > p100= re.compile('(a name=)+(.*)(-)+(.*)(>)+') > [...] One obvious opportunity for optimization is to compile those re's only once at the beginning of the program instead of every time replacecycle() is called (which is inexplicably called 13 times for each file). -- Carsten Haese http://informixdb.sourceforge.net From ruoyu0088 at gmail.com Tue Sep 25 22:54:18 2007 From: ruoyu0088 at gmail.com (HYRY) Date: Tue, 25 Sep 2007 19:54:18 -0700 Subject: the address of list.append and list.append.__doc__ Message-ID: <1190775258.351819.24930@22g2000hsm.googlegroups.com> I have the following questions, I am using Python 2.4.2 >>> a = [1,2,3] >>> id(a.append) 19167152 #1 >>> id(list.append) 11306608 #1 1. the address of a.append and list.append is different, can I get the address of list.append from a.append? >>> id(a.append.__doc__) 19162720 >>> id(a.append.__doc__) 19162336 >>> id(a.append.__doc__) 19162592 >>> id(a.append.__doc__) 19162720 >>> id(list.append.__doc__) 19162336 >>> id(list.append.__doc__) 19162720 >>> id(list.append.__doc__) 19162592 >>> id(list.append.__doc__) 19162336 2. why the address of a.append.__doc__ and list.append.__doc__ change, this means __doc__ is not a normal string, but something return a string. From khemkaamit at gmail.com Thu Sep 6 01:40:57 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 6 Sep 2007 11:10:57 +0530 Subject: Using wild character In-Reply-To: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> Message-ID: <1360b7230709052240v2da7ce68p5aae956bb22b8a41@mail.gmail.com> On 9/6/07, Sreeraj wrote: > hi, > > I am a beginner in Python. I wish to know how can i filter a list of > strings using wild characters.ie > Lets say i have list countries = > ["india","africa","atlanta","artica","nigeria"]. I need only the list > of string starting with 'a'. There are a few ways of doing so. For some simple operations there are functions on the strings, If you want some more complex "filtering" then have a look at Python's regular expression module "re". example: >>> l = ["india","africa","atlanta","artica","nigeria"] >>> al = [c for c in l if c.startswith('a')] # this is a list comprehension >>> al ['africa', 'atlanta', 'artica'] To know more about list comprehensions, have a look at: http://docs.python.org/tut/node7.html#SECTION007140000000000000000 Methods on strings: http://docs.python.org/lib/string-methods.html#string-methods Btw, not all of names in your list are countries ! Cheers, -- ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in From tjreedy at udel.edu Tue Sep 18 22:56:41 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Sep 2007 22:56:41 -0400 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> Message-ID: "TheFlyingDutchman" wrote in message news:1190164166.378500.155990 at o80g2000hse.googlegroups.com... | On Sep 2, 5:38 pm, "Eduardo O. Padoan" | wrote: | > > No.http://www.artima.com/weblogs/viewpost.jsp?thread=211430 | > | > Ops, I meant:http://www.artima.com/forums/threaded.jsp?forum=106&thread=211200 | > | > --http://www.advogato.org/person/eopadoan/ | > Bookmarks:http://del.icio.us/edcrypt | | "No. We're not changing the CPython implementation much. Getting rid | of the GIL would be a massive rewrite of the interpreter because all | the internal data structures (and the reference counting operations) | would have to be made thread-safe. This was tried once before (in the | late '90s by Greg Stein) and the resulting interpreter ran twice as | slow." Since Guido wrote that, there have been put forth more ideas and interest and promises of efforts to remove or revise the GIL or do other things to make using multiple cores easier. (The later being the point of the concern over GIL.) | How much faster/slower would Greg Stein's code be on today's | processors versus CPython running on the processors of the late | 1990's? Perhaps a bit faster, though processor speeds have not increased so much the last couple of years. |And if you decide to answer, please add a true/false response | to this statement - "CPython in the late 1990's ran too slow". False by late 1990's standards, True by today's standards ;-). Most people are not currently bothered by the GIL and would not want its speed halved. In any case, any of the anti-GIL people are free to update Stein's code and distribute a GIl-less version of CPython. (Or to use Jython or IronPython.) tjr From UrsusMaximus at gmail.com Mon Sep 3 18:33:52 2007 From: UrsusMaximus at gmail.com (UrsusMaximus at gmail.com) Date: Mon, 03 Sep 2007 22:33:52 -0000 Subject: Python411 Podcast: Python for Mobile Interfaces Message-ID: <1188858832.655778.24890@g4g2000hsf.googlegroups.com> Python for Mobile Interfaces is a clarion call for Pythonistas to pioneer the future of alternative user interfaces for mobile phones, PDA's, and wearable computers, including voice recognition, gesture recognition, and wearable computing. www.awaretek.com From http Mon Sep 3 12:52:11 2007 From: http (Paul Rubin) Date: 03 Sep 2007 09:52:11 -0700 Subject: Does shuffle() produce uniform result ? References: Message-ID: <7xejhfbsjo.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > If I understand correctly that you are using urandom as a random > generator I wouldn't trust too much on this performance. Urandom > uses the systemwide entropy-pool. If other programs need this pool > too, your performance can drop spectaculary. No the idea is that once there's enough entropy in the pool to make one encryption key (say 128 bits), the output of /dev/urandom is computationally indistinguishable from random output no matter how much data you read from it. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 20 07:46:29 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Sep 2007 11:46:29 -0000 Subject: Sets in Python References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <13f3m15igkstq2e@corp.supernews.com> <1190260923.243865.312190@z24g2000prh.googlegroups.com> Message-ID: <13f4nclh902f78f@corp.supernews.com> On Thu, 20 Sep 2007 04:02:03 +0000, Karthik Gurusamy wrote: > On Sep 19, 7:17 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 19 Sep 2007 20:58:03 +0000, Karthik Gurusamy wrote: >> > While it's easy to explain the behavior, I think the decision to dis- >> > allow mutable items as keys is a bit arbitrary. There is no need for >> > dict to recompute hash >> >> What??? >> >> Of course it does. How else can it look up the key? Because it >> (somehow) just recognizes that it has seen the key before? How? By >> magic? > > You answered it yourself later. For a mapping service, hash is just one > way to do things. What you need is for each item in the collection, a > unique key. And does the mapping get access to that unique key (the key's key)? It can't keep a mapping of object:key, because if it could do that, it wouldn't need the key, it could just keep object:payload. Since the mapping can't know the key's key, it has to ask the key, and that's what the __hash__ method does. > How you go from the key to the value is not something a programmer needs > to know. You are correct. All you need to know is that in Python, you can't use lists and sets as keys directly. You only need to know about the details of the way dicts look up keys if you are writing your own class, and you aren't happy with Python's default hash for instance objects. It isn't a common task. > Your mind is set on thinking on hash alone and hence you don't see > beyond it. No, these issues exist regardless of the implementation of the mapping. Whether you use a hash table or a binary tree of some sort, or a linear linked list, or a database, or folders in a filing cabinet. The behaviour of mutable objects in a mapping is always problematic, regardless of the mapping implementation. >> > (first of all, a user doesn't even need to know if underneath >> > 'hashing' is used -- the service is just a mapping between one item >> > to another item). >> >> The user doesn't need to know the mechanism, but the dict does. Dicts >> are implemented as hash tables. I suppose they could be implemented as >> something else (what? linear lists? some sort of tree?) but the same >> considerations must be made: > > Oh yes. If the keys are all integers (or any set of items that can be > ordered), why not an avl. It has guaranteed O(log N) while a hash in > worst case is O(N). But both the best and average cases are O(1), which beats AVL trees by a lot. Since dicts are used for Python's internals, they are HIGHLY optimized and VERY fast. Their O(1) will beat the O(log N) of AVL trees easily. Hash tables can also use keys even if they can't be ordered: {1+2j: None} > Why you want to tie yourself to the drawbacks of one > datastructure? Understand your goal is not to provide a hash; but to > provide a mapping service. No, the goal of a good language designer is to provide the fastest, most lightweight, simplest, most flexible mapping as a built-in. Any old slow, heavyweight, complicated, inflexible mapping will not do the job. That goal is best provided by a hash table. If people want additional mappings as well, they can be added as libraries. If those libraries are very useful, they can be added to the standard library. If they are HUGELY useful, they will become built-ins. AVL trees are not as flexible or fast as hash tables, and even if they were, you would *still* need to resolve the difficulties that occur if the keys mutate. >> the dict must be able to find keys it has >> seen before. How is the dict supposed to recognise the key if the key >> has changed? >> >> > Since we know hashing is used, all that is needed is, a well-defined >> > way to construct a hash out of a mutable. "Given a sequence, how to >> > get a hash" is the problem. >> >> Nonsense. That's not the problem. The problem is how to get exactly the >> same hash when the sequence has changed. > > Yes, if you keep thinking hash is the only tool you got. Fine, let me re-word it in terms of an AVL. Suppose you have two lists in an AVL: L1 = [1, 2, 3] L2 = [4, 5, 6] M = avl((L1, True), (L2, False)) The tree M (for mapping) has L1 at the top of the tree, and L2 as the right node. But now, EVERY time ANY mutable object changes, Python has to check whether it is a key in EVERY avl, and if so, re-built the tree. Otherwise the tree can become corrupt because the AVL invariants are no longer true. (Consider what happens if we say L1[0] = 999. Now L1 > L2. If you don't reorder the avl, M[L2] cannot be reached except by an exhaustive search of every node. That means it is no longer an AVL tree, just an inordered tree. Might as well save memory and use a linear linked list.) Needless to say, this will slow down Python just a tad. Look, you can go back to the archives of 1993 when this was first discussed. Nothing has changed since then. Mutable keys are still problematic, regardless of the implementation, and the simplest solution is to simply prohibit them. http://www.python.org/search/hypermail/python-1993/0044.html If you want to use a mutable object as a key, by object identity rather than value, then the easy way is to wrap it in an instance: class Wrapper: # don't even need new-style classes pass # or even an __init__ key = Wrapper() key.payload = [1, 2, 3] D = {key: "value"} But of course you can't look up the dict by value, only by identity. But that's what you wanted. Another way is to use this class: class HashableList(list): def __hash__(self): return hash(tuple(self)) Have fun, and remember us when you're debugging your code, because you'll be doing a lot of it. -- Steven. From __peter__ at web.de Tue Sep 25 03:53:22 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Sep 2007 09:53:22 +0200 Subject: strange behavious of the logging module? References: <1190643051.084144.230220@o80g2000hse.googlegroups.com> <1190672978.233964.232900@g4g2000hsf.googlegroups.com> Message-ID: Vinay Sajip wrote: > This is a known bug, and not specifically related to logging, though > it sometimes manifests itself via logging: > > http://bugs.python.org/issue1180193 Yup, thanks for looking into it. Peter From nospam at nospam.com Fri Sep 21 23:19:59 2007 From: nospam at nospam.com (Mark T) Date: Fri, 21 Sep 2007 20:19:59 -0700 Subject: elementtree question References: Message-ID: "Gabriel Genellina" wrote in message news:mailman.898.1190412966.2658.python-list at python.org... > En Fri, 21 Sep 2007 11:49:53 -0300, Tim Arnold > escribi?: > >> Hi, I'm using elementtree and elementtidy to work with some HTML files. >> For >> some of these files I need to enclose the body content in a new div tag, >> like this: >> >>
>> original contents... >>
>> >> >> I figure there must be a way to do it by creating a 'div' SubElement to >> the >> 'body' tag and somehow copying the rest of the tree under that >> SubElement, >> but it's beyond my comprehension. > > import xml.etree.ElementTree as ET > source = """Test > original contents... 2&3 some text >

Another paragraph

> """ > tree = ET.XML(source) > body = tree.find("body") > newdiv = ET.Element('div', {'class':'remapped'}) > newdiv.append(body) > bodyidx = tree.getchildren().index(body) > tree[bodyidx]=newdiv > ET.dump(tree) > > -- > Gabriel Genellina > The above wraps the body element, not the contents of the body element. I'm no ElementTree expert, but this seems to work: import xml.etree.ElementTree as ET source = """Test original contents... 2&3 some text

Another paragraph

""" tree = ET.XML(source) body = tree.find("body") newdiv = ET.Element('div', {'class':'remapped'}) for e in body.getchildren(): newdiv.append(e) newdiv.text = body.text newdiv.tail = body.tail body.clear() body.append(newdiv) ET.dump(tree) Result: Test
original contents... 2&3 some text

Another paragraph

-Mark From jesse.k.rosenthal at gmail.com Mon Sep 10 20:29:35 2007 From: jesse.k.rosenthal at gmail.com (jesse.k.rosenthal at gmail.com) Date: Mon, 10 Sep 2007 17:29:35 -0700 Subject: mailbox module, Maildir, and flags Message-ID: <1189470575.927590.122140@o80g2000hse.googlegroups.com> Dear all, I'm trying to figure out if mailbox will let me get the flags of a Maildir message without running get_message on it, and reading the whole message. It seems like it should work by doing this: >>> import mailbox >>> mybox = mailbox.Maildir('~/Maildir/', mailbox.MaildirMessage) >>> myfolder = mybox.get_folder('School') >>> len(myfolder) 2102 >>> msg = myfolder.next() But then,when I try to get_flags on msg, I get nothing >>> msg.get_flags() '' Instead, I have to ener >>> msg=myfolder.get_message(key) which reads the whole message. Then the flags show up (RS or whatever). Given that there's 2102 messages in the folder, and some of them have attachments, I'd rather run get_message on all of them. To explain my motivation: I'm writing a curses email client as a hobby. I started out with IMAP, and implemented a simple caching behaviour, using a pickled cache. When it logs in to the IMAP server, it checks only the uids and flags on the server, compares those to the ones in the cache, and from that can figure out what has been added, deleted, or changed. From that, it can figure out what headers to download. Saves a *lot* of time at startup. I'd like to implement something like this for Maildir. Figure out which msgs it needs to get a new Message instance for, and only those. The rest are in the cache. So after the first time, starting up on a large maildir folder will be pretty quick. Following the same logic, I just need the unique names and the flags. Now, I know the flags are in the name, but I can't find anyway in the mailbox module to get them. So, should I just run some text parsing on the filenames, using os.listdir? Given: '1110326951.M818715P9617V0000000000000307I001A45A4_1401.belacqua,S=960:2,RS' it's easy enough to apply string.split(":2,"). But then I have to deal with all the nastiness of the maildir standard. This is probably what I'll end up doing, but I was wondering if the mailbox module had a way to do it. One other question. Given a mailbox.Maildir folder like the one above, is there a way to run through it and just get the headers? Basically, the opposite of get_payload? I know I can scew around with msg.keys(), but is there something like for msg in folder: hdr = msg.get_header() ? Thanks for all your help. Sorry if this was unclear or long-winded. Best, Jesse From __peter__ at web.de Tue Sep 25 08:24:33 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Sep 2007 14:24:33 +0200 Subject: Raw string printing References: <1190722082.406690.222540@57g2000hsv.googlegroups.com> Message-ID: Alexandre Badez wrote: > I would like to do something like: > > s = r"a\tb\n" > print unraw(s) # <= this is the "magic" function I'm searching for > # result with > a b > n > > Does any of you know how to do it properly ? >>> print r"a\tb\nx".decode("string-escape") a b x Peter From horpner at yahoo.com Mon Sep 10 13:44:02 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 10 Sep 2007 17:44:02 GMT Subject: Checking if elements are empty References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> <46e2013a$0$7687$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On 2007-09-10, Chris Mellon wrote: > On 9/10/07, Neil Cerutti wrote: >> Agreed; but I prefer 'if y[0] == ""', absent more context and >> better names. > > Probably should use u"" if you're going to take that route, as > this will fail spuriously if y[0] contains a unicode string > that can't be implicitly converted to ascii. Personally, I > prefer the boolean check and I'll let operations fail elsewhere > if there's a type mismatch. I have a quibble not with the functionality of the boolean check, but with its expressiveness. if y[0] == "" expresses more, i.e., that I expect y[0] to contain a Python byte string. -- Neil Cerutti From byte8bits at gmail.com Fri Sep 21 15:32:03 2007 From: byte8bits at gmail.com (byte8bits at gmail.com) Date: Fri, 21 Sep 2007 19:32:03 -0000 Subject: RE Help In-Reply-To: References: <1190399985.324448.242610@d55g2000hsg.googlegroups.com> <1190401551.706792.178450@22g2000hsm.googlegroups.com> Message-ID: <1190403123.841267.7000@r29g2000hsg.googlegroups.com> > You'll want to use a non-greedy match: > x = re.compile(r"START(.*?)END", re.DOTALL) > Otherwise the . will match END as well. On Sep 21, 3:23 pm, Steve Holden wrote: > Only if there's a later END in the string, in which case the user's > requirements will determine whether greedy matching is appropriate. > > regards > Steve There will be lots of START END combinations in the data. This is more accurate: sfgdfg*START*dfhdgh*END*dfdgh*START*dfhfdgh*END*dfgsdh*START*sdfhfdhj*END*fdghfdj The RE should extract the data between each couples of START and END. Thanks! From yalum at earthlink.net Mon Sep 3 17:41:27 2007 From: yalum at earthlink.net (Fit E. Cal) Date: Mon, 03 Sep 2007 21:41:27 -0000 Subject: Let's Unite Against Jews and Mongrels! In-Reply-To: <1188849476.067121.119110@r34g2000hsd.googlegroups.com> References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> <1188300284.507909.126770@57g2000hsv.googlegroups.com> <46D40BFE.2020301@comcast.net> <1188744204.822322.198360@57g2000hsv.googlegroups.com> <46DAD433.1030503@comcast.net> <1188849476.067121.119110@r34g2000hsd.googlegroups.com> Message-ID: <1188855687.442121.85030@22g2000hsm.googlegroups.com> On Sep 3, 12:57 pm, devondej... at comcast.net wrote: > On Sep 2, 9:18 am, "Richard B. Gilbert" > wrote: > > > HEY! NOBODY BASHES THE TOOTH FAIRY! > -Shrug- I fucked her. mvm From mail at microcorp.co.za Thu Sep 20 03:05:36 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 20 Sep 2007 09:05:36 +0200 Subject: Google and Python References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> Message-ID: <00f801c7fb59$3300cca0$03000080@hendrik> "TheFlyingDutchman" wrote: > Around 2000 I heard that Google was using Python to some extent. Now I > see that Guido Van Rossum works for them as well as Alex Martellis 8< ----------------------------------------------------------------------------- --------- It seems that shortening "Alessandro" to "Alex" was not enough. I wonder if the Flying Dutchman is another van der Decker? - Hendrik From kenneth.m.mcdonald at sbcglobal.net Sat Sep 1 23:35:44 2007 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Sat, 01 Sep 2007 22:35:44 -0500 Subject: How best to dynamically define methods (and functions)? Message-ID: <46DA2F90.7010109@sbcglobal.net> I can see an obvious but hacky way to define a Python function at runtime. I can't see any obvious way to add a method to a class at runtime (though I'm sure one could do just about anything by digging into the metaclass stuff, which I will do if needed). But pointers to cleaner or easier existing ways to do this would be most appreciated. In case it's of interest in the context of the question, I need to define a largish set of functions (and similar methods) that define a XML-type markup language. Most of these functions will just be of the form def fun(...): return Node('fun', ...) so it'd definitely be nice to just create most of them automatically, and only do the special cases by hand. Many thanks, Ken From steve at holdenweb.com Mon Sep 10 16:24:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Sep 2007 16:24:46 -0400 Subject: PIL Error: "cannot read interlaced PNG files" In-Reply-To: <1189449506.496986.88290@y42g2000hsy.googlegroups.com> References: <1189449506.496986.88290@y42g2000hsy.googlegroups.com> Message-ID: T-u-N-i-X wrote: > Hey There, > > I'm developing an application that lets the user to upload JPG and PNG > files. I'm using PIL to check the images after the upload (like > checking it storage size, width and height). But PIL raises an error: > > "cannot read interlaced PNG files" > > It says that interlaced PNG files are not supported in the PIL > documentation. I'm using PIL 1.1.6-2 on Arch Linux.. > > I can check all images with: > > from PIL import Image > im = Image.open('image.png') > im.info > > which returns a dictionary about the image. If the dict has > 'interlace' key with the value 1, then I reject the event that's being > send with a validation error. But I don't think this is a good idea > since this could be very annoying for the users. > Perhaps so, but it would seem this is your only viable option short of either persuading the effbot to patch PIL to read interlaced PNGs or patching it yourself. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From henriklied at gmail.com Thu Sep 27 07:28:19 2007 From: henriklied at gmail.com (Henrik Lied) Date: Thu, 27 Sep 2007 11:28:19 -0000 Subject: "No backend servers available" using httplib In-Reply-To: <46fb7e40$0$29672$426a74cc@news.free.fr> References: <1190884447.792688.107710@g4g2000hsf.googlegroups.com> <46fb7e40$0$29672$426a74cc@news.free.fr> Message-ID: <1190892499.308111.61600@g4g2000hsf.googlegroups.com> On Sep 27, 11:56 am, Bruno Desthuilliers wrote: > Henrik Lied a ?crit : > > > Hi there! > > > I'm using a recipe found on ASPN [1] to upload some data to an > > external server. > > > The request fails, and all I get in response is "No backend servers > > available". > > > So I'm wondering: Is this a known exception-message in httplib, > > If it was, you should have a full traceback then. > > > or > > could it be an error in the requested external resource? > > [1]:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 > > From the recipe's code and the message, looks like you're connecting to > (or via) a proxy which fails to relay to the real server. Hello Bruno, The actual reason was quite a bit simpler: The receiving server required a certain keyword to be first in the request - which I was not aware of. So now it works - but it's not perfect: Is there a way to stream the file content over the connection? The way it works now, the whole file is loaded into memory, right? From bscrivener42 at gmail.com Fri Sep 14 21:14:26 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Sat, 15 Sep 2007 01:14:26 -0000 Subject: vi and python In-Reply-To: References: Message-ID: <1189818866.523024.196320@g4g2000hsf.googlegroups.com> On Sep 14, 7:35 pm, "Danyelle Gragsone" wrote: > Good Evening, > > I am running gentoo. I want to use vi to program in python. I > wondered are there any other gentooovians out there who know if python > support is already installed. http://tinyurl.com/2mzakm rd From khemkaamit at gmail.com Tue Sep 4 07:03:05 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 4 Sep 2007 16:33:05 +0530 Subject: TypeError: 'module object is not callable' In-Reply-To: <1188903123.701882.205780@o80g2000hse.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188903123.701882.205780@o80g2000hse.googlegroups.com> Message-ID: <1360b7230709040403l20f3290k3b1624bdffba8bd4@mail.gmail.com> On 9/4/07, cjt22 at bath.ac.uk wrote: > On Sep 4, 11:24 am, "Amit Khemka" wrote: > > On 9/4/07, Chris.T... at jet.uk wrote: > > > > > Thanks guys. Changing to how Python does things has a lot of geting > > > used to! > > > Do any of you have any ideas on the best way to do the following > > > problem: > > > > > Each loop I perform, I get a new list of Strings. > > > I then want to print these lists as columns adjacent to each other > > > starting with the first > > > created list in the first column and last created list in the final > > > column. > > > > > If you need any more information, just let me know! > > > Cheers > > > > If I understand correctly what you may want is: > > > > >>> l = ['1', '2', '3', '4'] > > > > you can do: > > > > >>> print "\t".join(l) # lookup join method in stringmodule, > > > > assuming "\t" as the delimiter > > > > or, > > > > >>> for i in l: > > > > .... print i, '\t' , # note the trailing "," > > > > If this isnotwhat you want, post an example. > > > > Btw, Please post new issues in a separate thread. > > > > Cheers, > > -- > > ---- > > Amit Khemka > > website:www.onyomo.com > > wap-site:www.owap.in > > I think that is very similar to what I want to do. > Say I had lists a = ["1" , "2", "3"] b = ["4", "5", "6"] c = ["7", > "8", "9"] > Stored in another list d = [a,b,c] > I want the printed output from d to be of the form: > 1 4 7 > 2 5 8 > 3 6 9 > > >From what I am aware, there is no table module to do this. The '\t' > operator looks like it can allow this, > I am playing with it at the moment, although going for my lunch break > now! Have a look at function 'zip' or function 'izip' in module "itertools" . -- ---- Amit Khemka website: www.onyomo.com wap-site: www.owap.in From kyosohma at gmail.com Tue Sep 18 15:33:40 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 18 Sep 2007 19:33:40 -0000 Subject: Extracting xml from html In-Reply-To: <46EF769E.4080103@web.de> References: <1190061079.025479.129070@w3g2000hsg.googlegroups.com> <46EF769E.4080103@web.de> Message-ID: <1190144020.294613.167800@57g2000hsv.googlegroups.com> On Sep 18, 1:56 am, Stefan Behnel wrote: > kyoso... at gmail.com wrote: > > I am attempting to extract some XML from an HTML document that I get > > returned from a form based web page. For some reason, I cannot figure > > out how to do this. > > Here's a sample of the html: > > > > > > > lots of screwy text including divs and spans > > > > 1126264 > > Mitsubishi > > Mirage DE > > > > > > > > > What's the best way to get at the XML? Do I need to somehow parse it > > using the HTMLParser and then parse that with minidom or what? > > lxml makes this pretty easy: > > >>> parser = etree.HTMLParser() > >>> tree = etree.parse(the_file_or_url, parser) > > This is actually a tree that can be treated as XML, e.g. with XPath, XSLT, > tree iteration, ... You will also get plain XML when you serialise it to XML: > > >>> xml_string = etree.tostring(tree) > > Note that this doesn't add any namespaces, so you will not magically get valid > XHTML or something. You could rewrite the tags by hand, though. > > Stefan I got it to work with lxml. See below: def Parser(filename): parser = etree.HTMLParser() tree = etree.parse(r'path/to/nextpage.htm', parser) xml_string = etree.tostring(tree) events = ("recordnum", "primaryowner", "customeraddress") context = etree.iterparse(StringIO(xml_string), tag='') for action, elem in context: tag = elem.tag if tag == 'primaryowner': owner = elem.text elif tag == 'customeraddress': address = elem.text else: pass print 'Primary Owner: %s' % owner print 'Address: %s' % address Does this make sense? It works pretty well, but I don't really understand everything that I'm doing. Mike From ldo at geek-central.gen.new_zealand Mon Sep 24 21:13:47 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 25 Sep 2007 13:13:47 +1200 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: In message , Neil Cerutti wrote: > On 2007-09-22, Lawrence D'Oliveiro > wrote: > >> In message <5lhs4pF8bkunU1 at mid.individual.net>, Bjoern >> Schliessmann wrote: > >>> Nah. Use vim. >> >> Every other text editor I have ever used understands that the >> current position in a file is _between_ two characters (or >> before the first character, or after the last character), not >> _on_ a character. But not vi and its ilk. >> >> Try the following in vi/vim: Move to some point in the middle >> of a line. Press "i" to get into insert mode. Press escape to >> get out again. You'll end up one position to the left of where >> you were before. Press "i", and then escape again--you've moved >> another position left. Why is it incapable of keeping track of >> such a simple thing as your current position in the file? > > That's a silly question. Of course it knows your current > position--it just chooses to modify your position when you exit > insert mode. That's like saying, about a program that, when given "2 + 2", outputs "5", that _of course_ it knows the correct answer is "4", it just chooses to "modify" the answer before outputting it. Why does it "choose" to modify your position when you exit insert mode? Does the phrase "broken as designed" mean anything to you? >> Why does it need two different insert commands, "i" versus "a"? >> Because one of them can't insert at the end of a line, and the >> other can't insert at the beginning. > > i and a are two of *many* ways to enter insert mode. Why do you need so many ways to enter insert mode? >> And why have command-versus-insert mode at all? No other text >> editor still surviving uses such an antiquated concept. > > The existence of command mode allows plain old keystrokes to be > commands--it potentially makes commands easier to type. And the downside is that the largest single proportion of those commands end up being variations on "enter insert mode". Because most of the keystrokes you enter during an editing session are in fact text to be input into the file, not commands to manipulate that text. So in a modal editor, having to jump in and out of insert mode all the time just adds to the number of keystrokes you have to type. From carsten at uniqsys.com Fri Sep 14 10:23:02 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 14 Sep 2007 10:23:02 -0400 Subject: where is help file? In-Reply-To: <13el4vvna6jildc@corp.supernews.com> References: <13el4vvna6jildc@corp.supernews.com> Message-ID: <1189779782.3377.7.camel@dot.uniqsys.com> On Fri, 2007-09-14 at 10:00 -0400, PaulS wrote: > new to Fedora7, typed python in interactive interpreter, then help(). Then > modules to get a list of modules. Then module name to get info on a module > but no help file. What is the help file name? Is there an environmental > variable I have to set? There is no help file, and no environment variable. The help text is stored directly inside each module and function that supplies a help text. Observe: >>> def f(x): ... "Calculate the square of x." ... return x**x ... >>> help(f) Help on function f in module __main__: f(x) Calculate the square of x. (END) Providing such a help text is optional, but all standard library modules do provide help as far as I know. Consequently, the fact that you have a module that doesn't provide a help text seems to indicate that it's not a standard library module. What's the name of the module you're trying to get help on? Hope this helps (no pun intended), -- Carsten Haese http://informixdb.sourceforge.net From lasses_weil at klapptsowieso.net Tue Sep 4 14:58:15 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Tue, 04 Sep 2007 20:58:15 +0200 Subject: Noob: What is a slot? Me trying to understand another's code In-Reply-To: References: Message-ID: <46ddaac8$0$4523$9b4e6d93@newsspool3.arcor-online.net> Carnell, James E wrote: > > I am thinking about purchasing a book, but wanted to make sure I could > get through the code that implements what the book is about (Artificial > Intelligence a Modern Approach). Anyway, I'm not a very good programmer > and OOP is still sinking in, so please don't answer my questions like I > really know anything. > > MY QUESTION: > What is a slot? In class Object below the __init__ has a slot. Note: > The slot makes use of a data object called 'percept' that is used in the > TableDrivenAgent(Agent) at the bottom of this post. I am guessing this > is a type of Finite State Machine (I haven't bought the book yet so I am > guessing). > I really have a hard time grasping what it is you don't understand (the annoying thing about not understanding stuff is that you usually lack the proper terms to explain what you don't understand, precisely _because_ you don't understand it ;)). At first I thought you were talking about __slots__, as explained in the docs . > [but some snipped code later you say:] > > ##################### HERE IS THE SLOT ####################### > > def __init__(self): > def program(percept): > return raw_input('Percept=%s; action? ' % percept) > self.program = program > self.alive = True > That is "simply" a special method (namely the one that is called after instance creation so you can set up the instance variables). You should really know that.<\nagging> Lookie here: Did that do it? Sorry, I have big trouble looking at long listings and figuring out their meaning. If that didn't help, try reformulating your question (please). /W From bert at bertisevil.tv Thu Sep 6 23:30:55 2007 From: bert at bertisevil.tv (Evil Bert) Date: Fri, 07 Sep 2007 03:30:55 GMT Subject: interesting puzzle......try this you will be rewarded... In-Reply-To: <1189130241.529344.52950@57g2000hsv.googlegroups.com> References: <1189072576.997085.32360@r29g2000hsg.googlegroups.com> <46e04138$0$16377$88260bb3@free.teranews.com> <1189130241.529344.52950@57g2000hsv.googlegroups.com> Message-ID: Basilisk96 wrote: > I remember seeing a more elaborate puzzle that involved coding, > cryptography knowledge, etc. to get through it. But what was the link, > I forget now... There's this one http://www.inwardhellix.net/ I haven't played it yet so I can't vouch for its quality. (am playing it now) From iclark at mail.ewu.edu Thu Sep 6 14:24:34 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Thu, 06 Sep 2007 11:24:34 -0700 Subject: Beginners Query - Simple counter problem In-Reply-To: <1189102450.3376.17.camel@dot.uniqsys.com> References: <13e0g0id9rlmg71@corp.supernews.com> <1189102450.3376.17.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > On Thu, 2007-09-06 at 11:00 -0700, Scott David Daniels wrote: >> def d6(count): >> result = 0 >> for die in range(count): >> result += random.randint(1, 6) >> return result > > This, of course, can be further improved into: > > def d6(count): > return sum(random.randint(1, 6) for die in range(count)) > My stab at it: >>> def roll(times=1, sides=6): ... return random.randint(times, times*sides) Ian From sjmachin at lexicon.net Sat Sep 22 00:07:49 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Sep 2007 21:07:49 -0700 Subject: Newbie completely confused In-Reply-To: References: Message-ID: <1190434069.108503.281930@y42g2000hsy.googlegroups.com> On Sep 22, 2:34 am, Jeroen Hegeman wrote: [snip] > ...processing all 2 files found > --> 1/2: ./test_file0.txt > Now reading ... > DEBUG readLines A took 0.093 s > ...took 8.85717201233 seconds Your code does NOT include any statements that could have produced the above line of output -- IOW, you have not posted the code that you actually ran. Your code is already needlessly monstrously large. That's two strikes against anyone bothering to try to nut out what's going wrong, if indeed anything is going wrong. [snip] > > The original problem showed up using Python 2.4.3 under linux (Fedora > Core 1). > Python 2.3.5 on OS X 10.4.10 (PPC) appears not to show this issue(?). And Python 2.5.1 does what? Strike 3. > > P.S. Any ideas on optimising the input to the classes would be > welcome too ;-) 1. What is the point of having a do-nothing __init__ method? I'd suggest making the __init__method do the "input". 2. See below [snip] > > class LongClass: > > def __init__(self): > return > def clear(self): > return > def input(self, foo, c): > self.item0 = float(foo[c]); c += 1 > self.item1 = float(foo[c]); c += 1 [multiple snips ahead] > self.item18 = float(foo[c]); c+=1 > self.item19 = int(foo[c]); c+=1 > self.item20 = float(foo[c]); c+=1 > self.item27 = bool(int(foo[c])); c+=1 > self.item30 = (foo[c] == "1"); c += 1 > self.item31 = (foo[c] == "1"); c += 1 > self.item47 = bool(int(foo[c])); c+=1 > return c at global level: converters = [float] * 48 cvlist = [ (int, (19, 22, 26, 34, 40, 46)), (lambda z: bool(int(z)), (27, 47)), (lambda z: z == "1", (30, 31, 36, 37, 42)), ] for func, indexes in cvlist: for x in indexes: converters[x] = func enumerated_converters = list(enumerate(converters)) Then: def input(self, foo, c): self.item = [func(foo[c+x]) for x, func in enumerated_converters] return c + 48 which requires you refer to obj.item[19] instead of obj.item19 If you *must* use item19 etc, then try this: for x, func in enumerated_converters: setattr(self, "item%d" % x, func(foo[c+x])) You could also (shock, horror) use meaningful names for the attributes ... include a list of attribute names in the global stuff, and put the relevant name in as the 2nd arg of setattr() instead of itemxx. For handling the bit extraction stuff, either (a) conversion functions have a 2nd arg which defaults to None and whose usage depends on the function itself ... would be mask or bit position (or could be e.g. a scale factor for implied-decimal-point input) or (b) do a loop over the bit positions HTH, John From george.trojan at noaa.gov Thu Sep 20 09:08:17 2007 From: george.trojan at noaa.gov (George Trojan) Date: Thu, 20 Sep 2007 09:08:17 -0400 Subject: frange() question Message-ID: A while ago I found somewhere the following implementation of frange(): def frange(limit1, limit2 = None, increment = 1.): """ Range function that accepts floats (and integers). Usage: frange(-2, 2, 0.1) frange(10) frange(10, increment = 0.5) The returned value is an iterator. Use list(frange) for a list. """ if limit2 is None: limit2, limit1 = limit1, 0. else: limit1 = float(limit1) count = int(math.ceil(limit2 - limit1)/increment) return (limit1 + n*increment for n in range(count)) I am puzzled by the parentheses in the last line. Somehow they make frange to be a generator: >> print type(frange(1.0, increment=0.5)) But I always thought that generators need a keyword "yield". What is going on here? George From aleax at mac.com Sat Sep 1 21:51:15 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 1 Sep 2007 18:51:15 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <1188585630.539835.242460@i38g2000prf.googlegroups.com> <1188592039.612652.223700@r23g2000prd.googlegroups.com> Message-ID: <1i3ryxd.g2pzgq159lt5sN%aleax@mac.com> Russ wrote: ... > > > the inputs. To test the > > > post-conditions, you just need a call at the bottom of the function, > > > just before the return, ... > > there's nothing to stop you putting the calls before every return. > > Oops! I didn't think of that. The idea of putting one before every > return certainly doesn't appeal to me. So much for that idea. try: blah blah with as many return statements as you want finally: something that gets executed unconditionally at the end You'll need some convention such as "all the return statements are of the same form ``return result''" (where the result may be computed differently each time), but that's no different from the conventions you need anyway to express such things as ``the value that foobar had at the time the function was called''. Alex From steve at holdenweb.com Fri Sep 21 15:23:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Sep 2007 15:23:09 -0400 Subject: RE Help In-Reply-To: <1190401551.706792.178450@22g2000hsm.googlegroups.com> References: <1190399985.324448.242610@d55g2000hsg.googlegroups.com> <1190401551.706792.178450@22g2000hsm.googlegroups.com> Message-ID: chris.monsanto at gmail.com wrote: > On Sep 21, 2:44 pm, David wrote: >>> data = "asdfasgSTARTpruyerfghdfjENDhfawrgbqfgsfgsdfg" >>> x = re.compile('START.END', re.DOTALL) >> This should work: >> >> x = re.compile('START(.*)END', re.DOTALL) > > You'll want to use a non-greedy match: > > x = re.compile(r"START(.*?)END", re.DOTALL) > > Otherwise the . will match END as well. > Only if there's a later END in the string, in which case the user's requirements will determine whether greedy matching is appropriate. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From wolf_tracks at invalid.com Tue Sep 18 22:33:07 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 19 Sep 2007 02:33:07 GMT Subject: Tutorial or Example (or Tutorial) of Using Canvas to Produce a Plot In-Reply-To: <9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com> References: <13evohih7rkd030@corp.supernews.com> <13f0b2qlvj5ige6@corp.supernews.com> <9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com> Message-ID: Thanks. I've arranged for an inter-library loan(ILL), and probably will not get his book for several days yet. I've had the book before, but was really unable to get the time to pursue it (the ILL). I have his web site bookmarked. I do not yet plan to buy his book, web or hardbound yet. Maybe I can re-examine his site for examples, and find one that is appropriate. Richard Townsend wrote: > On Tue, 18 Sep 2007 13:18:36 -0700, "W. Watson" > wrote: > >> Tk is it. I'm really not interested in the others at this point. >> > > John Grayson's book 'Python and Tkinter Programming' has a chapter on > plotting Graphs and Charts. You can even download that chapter as a > PDF file: > > http://www.manning-source.com/books/grayson/grayson_ch11.pdf > > See http://www.manning.com/grayson/ for more info about the book. > -- Wayne Watson (Nevada City, CA) Web Page: From http Thu Sep 20 11:42:37 2007 From: http (Paul Rubin) Date: 20 Sep 2007 08:42:37 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> <1190241711.344058.238380@57g2000hsv.googlegroups.com> <1190242799.954176.279440@22g2000hsm.googlegroups.com> <7xps0ew0a8.fsf@ruckus.brouhaha.com> <13f3roj6gdfq6b7@corp.supernews.com> <7x1wctwg6x.fsf@ruckus.brouhaha.com> Message-ID: <7xsl59uyvm.fsf@ruckus.brouhaha.com> "Chris Mellon" writes: > > The compute intensive stuff (image rendering and crunching) has > > already had most of those skerricks pulled out. It is written in C > > and assembler > That means that this part is also unaffected by the GIL. Right, it was a counterexample against the "speed doesn't matter" meme, not specifically against the GIL. And that code is fast because someone undertook comparatively enormous effort to code it in messy, unsafe languages instead of Python, because Python is so slow. > At the really high levels of scalability, such as across a server > farm, threading is useless. The entire point of threads, rather than > processes, is that you've got shared, mutable state. A shared nothing > process (or Actor, if you will) model is the only one that makes sense > if you really want to scale because it's the only one that allows you > to distribute over machines. The fact that it also scales very well > over multiple cores (better than threads, in many cases) is just > gravy. In reality you want to organize the problem so that memory intensive stuff is kept local, and that's where you want threads, to avoid the communications costs of serializing stuff between processes, either between boxes or between cores. If communications costs could be ignored there would be no need for gigabytes of ram in computers. We'd just use disks for everything. As it is, we use tons of ram, most of which is usually twiddling its thumbs doing nothing (as DJ Bernstein put it) because the cpu isn't addressing it at that instant. The memory just sits there waiting for the cpu to access it. We actually can get better-than-linear speedups by designing the hardware to avoid this. See: http://cr.yp.to/snuffle/bruteforce-20050425.pdf for an example. > The only hard example I've seen given of the GIL actually limiting > scalability is on single server, high volume Django sites, and I don't > think that the architecture of those sites is very scalable anyway. The stuff I'm doing now happens to work ok with multiple processes but would have been easier to write with threads. From deets at nospam.web.de Wed Sep 12 05:16:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Sep 2007 11:16:52 +0200 Subject: setattr vs readonly property References: <1189588059.059818.301090@y42g2000hsy.googlegroups.com> Message-ID: <5kpp44F4s7pgU1@mid.uni-berlin.de> james_027 wrote: > hi, > > My main purpose for using setattr(object, attr, value) for assign > values from a dict that has some keys that may not be present on some > object's attibute, which makes it work for me. My problem is dealing > with read only attribute like sample_attribute = > property(f_get=_get_sample_attribute). what approach should I use? Or > is my first approach In the first place right? Since read-only properties are very concise written as this: class Foo(object): @property def ro_prop(self): return "whatever" I'd say that's the way to go - using __getattr__ for this will lead to rather convoluted code IHMO. Diez From andrew.lee at nymag.com Thu Sep 13 12:10:03 2007 From: andrew.lee at nymag.com (Andrew F) Date: Thu, 13 Sep 2007 09:10:03 -0700 Subject: Error in random module, bad installation? In-Reply-To: <9lghe31glgpq8ge20ko3t1nqui0h9oag2a@4ax.com> References: <1189635238.655642.233240@g4g2000hsf.googlegroups.com> <9lghe31glgpq8ge20ko3t1nqui0h9oag2a@4ax.com> Message-ID: <1189699803.582384.125320@k79g2000hse.googlegroups.com> On Sep 13, 12:57 am, Tim Roberts wrote: > Andrew F wrote: > >I'm a linux user and I just upgraded from 2.1 to 2.5 and changed the > >location of a number of libraries and tools. > > >So far I've tracked most errors, but this one has me scratching my > >head : > > >$ which python > >/usr/local/bin/python > >$ echo $PYTHONPATH > >/usr/local/bin/python > > PYTHONPATH is supposed to point to the directory containing modules, NOT > the directory containing the executable. It should be /lib/python2.5. > Thank you both -- it was a combination of the problems. From fredrik at pythonware.com Wed Sep 26 09:37:09 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 15:37:09 +0200 Subject: Test-driven development and code size In-Reply-To: <5lv4t4Faeqk8U1@mid.uni-berlin.de> References: <5ls95aF9pq3gU1@mid.uni-berlin.de> <87ejgmmgc2.fsf_-_@benfinney.id.au> <5lv4t4Faeqk8U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Sounds good to me. IMHO there are two ways one gathers tests: > > - concrete bugs appear, and one writes a test that reproduces the bug & > eventually after the fix runs smoothly > > - new features are planned/implemented, and the tests accompany them right > from the start, to allow .. .well, to test them :) > > I always found it difficult to "just think" of new tests. Of course if you > _start_ with TDD, point two is applied right from the start and should > apply. an approach that works for me is to start by adding "sanity checks"; that is, straightforward test code that simply imports all modules, instantiates objects, calls the important methods with common argument types/counts, etc, to make sure that the library isn't entirely braindead. this has a bunch of advantages: - it gets you started with very little effort (especially if you use doctest; just tinker a little at the interactive prompt, and you have a first version) - it gives you a basic structure which makes it easier to add more detailed tests - it gives you immediate design feedback -- if it's difficult to think of a even a simple test, is the design really optimal? - it quickly catches build and installation issues during future development (including refactoring). and probably a few more things that I cannot think of right now. From facundobatista at gmail.com Thu Sep 13 15:08:48 2007 From: facundobatista at gmail.com (Facundo Batista) Date: Thu, 13 Sep 2007 16:08:48 -0300 Subject: Python tickets summary In-Reply-To: References: Message-ID: 2007/9/10, Facundo Batista : > I modified my tool, whichs makes a summary of all the Python tickets > (I moved the source where the info is taken from SF to our Roundup). > > In result, the summary is now, again, updated daily: Taking an idea from Jeff Rush, now there're separate listings in function of the keyword of the ticket. This way, you can see only the Py3k tickets, or the patchs, etc. All the listings are accesible from the same pages, start here: http://www.taniquetil.com.ar/facundo/py_tickets.html (remember to refresh) Any idea to improve these pages is welcomed. Regards, -- . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From __peter__ at web.de Wed Sep 19 09:09:54 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2007 15:09:54 +0200 Subject: cannot create my own dict References: Message-ID: A.T.Hofkamp wrote: > This morning I tried to create my own read-only dictionary, and failed > miserably. > I don't understand why, can somebody enlighten me? > > Below is a brute-force experiment that cannot deal with "x in obj", plz read > the explanation below the code: > -------------------------------- > class myowndict(object): > def __init__(self, mydict): > self.mydict = mydict > > # Below is produced with > # print '\n'.join([' self.%s = self.mydict.%s' % (v,v) > # for v in dir(dict)]) > # commented-out functions done by hand > # > #self.__class__ = self.mydict.__class__ > self.__cmp__ = self.mydict.__cmp__ > self.__contains__ = self.mydict.__contains__ > self.__delattr__ = self.mydict.__delattr__ > self.__delitem__ = self.mydict.__delitem__ > #self.__doc__ = self.mydict.__doc__ > self.__eq__ = self.mydict.__eq__ > self.__ge__ = self.mydict.__ge__ > self.__getattribute__ = self.mydict.__getattribute__ > self.__getitem__ = self.mydict.__getitem__ > self.__gt__ = self.mydict.__gt__ > self.__hash__ = self.mydict.__hash__ > #self.__init__ = self.mydict.__init__ > self.__iter__ = self.mydict.__iter__ > self.__le__ = self.mydict.__le__ > self.__len__ = self.mydict.__len__ > self.__lt__ = self.mydict.__lt__ > self.__ne__ = self.mydict.__ne__ > #self.__new__ = self.mydict.__new__ > self.__reduce__ = self.mydict.__reduce__ > self.__reduce_ex__ = self.mydict.__reduce_ex__ > self.__repr__ = self.mydict.__repr__ > self.__setattr__ = self.mydict.__setattr__ > self.__setitem__ = self.mydict.__setitem__ > self.__str__ = self.mydict.__str__ > self.clear = self.mydict.clear > self.copy = self.mydict.copy > self.fromkeys = self.mydict.fromkeys > self.get = self.mydict.get > self.has_key = self.mydict.has_key > self.items = self.mydict.items > self.iteritems = self.mydict.iteritems > self.iterkeys = self.mydict.iterkeys > self.itervalues = self.mydict.itervalues > self.keys = self.mydict.keys > self.pop = self.mydict.pop > self.popitem = self.mydict.popitem > self.setdefault = self.mydict.setdefault > self.update = self.mydict.update > self.values = self.mydict.values > > # end of __init__ > > if __name__ == '__main__': > fd = myowndict({1:10}) > print 1 in fd # FAILS! (with "TypeError: iterable argument required") > -------------------------------- > > I wanted to make my own dictionary. However, a simple element test failed > (after implementing various __*__ functions), and I cannot figure out why. > > The above code is a brute force attempt, where I forward all methods (except > __class__, __doc__, __init__, and __new__) to my local 'mydict' object. > > IT STILL FAILS. __special__ methods are looked up in the class, never in the instance for newstyle classes: >>> def class_method(self, *v): print "class" ... >>> def inst_method(*v): print "instance" ... >>> class B(object): ... __contains__ = class_method ... copy = class_method ... def __init__(self): ... self.__contains__ = inst_method ... self.copy = inst_method ... >>> 42 in B() class False >>> B().copy() instance > So if copying all methods of a native dictionary is not enough, what should I > do to make my class work as a dictionary WITHOUT deriving from dict (which will > obviously work). Write wrappers like def __contains__(self, value): return value in self.mydict Peter From steve at REMOVE-THIS-cybersource.com.au Sun Sep 2 18:53:32 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 02 Sep 2007 22:53:32 -0000 Subject: how can I find out the process ids with a process name References: <1188761187.522146.192380@y42g2000hsy.googlegroups.com> Message-ID: <13dmfncmf5pmf7b@corp.supernews.com> On Sun, 02 Sep 2007 19:26:27 +0000, herman wrote: > But now I would like to do the programmically in my python script. I > know I can use ' os.system(cmd)' to execute the command 'ps -ef | grep > emacs', but how > can I pipe the output of my 'ps -ef | grep emacs' to my python script > and then run a regression expression with it to get the process Ids? Use popen. >>> f = os.popen('ps ax | grep -i PYTHON') >>> print f.read() 1952 ? Ssl 0:01 /usr/bin/python -E /usr/sbin/setroubleshootd 2117 ? S 0:00 python ./hpssd.py 2376 ? SN 3:19 /usr/bin/python /usr/sbin/yum-updatesd 18087 pts/4 S+ 0:00 python 18115 pts/4 S+ 0:00 sh -c ps ax | grep -i PYTHON 18117 pts/4 R+ 0:00 grep -i python There is also a module popen2 which does similar but more advanced things. -- Steven. From robertoedwins at gmail.com Wed Sep 5 15:02:26 2007 From: robertoedwins at gmail.com (rieh25) Date: Wed, 5 Sep 2007 12:02:26 -0700 (PDT) Subject: ZSI sample and issues with the WSDL In-Reply-To: References: Message-ID: <12508850.post@talk.nabble.com> I'm not sure I know enough to help you, but who knows, maybe this could be of help. I think that technology is more complicated (or ureliable) than it should. Possibly the best thing to do is not to depend upon already built wsdl facilities, but instead work with a basic webservice routine, and work with it around wsdl. For instance: ## message_builder_py: import sys, httplib def send_message(m): #construct and send the header if m['type'] == 'HTTP': webservice = httplib.HTTP(m['page'], 80) elif m['type'] == 'HTTPS': webservice = httplib.HTTPS(m['page'], 443) webservice.putrequest("POST", m['post']) webservice.putheader("Host", m['host']) webservice.putheader("Content-type", m['content-type']) webservice.putheader("Content-length", "%d" % len(m['message'])) webservice.putheader("SOAPAction", m['SOAPAction']) webservice.endheaders() webservice.send(m['message']) # get the response statuscode, statusmessage, header = webservice.getreply() r = {} r['Response'] = {'statuscode': statuscode, 'statusmessage': statusmessage} r['header'] = header r['res'] = webservice.getfile().read() return r ###call in another place: xml = """ gamazari laclave %s %s """ mensaje = {} mensaje['funcion'] = 'SIAFCatalogoFacturas' mensaje['funcion atribs'] = [['xmlns', 'http://tempuri.org/SIAFProxyWS/Service1']] params = [] params += [{'parametro': 'xml', 'type': 'string', 'valor': xml % (anio, mes)}] mensaje['parametros'] = params mensaje['pagina'] = 'sicoindes.minfin.gob.gt' mensaje['tipo'] = 'HTTPS' mensaje['post'] = '/SIAFProxyWs/SIAFPService.asmx' mensaje['host'] = 'sicoindes.minfin.gob.gt' mensaje['SOAPAction'] = '"http://tempuri.org/SIAFProxyWS/Service1/SIAFCatalogoFacturas"' res = context.Funcionalidad.Utilidades.SOAP.message_builder_py(mensaje) David Ross-6 wrote: > > First two appologies, this is probably not a Python question, more > SOAP. And second, there is every possibilty I am terminally confused > having looked at this for two days now. > > What I want is to create a Python SOAP server. I am using the sample > which comes with ZSI, namely the Echo.wsdl and associated files. I > then follow the instructions in the readme, and I CAN get a python > client and server to communicate. > > But when I take the WSDL file and try to create a VB.NET program: > >>wsdl.exe /language:VB /out:myProxyClass.vb Echo.wsdl > > I get: > > Error: Unable to import binding 'EchoServer' from namespace > 'urn:ZSI:examples'. > - Unable to import operation 'Echo'. > - Specified cast is not valid. > > So I tried to set up the wsdl to point to my domain: > > > > xmlns="http://schemas.xmlsoap.org/wsdl/" > xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" > xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" > xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" > xmlns:xsd="http://www.w3.org/2001/XMLSchema" > xmlns:tns="http://www.me.org/Namespaces" > targetNamespace="http://www.me.org/Namespaces" > > > > > > > > > > > > > > > > > > transport="http://schemas.xmlsoap.org/soap/http"/> > > > > > > > > > > > > > > > > > > > > > I get a the same error: > > Error: Unable to import binding 'EchoServer' from namespace > 'http://www.me.org/Namespaces'. > - Unable to import operation 'Echo'. > - Specified cast is not valid. > > My problem is that I'm not sure how to edit the ZSI example. Worse, > this is pretty much as simple as it seems to get ;-( > > Any pointers would be greatfully received. > > I know I should ask in the MS forumns, but I was hoping someone would > understand the ZSI example better than I seem to. > > Cheers > > David > > ---- > Note anti-spam in email address... > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/ZSI-sample-and-issues-with-the-WSDL-tf4384788.html#a12508850 Sent from the Python - python-list mailing list archive at Nabble.com. From bdesth.quelquechose at free.quelquepart.fr Thu Sep 13 13:52:47 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 13 Sep 2007 19:52:47 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <1189700775.661780.292150@50g2000hsm.googlegroups.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> Message-ID: <46e97917$0$9014$426a74cc@news.free.fr> TheFlyingDutchman a ?crit : > Well I'm with Bruce Eckel - there shouldn't be any argument for the > object in the class method parameter list. def fun(obj, *args, **kw): # generic code here that do something with obj import some_module some_module.SomeClass.fun = fun This is why uniformity is important. But anyway, I think it's quite clear that Python won't drop the explicit self, so it looks like you have to live with it or choose another language. > Bruce said that no other mainstream OO language is explicitly passing > the object as a parameter to class methods. to methods. class methods gets the class as first parameter. Anyway, there are a lot of things that Python doesn't do like "other mainstream OO languages", and that's a GoodThing. > What I would like to have seen added to class definitions was the > forced declaration of all object variables in the class outside of > methods. I don't like the fact that they have to be, and can be > created in any method on the fly. I definitively think you'd be happier with some other language. From ldo at geek-central.gen.new_zealand Mon Sep 24 00:23:46 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 24 Sep 2007 16:23:46 +1200 Subject: database persistence with mysql, sqlite References: <1190502677.970811.181100@22g2000hsm.googlegroups.com> Message-ID: In message <1190502677.970811.181100 at 22g2000hsm.googlegroups.com>, coldpizza wrote: > So far, with mysql I use 'SELECT * FROM TABLE LIMIT L1, L2' where L1 > and L2 define the range for the 'Next' and 'Previous' commands. I > have to run the query every time a click a 'Next/Prev' link. But I am > not sure that this is the best and most efficient way. Try it first, then see what happens. Remember, premature optimization is the root of all (programming) evil. From tjreedy at udel.edu Sat Sep 1 12:34:05 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Sep 2007 12:34:05 -0400 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com><-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com><1188364909.397692.209170@q4g2000prc.googlegroups.com><1188367108.393207.241970@g4g2000hsf.googlegroups.com><1188369928.755777.142690@i38g2000prf.googlegroups.com><46d75191$0$401$426a74cc@news.free.fr><1188518054.298017.90610@x35g2000prf.googlegroups.com><46d76595$0$4013$426a74cc@news.free.fr><1188523589.736146.263510@l22g2000prc.googlegroups.com><1i3o9kr.2gmni61g62moaN%aleax@mac.com><7xwsvcc9yz.fsf@ruckus.brouhaha.com><1i3p8lm.19738kn1q0gkouN%aleax@mac.com><1188587846.687895.69240@q5g2000prf.googlegroups.com><38rmq4-cq.ln1@strongwill.g2ctech><46d903db$0$19580$4c368faf@roadrunner.com> <026201c7ec75$07d6e0c0$03000080@hendrik> Message-ID: "Hendrik van Rooyen" wrote in message news:026201c7ec75$07d6e0c0$03000080 at hendrik... | This really intrigues me - how do you program a dam? - and why is it | critical? | | Most dams just hold water back. Most big dams also generate electricity. Even without that, dams do not just hold water back, they regulate the flow over a year or longer cycle. A full dam is great for power generation and useless for flood control. An empty dam is great for flood control and useless for power generation. So both power generation and bypass release must be regulated in light of current level, anticipated upstream precipitation, and downstream obligations. Downstream obligations can include both a minimum flow rate for downstream users and a maximum rate so as to not flood downstream areas. tjr From aleax at mac.com Wed Sep 12 12:43:57 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 12 Sep 2007 09:43:57 -0700 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <1i4bjb8.63ihk49vs6c8N%aleax@mac.com> Message-ID: <1i4bm7a.1s51u591kreqe4N%aleax@mac.com> Chris Mellon wrote: ... > > Actually you could do the "magic first-parameter insertion" just when > > returning a bound or unbound method object in the function's __get__ > > special method, and that would cover all of the technical issues you ... > This would mean that mixing functions and methods would have to be > done like you do it in C++, with lots of careful knowledge and > inspection of what you're working with. Not particularly -- it would not require anything special that's not required today. > What would happen to stuff > like inspect.getargspec? It would return the signature of the function, if asked to analyze a function, and the signature of the method, if asked to analyze a method. Not exactly rocket science, as it happens. > Besides, if self isn't in the argument spec, you know that the very > next thing people will complain about is that it's not implicitly used > for locals, Whether 'self' needs to be explicit as a function's first argument, and whether it needs to be explicit (as a "self." ``prefix'') to access instance variables (which is what I guess you mean here by "locals", since reading it as written makes zero sense), are of course separate issues. > and I'll punch a kitten before I accept having to read > Python code guessing if something is a global, a local, or part of > self like I do in C++. Exactly: the technical objections that are being raised are bogus, and the REAL objections from the Python community boil down to: we like it better the way it is now. Bringing technical objections that are easily debunked doesn't _strengthen_ our real case: in fact, it _weakens_ it. So, I'd rather see discussants focus on how things SHOULD be, rather than argue they must stay that way because of technical difficulties that do not really apply. The real advantage of making 'self' explicit is that it IS explicit, and we like it that way, just as much as its critics detest it. Just like, say, significant indentation, it's a deep part of Python's culture, tradition, preferences, and mindset, and neither is going to go away (I suspect, in fact, that, even if Guido somehow suddenly changed his mind, these are issues on which even he couldn't impose a change at this point without causing a fork in the community). Making up weak technical objections (ones that ignore the possibilities of __get__ or focus on something so "absolutely central" to everyday programming practice as inspect.getargspec [!!!], for example;-) is just not the right way to communicate this state of affairs. Alex From thanosv at gmail.com Tue Sep 18 09:22:51 2007 From: thanosv at gmail.com (thanosv at gmail.com) Date: Tue, 18 Sep 2007 06:22:51 -0700 Subject: Looking for web software in Python. In-Reply-To: References: Message-ID: <1190121771.527196.193960@50g2000hsm.googlegroups.com> On Sep 17, 9:53 pm, Kevin Ar18 wrote: > Are any of the following pieces of web software available in Python (under a non-copyleft license like BSD or MIT or Python license)? > > Mailing list - with web accessable archive and list maintenance. > Source control > Wiki System > > Again, only non-copyleft licenses like MIT, BSD, or public domain. > > Or would I be better off with PHP? > > BTW, does anyone know where that project is that was working on a forum made with Python? > _________________________________________________________________ > More photos; more messages; more whatever - Get MORE with Windows Live? Hotmail?. NOW with 5GB storage.http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_m... Mailman and Trac cover your needs. From ldo at geek-central.gen.new_zealand Sat Sep 1 02:44:30 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 18:44:30 +1200 Subject: So what exactly is a complex number? References: <451mq4-les.ln1@ozzie.tundraware.com> <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> Message-ID: In message , Roy Smith wrote: > In article , > Lawrence D'Oliveiro wrote: > >> In message <46d89ba9$0$30380$9b4e6d93 at newsspool4.arcor-online.net>, >> Wildemar Wildenburger wrote: >> >> > Tim Daneliuk wrote: >> >> >> >> One of the most common uses for Complex Numbers is in what are >> >> called "vectors". In a vector, you have both an amount and >> >> a *direction*. For example, I can say, "I threw 23 apples in the air >> >> at a 45 degree angle". Complex Numbers let us encode both >> >> the magnitude (23) and the direction (45 degrees) as a "number". >> >> >> > 1. Thats the most creative use for complex numbers I've ever seen. Or >> > put differently: That's not what you would normally use complex numbers >> > for. >> >> But that's how they're used in AC circuit theory, as a common example. > > But, if I talk about complex impedance in an AC circuit, I'm measuring two > fundamentally different things; resistance and reactance. One of these > consumes power, the other doesn't. There is a real, physical, difference > between these two things. When I talk about having a pole in the > left-hand plane, it's critical that I'm talking about negative values for > the real component. I can't just pick a different set of axis for my > complex plane and expect things to still make sense. In other words, there is a preferred coordinate system for the vectors. Why does that make them any the less vectors? From erik at myemma.com Sat Sep 15 12:09:05 2007 From: erik at myemma.com (Erik Jones) Date: Sat, 15 Sep 2007 11:09:05 -0500 Subject: Python 3K or Python 2.9? In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> Message-ID: <9AA6015D-67C7-4D4D-A039-BFBB04607E50@myemma.com> On Sep 14, 2007, at 11:54 PM, David Trudgett wrote: > TheFlyingDutchman writes: > >> The confusing way about the current Python method when you first >> encounter it is >> why is "self" being passed in when you write the function but not >> when you call it. If the compiler is smart enough to know that >> >> a = MyClass() >> a.SomeFunction(12) >> >> SomeFunction() has a "self" implicitly added to the parameter >> list, it >> seems that it should be smart enough to know that a function defined >> in a class has a "self" implicitly added to the parameter list. > > Several languages use the "object.method(args)" form, which is > syntactic > sugar for "method(object, other_args)" which Ada, for instance, uses. > Knowing this clears up half the confusion (the object /is/ passed as a > parameter whichever syntax is used). > > The other half of the confusion is cleared up by considering that > Python methods are ordinary functions that don't magically "know" in > which "class" context they are executing: they must be told via the > first parameter. Yes, that is really the crux of the issue, though. While the former may be syntactic sugar for the latter, once any syntactic sugar has become prevalent enough, it becomes the expected norm and the latter becomes clutter or, at best, awkward. It's something that really just takes a little use until you get to the point where you don't usually think of it but, every so often, the thought creeps in. I'm not complaining, just pointing out if you step out of this particular box, you'll realize that it really is a pointless one. Saying, "because that's how Python does it" may be the only valid reason, but that argument is about on par with a six year old's "just because...". Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From rave247 at seznam.cz Thu Sep 6 14:50:09 2007 From: rave247 at seznam.cz (=?us-ascii?Q?rave247=20rave247?=) Date: Thu, 06 Sep 2007 20:50:09 +0200 (CEST) Subject: =?us-ascii?Q?Re=3A=20Getting=20original=20working=20directory?= In-Reply-To: <1189102614.459515.206700@57g2000hsv.googlegroups.com> Message-ID: <1658.1882-17889-484690911-1189104609@seznam.cz> > One of the best portable ones that I've seen used is this: > > os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),'.')) This is not working. Please look at this code: import os import sys x = os.getcwd() os.chdir("\whatever") y = #here I don't know. This code is not working: os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),'.')) if x == y: print 'This is what I need' > > I've used it myself and it works for my needs. > > Mike > From bj_666 at gmx.net Tue Sep 25 07:34:46 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Sep 2007 11:34:46 GMT Subject: Inserting an element into existing xml file References: <1190712485.761290.136570@50g2000hsm.googlegroups.com> <46F8E0E2.3050602@web.de> <1190716205.955284.220810@n39g2000hsh.googlegroups.com> Message-ID: <5lsa2mF8691tU2@mid.uni-berlin.de> On Tue, 25 Sep 2007 03:30:05 -0700, Anand wrote: > I'm Afraid to say, I can't use lxml or elementTree as it requires many > legal approvals and there is high chances of not getting it through. In what environment is it hard to get something BSD licensed through!? Ciao, Marc 'BlackJack' Rintsch From roy at panix.com Tue Sep 4 08:28:20 2007 From: roy at panix.com (Roy Smith) Date: Tue, 04 Sep 2007 08:28:20 -0400 Subject: So what exactly is a complex number? References: Message-ID: In article , Steve Holden wrote: > Roy Smith wrote: > > Boris Borcic wrote: > >> Complex numbers are like a subclass of real numbers > > > > I wouldn't use the term "subclass". It certainly doesn't apply in the same > > sense it applies in OOPLs. For example, you can't say, "All complex > > numbers are real numbers". In fact, just the opposite. > > > > But, it's equally wrong to say, "real numbers are a subclass of complex > > numbers", at least not if you believe in LSP > > (http://en.wikipedia.org/wiki/Liskov_substitution_principle). For example, > > it is true that you can take the square root of all complex numbers. It is > > not, however, true that you can take square root of all real numbers. > > > That's not true. I suspect what you are attempting to say is that the > complex numbers are closed with respect to the square root operation, > but the reals aren't. Yes, that's what I was trying to say. > I don't think "subclass" has a generally defined meaning in mathematics That may be true, but this is a programming newsgroup, so I was using a programming sort of definition. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Sep 17 14:14:46 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 17 Sep 2007 20:14:46 +0200 Subject: =?ISO-8859-1?Q?I=B4m?= trying to desenvolve a site in python References: <1190051850.198096.258890@o80g2000hse.googlegroups.com> Message-ID: <5l7uglF6kto9U1@mid.individual.net> Andre P.S Duarte wrote: > I?m trying to desenvolve a site in python. What does "desenvolve" mean? By "site", do you mean a web site? Regards, Bj?rn -- BOFH excuse #247: Due to Federal Budget problems we have been forced to cut back on the number of users able to access the system at one time. (namely none allowed....) From eduardo.padoan at gmail.com Thu Sep 27 23:25:35 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Fri, 28 Sep 2007 00:25:35 -0300 Subject: Python 3.0 migration plans? In-Reply-To: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> Message-ID: On 9/27/07, TheFlyingDutchman wrote: > It seems that Python 3 is more significant for what it removes than > what it adds. > > What are the additions that people find the most compelling? - dict.items(), .values() and .keys() returns "dict views", and the .iter*() removal http://www.python.org/dev/peps/pep-3106/ - the new super() http://www.python.org/dev/peps/pep-3135/ etc... -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From dariusjack2006 at yahoo.ie Sat Sep 22 13:53:24 2007 From: dariusjack2006 at yahoo.ie (http://members.lycos.co.uk/dariusjack/) Date: Sat, 22 Sep 2007 10:53:24 -0700 Subject: Who can develop the following Python script into working application ? In-Reply-To: References: <1190334828.210230.293980@50g2000hsm.googlegroups.com> <1190372423.768184.60080@19g2000hsx.googlegroups.com> <5lho31F84jgjU1@mid.uni-berlin.de> <1190419744.390216.19040@w3g2000hsg.googlegroups.com> <5lk9e0F8leeeU1@mid.uni-berlin.de> Message-ID: <1190483604.065498.325530@r29g2000hsg.googlegroups.com> On Sep 22, 4:25 pm, Andrey Khavryuchenko wrote: > DBR> And as you said yourself: > > DBR> """ > DBR> Frankly speaking I would prefer to pay for your kind assistance > DBR> as it may take me to much time to learn some Python and understand the > DBR> following script. > DBR> """ > > DBR> Now, again:http://www.guru.com/There you can get devlopers for > DBR> money. So what again is your problem? > > Actually, I am a python (and django) developer, looking for a contract, > owning Nokia 770 and contacted original poster with no response. > > -- > Andrey V Khavryuchenko http://a.khavr.com/ > Chytach - unflood your feedshttp://www.chytach.com/ > Software Development Companyhttp://www.kds.com.ua/ Thanks Andrey, if you mean having emailed me before. I really sorry having to tell that I haven't got any email from you. Don't use Reply to author feature by Google Groups as any such email is not sent from your mailbox and you don't have a copy of it. Just read my e-mail and email me directly from your mailbox not Google Groups. At some groups Google diabled this option to contact original poster personally and even poster's email adresss is not avaliable. Thanks for your interest. Darius From bdesth.quelquechose at free.quelquepart.fr Thu Sep 27 14:43:59 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 27 Sep 2007 20:43:59 +0200 Subject: True of False In-Reply-To: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> Message-ID: <46fbfa1b$0$8896$426a74cc@news.free.fr> koutoo at hotmail.com a ?crit : > I tried writing a true and false If statement and didn't get > anything? I read some previous posts, but I must be missing > something. I just tried something easy: > > a = ["a", "b", "c", "d", "e", "f"] > > if "c" in a == True: > Print "Yes" > > When I run this, it runs, but nothing prints. What am I doing wrong? See other answers for the details. Anyway, since '"c" in a' is already a boolean expression, testing the result of the evaluation of this expression against a boolean is a pure waste of time. The usual idiom - and this is definitively not Python-specific - is: if "c" in a: print "Yes" Also, in Python (and in some other languages too), there's a notion of "something" vs "nothing" - where, in a boolean context, "something" evals to true and "nothing" to false. wrt/ Python, the empty string, an empty container (list, tuple, dict, set etc), numerical zero's (int or float), and of course the None object all eval to false, and most other objects eval to true. From rshepard at nospam.appl-ecosys.com Thu Sep 27 20:13:16 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 28 Sep 2007 00:13:16 GMT Subject: Importing Module To Use Variables In A Second Module References: Message-ID: On 2007-09-27, Steve Holden wrote: > Self-evidently you are *not* creating the variables you think you are in > the variablePage module. Have you tried an interactive test? Try this at > the interpreter prompt: > > >>> import variablePage > >>> dir(variablePage) > > and you will see exactly what names the module is defining in its > namespace. You could also try > > >>> variablePage.__file__ > > to make sure that you are importing the module you think you are. Steve, Many thanks. I _think_ the problem is that the wxPython objects are not instatiated when I'm trying to access the variables. Since they are instance variables, they just don't exist yet. Learning just when wxPython objects are instantiated is something I've just begun to do. Rich From george.sakkis at gmail.com Sat Sep 22 20:45:22 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Sep 2007 00:45:22 -0000 Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <46f57841$1$15333$4c368faf@roadrunner.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> <1190472612.942736.325850@w3g2000hsg.googlegroups.com> <46f57841$1$15333$4c368faf@roadrunner.com> Message-ID: <1190508322.254185.118740@r29g2000hsg.googlegroups.com> On Sep 22, 3:29 pm, Carl Banks wrote: > On Sat, 22 Sep 2007 14:50:12 +0000, Paddy wrote: > > Sorry Carl, > > I think *you* may not have much need for bitwise operators but others, > > including myself do. No matter what the usage found, I would think > > replacing bitwise operators by function calls a retrograde step. > > Well, if people are going to take the suggestion this personally, maybe > that's reason enough not to bother. > > Carl Banks If you want to push it further, one argument could be along the lines of "ok, apparently bit fiddling is important for some classes of problems but so are regular expressions. Are bit operations so frequent and/or important to grant them around a dozen of operators while there are none for regexps ?" George From sajmikins at gmail.com Wed Sep 12 13:22:17 2007 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 12 Sep 2007 17:22:17 -0000 Subject: Tkinter pack difficulty Message-ID: <1189617737.700363.187450@g4g2000hsf.googlegroups.com> Hi all, I realize this is more of a Tk question than a python one, but since I'm using python and don't know Tcl/Tk I figured I'd ask here first before bugging the Tcl folks. I am having a terrible time trying to get a pack() layout working. I have three frames stacked top to bottom and stretching across the master window from edge to edge. Crude ASCII Art rendition of the frames: ============ | header | ------------ | body | ------------ | log | ============ I want the header and log frames to have a fixed height (and stick to the top and bottom, respectively, of the master frame) and the body frame to expand to fill the rest of the space, for instance if the window is maximized. Here is a simple script that /almost/ does what I want. I've been tweaking the pack() options for three hours and I just can't seem to get the effect I want. This /can't/ really be this hard can it? If you run the script, be aware that since there are only frame widgets the window will initially be very very tiny. If you expand or maximize the window you'll see a thin black frame at the top, yay, a thin white frame at the bottom, yay, but the middle grey "body" frame will NOT span the Y axis, boo. It's there, and stretches from side to side, but it refuses to stretch top to bottom. Adding a widget (say, a Text) doesn't help, the light grey non-frame rectangles remain. My investigations seem to indicate that the light grey bars are part of something the Tk docs call a "parcel" that each slave widget gets packed into. Apparently the "header" and "log" frames don't use their entire parcels, but I don't know how to get the parcels themselves to "shrinkwrap" to the size of the actual Frame widgets. In any event, my head's sore and I'm just about ready to take out some graph paper and use the grid() layout manager instead. But I really want the automatic resizing that the pack() manager will do, rather than the static layout grid() will give me. Any thoughts or advice? Thanks in advance, ~Simon # Tkinter script from Tkinter import * t = Tk() header = Frame(t, bg="black", height=10) header.pack(expand=1, fill=X, side=TOP, anchor=N) body = Frame(t, bg="grey") body.pack(expand=1, fill=BOTH, anchor=CENTER) log = Frame(t, bg="white", height=10) log.pack(expand=1, fill=X, side=BOTTOM, anchor=S) t.mainloop() From __peter__ at web.de Thu Sep 13 02:19:09 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Sep 2007 08:19:09 +0200 Subject: Search path for python script References: <1189633230.265179.58780@19g2000hsx.googlegroups.com> Message-ID: Am Wed, 12 Sep 2007 14:40:30 -0700 schrieb grt: > I'm new to python, running it under cygwin. This must be easy but I > haven't figured it out. I'm trying to run a script by typing: > > python test.py > > where test.py is in a directory I've added to PYTHONPATH, but test.py > is not found. Perhaps PYTHONPATH only applies to modules imported > within a script. I didn't notice an option to python to search the > standard path, like Perl -S. > > How is this done? python -m test Peter From zzbbaadd at aol.com Fri Sep 28 14:40:03 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 11:40:03 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> Message-ID: <1191004803.604547.213280@o80g2000hse.googlegroups.com> On Sep 28, 11:16 am, Jean-Paul Calderone wrote: > On Fri, 28 Sep 2007 11:04:39 -0700, TheFlyingDutchman wrote: > > [snip] > > >In this case I asked it as part of the original question and it was > >ignored. I have programmed in C and C++ and a little Pascal many years > >ago. I don't remember anything about Higher Order Functions and would > >like to see exactly how you do it and to verify the contention. > > Perhaps you could do a bit of independent research. Then your messages > to the group could contain more thoughtful questions and responses. > But you miss the fact that I am providing value to the group by providing unthoughtful questions and unthoughtful responses. By having most of the pocket protectors being thrown at me, I provide a diversion that allows others to speak more freely and without fear of reproach. From robin at reportlab.com Fri Sep 21 07:08:57 2007 From: robin at reportlab.com (Robin Becker) Date: Fri, 21 Sep 2007 12:08:57 +0100 Subject: Odd files; just left behind? In-Reply-To: <46f3a032$0$26141$426a74cc@news.free.fr> References: <878x725ts7.fsf@pobox.com> <46F191DF.7000908@jessikat.plus.net> <46f2bd9b$0$20143$426a74cc@news.free.fr> <46f3a032$0$26141$426a74cc@news.free.fr> Message-ID: <46F3A649.6060703@chamonix.reportlab.co.uk> Bruno Desthuilliers wrote: ........ >> >>> >> >> it would seem simpler to have the .so files inside the site-packages and >> there's the question of why this folder has to be obfuscated (name >> starts with .). Even if these files are "resources" why should they be >> assumed to belong to the user? > > Notice that you did install your lib/python in /myhome, not in /usr[/local] yes, so should I then assume that the root installs will put all the .so files in /usr/local/lib/.python-eggs? In fact when I look at my root installed pythons they seem quite happy to put the _mysql.so underneath site-packages. I suspect that if I just installed from source I'd get that behaviour, but the egg stuff is different. > > (snip) >> Just another nonsense from the eggworld > > Or just another example of not reading the FineManual(tm) ? well I didn't write the installer or the associated egg setup. The egg things are supposed to do the right thing, but perhaps they're too difficult for the egg layers. -- Robin Becker From Martin.Drautzburg at web.de Tue Sep 11 15:08:07 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Tue, 11 Sep 2007 21:08:07 +0200 Subject: Lost in __setstate__() in C++ and swig Message-ID: <1884096.5YeUtxM9vj@beaureve.gmx.net> I am trying to cPickle/unpickle a C++ extension class with some private data members. I wrote __getstate__() and __setstate__ in C++ (I have to, due to the private data). Pickling writes the following file: ccopy_reg _reconstructor p1 (cpyramid MidiBytes p2 c__builtin__ object p3 NtRp4 (S'some unknown MidiBytes' I1 I2 I3 tb. But when unpickling I get the following error TypeError: in method 'MidiBytes___setstate__', argument 1 of type 'pyramid::MidiBytes *' I debugged the swig wrapper and indeed the wrapper is called with just one tuple argument. No object seems to be present at the time. All the examples I've seen use python functions for __getstate__ and __setstate__ and it seems to me that the object itself is already there when __setstate__ is called. In a moment of dispair I declared __setstate__() static and have it create and return a MidiBytes object. MidiBytes *MidiBytes:: __setstate__ (PyObject * aTuple) { return new MidiBytes(); } Then unpickling no longer complains about "argument 1", but the unpickled object does not work >>> nn = cPickle.load(FILE) >>> nn.len() Traceback (most recent call last): File "", line 1, in ? File "/usr/src/sound.d/pyramid/pyramid.py", line 618, in len return _pyramid.MidiBytes_len(*args) TypeError: in method 'MidiBytes_len', argument 1 of type 'pyramid::MidiBytes *' whereas the original object behaves well >>> n = pyramid.MidiBytes() >>> n.len() 0 Am I missing something obvious ? From Herman.Schultz at gmail.com Sun Sep 2 15:26:27 2007 From: Herman.Schultz at gmail.com (herman) Date: Sun, 02 Sep 2007 19:26:27 -0000 Subject: how can I find out the process ids with a process name Message-ID: <1188761187.522146.192380@y42g2000hsy.googlegroups.com> Hi, I would like to find out all the process id with the process name 'emacs'. In the shell, i can do this: $ ps -ef |grep emacs root 20731 8690 0 12:37 pts/2 00:00:09 emacs-snapshot-gtk root 25649 25357 0 13:55 pts/9 00:00:05 emacs-snapshot-gtk rtp.c root 26319 23926 0 14:06 pts/7 00:00:04 emacs-snapshot-gtk stressTestVideo.py root 26985 1 0 14:15 ? 00:00:01 /usr/bin/emacs-snapshot- gtk root 27472 21066 0 14:23 pts/5 00:00:00 grep emacs and I can see the process id is 20731, 25649, etc, etc. But now I would like to do the programmically in my python script. I know I can use ' os.system(cmd)' to execute the command 'ps -ef | grep emacs', but how can I pipe the output of my 'ps -ef | grep emacs' to my python script and then run a regression expression with it to get the process Ids? Thank you. From spam at spam.com Tue Sep 4 16:50:36 2007 From: spam at spam.com (daz.diamond) Date: Tue, 04 Sep 2007 20:50:36 GMT Subject: pyPortMidi In-Reply-To: <1188885640.409493.147160@w3g2000hsg.googlegroups.com> References: <1188885640.409493.147160@w3g2000hsg.googlegroups.com> Message-ID: Cappy2112 wrote: > Does anyone here use pyPortMidi- in particular for Sending/receiving > sysex? > I'm starting to, but then I lurk more than I know ... daz From wolf_tracks at invalid.com Tue Sep 18 10:29:41 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Tue, 18 Sep 2007 14:29:41 GMT Subject: Tutorial or Example (or Tutorial) of Using Canvas to Produce a Plot Message-ID: I'm looking for an example with canvas that produces, say, a complete x-y plot of some data. By that I mean, it should do something like the following: 1. Produce x-y axes. The x-axis should be blue and the y-axis should be green 2. Put a label on each axis (vertical and horizontal text) 3. Plot some data (3 points is enough) and connect the points with a dashed line. Color one line red and the other green. 4. Position a title at some arbitrary place inside the x-y axes. That is, not just a title above and outside the top of the x-y area. I just want to see how it's done. I'm not interested in a full-blown canned class or widget that does an x-y plot given some data. If not exactly the above, then something like it that gives me some idea of how to do such a graph. Maybe there's a tutorial that does something like this as an example. -- Wayne Watson (Nevada City, CA) Web Page: From DustanGroups at gmail.com Sun Sep 16 08:17:17 2007 From: DustanGroups at gmail.com (Dustan) Date: Sun, 16 Sep 2007 12:17:17 -0000 Subject: Python statements not forcing whitespace is messy? In-Reply-To: References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> <1189890755.870694.29790@r29g2000hsg.googlegroups.com> Message-ID: <1189945037.621620.267040@22g2000hsm.googlegroups.com> On Sep 15, 5:11 pm, James Stroud wrote: > Steve Holden wrote: > > I don't know why you have a bug up your ass about it, as the > > Americans say. > > I think most Americans say "wild hare up your ass". We do not, in fact, > say "wild hair up your ass". Many of us can testify that a hair up one's > ass would be nothing terribly unusual and would go completely unnoticed > under most circumstances. > > Also, some Americans erroneously say "hair's breath", and others think > they mean "hare's breath" (which might be tiny, but diffuses quickly to > theoretically infinite volume). In reality, however, they mean "hair's > breadth"--which is quite small indeed! For instance, a hair's breadth is > far smaller than a hare's breath (even at the exact moment of respiration). > > James Funny... I have never heard any of those expressions. I guess I need to get out more. From jstroud at mbi.ucla.edu Thu Sep 13 16:20:29 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 13 Sep 2007 13:20:29 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189664832.876539.86800@k79g2000hse.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> Message-ID: Mark Summerfield wrote: > - If an item is inserted it is put in the right place (because the > underlying data structure, b*tree, skiplist or whatever is > intrinsically ordered by < on the key) +1 for all your suggestions below, but -1 for the above. You suggest that myOrderedDict['key'] = value would place it in the dictionary in sorted order depending on 'key'. More natural to some of us (or maybe its just me) would be to append the key/value pair to the end of items. My Argument: The problem with inserting at sorted position is the assumption that the dict is already sorted, but maybe I want the key ordering to reflect something arbitrary, like a database, etc (e.g. 'Last', 'First', 'MI'). So now I assign to an OrderedDict that already has these latter 3 keys: myOrderedDict['Favorite Color'] = 'chartruse' Where does it go? Answer: it probably depends on how the underlying sorter works and (even worse) the internal state of the sorter's data structure. So, my intuition is that SortedDict behavior should be kept distinct from OrderedDict behavior. > - Extra methods > key_at(index : int) -> key > item_at(index : int) -> (key, value) > value_at(index : int) -> value > set_value_at(index : int, value) # no return value necessary but > maybe key if convenient > od[x:y:z] -> list of values ordered by key # can read a slice but > not assign a slice I do not see why assigning a slice is a bad idea here. The behavior could be such: od = OrderedDict((('Last':'Smith'), ('First':'John'), ('MI':'J')) od[:1] = ['Brown'] od[:2] = ['Glotz', 'Joe'] od[:2] = ['Williams', 'Mary', 'Francis'] # <== ValueError The latter would be a phenomenon similar to unpacking a tuple of the wrong length. > and maybe > keys_for(fromindex : int, uptobutexcludingindex : int) -> ordered > list of keys Of course the naming is redundant for these in my opinion. E.g.: key_at -> key item_at -> item value_at -> value set_value_at -> set_value (not simply set) keys_for -> keys (takes optional argument(s)) James From meesters at uni-mainz.de Mon Sep 24 10:10:43 2007 From: meesters at uni-mainz.de (Christian Meesters) Date: Mon, 24 Sep 2007 16:10:43 +0200 Subject: strange behavious of the logging module? References: Message-ID: Thanks Peter and Gabriel, I see, so I should provide the application with an additional handler for the file in order to gain maximum independence of the two handlers (console & file stream). >> Also, adding %(funcName)-8s to the formatter in basigConfig does not work >> for me: instead of the functions name the level in lower case gets >> inserted >> into the logfile. > > Looks like a bug... > Well, the documentation -- as far as I understand it ;-) -- says the behaviour should be different, you two basically agree ... think I should file a report. Thanks, Christian From paddy3118 at googlemail.com Thu Sep 20 11:38:30 2007 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 20 Sep 2007 15:38:30 -0000 Subject: how to convert xml file to word document. In-Reply-To: <1190293176.702616.235480@e9g2000prf.googlegroups.com> References: <1190293176.702616.235480@e9g2000prf.googlegroups.com> Message-ID: <1190302710.518023.89960@r29g2000hsg.googlegroups.com> On Sep 20, 1:59 pm, prajwala wrote: > I want to convert xml file to a word document using python. Is > there > any built in module available? > or Is there any other way to convert xml file to word document. > Please suggest me. This is very urgent now. > > Thanks, > prajwala XML to XHTML via XSLT ? - loads of X's but I'd slip Python and elementtree in there somewhere. - Paddy. From uymqlp502 at sneakemail.com Sun Sep 2 01:44:41 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Sat, 01 Sep 2007 22:44:41 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: <1i3ryxd.g2pzgq159lt5sN%aleax@mac.com> References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> <1188585630.539835.242460@i38g2000prf.googlegroups.com> <1188592039.612652.223700@r23g2000prd.googlegroups.com> <1i3ryxd.g2pzgq159lt5sN%aleax@mac.com> Message-ID: <1188711881.370954.175830@o80g2000hse.googlegroups.com> On Sep 1, 6:51 pm, al... at mac.com (Alex Martelli) > try: > blah blah with as many return statements as you want > finally: > something that gets executed unconditionally at the end Thanks. I didn't think of that. So design by contract *is* relatively easy to use in Python already. The main issue, I suppose, is one of aesthetics. Do I want to use a lot of explicit function calls for pre and post-conditions and "try/ finally" blocks in my code to get DbC (not to mention a global variable to enable or disable it)? I suppose if I want it badly enough, I will. But I also happen to be a bit obsessive about the appearance of my code, and this does complicate it a bit. The nice thing about having it in the doc string (as per PEP 316) is that, while it is inside the function, it is also separate from the actual code in the function. I like that. As far as I am concerned, the self-test code shouldn't be tangled up with the primary code. By the way, I would like to make a few comments about the "reliability" of Python code. Apparently I offended you the other day by claiming or implying that Python code is inherently unreliable. I think it is probably possible to write very reliable code in Python, particularly for small to medium sized applications, but you probably need top notch software engineers to do it. And analyzing code or *proving* that a program is correct is technically harder without static typing. In highly regulated safety critical domains, you need more than just reliable code; you need to *demonstrate* or *prove* the reliability somehow. I personally use Python for its clean syntax and its productivity with my time, so I am certainly not denigrating it. For the R&D work I do, I think it is very appropriate. But I did raise a few eyebrows when I first started using it. I used C++ several years ago, and I thought about switching to Ada a few years ago, but Ada just seems to be fading away (which I think is very unfortunate, but that's another story altogether). In any case, when you get right down to it, I probably don't know what the hell I'm talking about anyway, so I will bring this rambling to a merciful end. On, one more thing. I see that the line wrapping on Google Groups is finally working for me after many months. Fantastic! I can't help but wonder if my mentioning it to you a few days ago had anything to do with it. From rainwatching at gmail.com Thu Sep 6 14:44:27 2007 From: rainwatching at gmail.com (=?iso-8859-1?q?S=F6nmez_Kartal?=) Date: Thu, 06 Sep 2007 18:44:27 -0000 Subject: reload(sys) In-Reply-To: <5-WdnUzNZuwZtX3bnZ2dnUVZ_vOlnZ2d@comcast.com> References: <1188521143.421431.119100@l22g2000prc.googlegroups.com> <1188564816.430863.219560@w3g2000hsg.googlegroups.com> <1188662049.337034.58220@w3g2000hsg.googlegroups.com> <1189077209.646830.111990@19g2000hsx.googlegroups.com> <1189094496.120836.61870@o80g2000hse.googlegroups.com> <5-WdnUzNZuwZtX3bnZ2dnUVZ_vOlnZ2d@comcast.com> Message-ID: <1189104267.431534.183650@o80g2000hse.googlegroups.com> On 6 Eyl?l, 19:19, Steven Bethard wrote: > S?nmez Kartal wrote: > > I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as > > "f.write(str(xml))". At execution of that line, it gives error with > > description, configure your default encoding... > > [and later] > > >http://rafb.net/p/RfaF8215.html > > > products in the code is a list of dictionaries which are returned by > > makeProduct function. > > > I'm not typing or pasting those characters into my script. So, > > declaring an encoding didn't make it. :-( But, your code excerpt > > runned well. > Gabriel Genellina wrote: > > You should ensure that arguments to makeProduct are either: > > - unicode objects > > - ASCII strings > > > If you got them from some other place, decode the strings as soon as > > possible into unicode. Read > > to understand what's happening > > To further illustrate Gabriel's point, here is some code where I read in > some UTF8 text from a file. If you properly decode that text from UTF8, > you don't get any errors. If you forget to decode that text, you'll get > exactly the "default encoding" error you were getting before: > > >>> f = open('temp.txt', 'w') > >>> f.write(u'? and ?'.encode('utf8')) > >>> f.close() > >>> non_decoded_text = open('temp.txt').read() > >>> decoded_text = non_decoded_text.decode('utf8') > >>> import xmlbuilder > >>> builder = xmlbuilder.XMLBuilder() > >>> builder.foo = dict(bar=non_decoded_text) > >>> str(builder) > Decoding Error: You must configure default encoding > >>> builder = xmlbuilder.XMLBuilder() > >>> builder.foo = dict(bar=decoded_text) > >>> str(builder) > '\xc2\xae and > \xc2\x99' > > Note that I didn't have to do anything with the default encoding. I > simply had to decode the text file with the appropriate codec. So, > looking at your code, I'm guessing that you need to figure out where > you're reading in the "name", "url" and "image" values, and make sure > you're properly decoding that text. > > STeVe > > P.S. If you can find somewhere to file a bug report for XMLBuilder, you > really should. The error instructing you to configure the default > encoding is really just wrong. Thank you Steve for your answers and Gabriel for reminding Unicode HOWTO to me which I'm going to read tomorrow! Happy coding From pyth0nc0d3r at gmail.com Wed Sep 12 22:49:40 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Wed, 12 Sep 2007 21:49:40 -0500 Subject: Does anyone know if Python 3 will change in structure? Message-ID: The 2.x stucture is boring, would be cool if there could be some sort of spacing we could do. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajmacd at ns.sympatico.ca Tue Sep 18 19:02:38 2007 From: ajmacd at ns.sympatico.ca (Aaron J. M.) Date: Tue, 18 Sep 2007 16:02:38 -0700 Subject: Deserializing specific objects from a file Message-ID: <1190156558.313252.31000@y27g2000pre.googlegroups.com> I'm building a game and am starting to seriously think about serialization, though I haven't done much serialization before except for a few experiments with the pickle module. There are many objects that I want be able to move in and out of memory at runtime; namely the game levels. I only want one level in memory at a time, so I want to be able to unpickle specific Level objects as the player moves between levels. I would prefer my serialized objects to reside in one file. I haven't come across references that say how to do something like what I'm describing. Does anyone here know what techniques I have to employ here? Thank you, Aaron J. M. P.S. Is it *deserialize* or *unserialize*? From __peter__ at web.de Wed Sep 5 10:11:12 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 5 Sep 2007 16:11:12 +0200 Subject: python exec behaves inconsistent with respect to module imports References: <1188997944.162811.33640@r34g2000hsd.googlegroups.com> Message-ID: Am Wed, 05 Sep 2007 13:12:24 +0000 schrieb carl.dhalluin at gmail.com: > I am completely puzzled why the following exec code does not work: > > mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" > def execute(): > exec mycode > execute() > > > I get the error: > > root at devmachine1:/opt/qbase# python error1.py > Traceback (most recent call last): > File "error1.py", line 5, in ? > execute() > File "error1.py", line 4, in execute > exec mycode > File "", line 4, in ? > File "", line 3, in f > NameError: global name 'math' is not defined > Note that the following code _does_ work: > > mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" > exec mycode > I have tested this in python 2.3 and 2.4. exec breaks nested namespaces here. Essentially exec "import math" puts the "math" name into the local namespace, but "def f(): math.floor" looks up "math" in the global namespace. On the module level global and local namespace are identical >>> globals() is locals() True but inside a function they are distinct >>> def f(): return globals() is locals() ... >>> f() False A workaround is to declare "math" as global: >>> s = """ ... global math ... import math ... def f(y): print math.floor(y) ... f(3.14) ... """ >>> def execute(): ... exec s ... >>> execute() 3.0 or pass it explicitly: [new interpreter session] >>> s = """ ... import math ... def f(y, math=math): print math.floor(y) ... f(3.14) ... """ >>> def execute(): ... exec s ... >>> execute() 3.0 Peter From bj_666 at gmx.net Mon Sep 24 06:05:50 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Sep 2007 10:05:50 GMT Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <1190419720.811685.145880@r29g2000hsg.googlegroups.com> <46f6eb3d$0$32060$426a34cc@news.free.fr> <1190606861.982113.25240@d55g2000hsg.googlegroups.com> <46f786cc$0$8901$426a74cc@news.free.fr> Message-ID: <5lpgfuF95s07U3@mid.uni-berlin.de> On Mon, 24 Sep 2007 11:43:59 +0200, Bruno Desthuilliers wrote: > You already can create functions without using the def statement: > > Help on class function in module __builtin__: > > class function(object) > | function(code, globals[, name[, argdefs[, closure]]]) > | > | Create a function object from a code object and a dictionary. > | The optional name string overrides the name from the code object. > | The optional argdefs tuple specifies the default argument values. > | The optional closure tuple supplies the bindings for free variables. > | Where the heck does *this* come from? Neither Python 2.5.1 nor the 3.0alpha has this in `__builtin__`. Ciao, Marc 'BlackJack' Rintsch From jjl at pobox.com Sat Sep 22 03:18:38 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 22 Sep 2007 07:18:38 GMT Subject: Odd files; just left behind? References: <878x725ts7.fsf@pobox.com> <46F191DF.7000908@jessikat.plus.net> <46f2bd9b$0$20143$426a74cc@news.free.fr> <46f3a032$0$26141$426a74cc@news.free.fr> Message-ID: <871wcr5fsh.fsf@pobox.com> Robin Becker writes: > Bruno Desthuilliers wrote: > ........ >>> >>> >>> >>> it would seem simpler to have the .so files inside the >>> site-packages and there's the question of why this folder has to be >>> obfuscated (name starts with .). Even if these files are >>> "resources" why should they be assumed to belong to the user? >> >> Notice that you did install your lib/python in /myhome, not in /usr[/local] > > yes, so should I then assume that the root installs will put all the > .so files in /usr/local/lib/.python-eggs? No no -- the extraction of these .so files happens at *runtime*, so it has to write the files somewhere it has permission to write to. It's like RL's zipapp resource extraction feature in fact, except the resource extraction happens at runtime. See those web pages I pointed you at before. > In fact when I look at my root installed pythons they seem quite happy > to put the _mysql.so underneath site-packages. I suspect that if I > just installed from source I'd get that behaviour, but the egg stuff > is different. Not sure without all the details, but I suspect those are non-egg installs. John From erfc at caballista.org Sat Sep 8 11:57:21 2007 From: erfc at caballista.org (Art Deco) Date: Sat, 08 Sep 2007 09:57:21 -0600 Subject: What does this thread have to do with classical music, References: <7nnh7350b5h25ghocra72b23mmsnnkj8bh@4ax.com> <46957ef1$0$10227$8f2e0ebb@news.shared-secrets.com> <46963170$0$97261$892e7fe2@authen.yellow.readfreenews.net> <46981df7$0$12095$8f2e0ebb@news.shared-secrets.com> <46990784$0$97223$892e7fe2@authen.yellow.readfreenews.net> <4699297c$0$4706$4c368faf@roadrunner.com> <140720071431044860%erfc@caballista.org> <46a3a1a7$0$15115$8f2e0ebb@news.shared-secrets.com> <220720072148091069%erfc@caballista.org> <46a5385d$0$4832$8f2e0ebb@news.shared-secrets.com> <250720071834457296%erfc@caballista.org> <46aceaa5$0$13281$8f2e0ebb@news.shared-secrets.com> <290720071853200863%erfc@caballista.org> <46b12539$0$4807$8f2e0ebb@news.shared-secrets.com> <010820072033374341%erfc@caballista.org> <46c63474$0$4844$8f2e0ebb@news.shared-secrets.com> <180820070841431634%erfc@caballista.org> <46c90727$0$14433$8f2e0ebb@news.shared-secrets.com> <200820071919337538%erfc@caballista.org> <46e1d2a4$0$5075$8f2e0ebb@news.shared-secrets.com> Message-ID: <080920070957212604%erfc@caballista.org> ah wrote: >Art Deco wrote: >> ah wrote: >>>Art Deco wrote: >>>> ah wrote: >>>>>Art Deco wrote: >>>>>> ah wrote: >>>>>>>Art Deco wrote: >>>>>>>> ah wrote: >>>>>>>>>Art Deco wrote: >>>>>>>>>> ah wrote: >>>>>>>>>>>Art Deco wrote: >>>>>>>>>>>> ah wrote: >>>>>>>>>>>>>Art Deco wrote: >>>>>>>>>>>>>> Who wrote? >>>>>>>>>>>>>> >>>>>>>>>>>>>> >>>>>>>>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>>>>>>>> >>>>>>>>>>>>>>>What does that have to do with classical music, snuhwolf? >>>>>>>>>>>>>> >>>>>>>>>>>>>> How many more times will you be asking the same tired, lame >>>>>>>>>>>>>> questions, >>>>>>>>>>>>>> Tholen? >>>>>>>>>>>>> >>>>>>>>>>>>>Till 2056? >>>>>>>>>>>> >>>>>>>>>>>> At that point, he will have made the Thirty Years Pset War look >>>>>>>>>>>> like >>>>>>>>>>>> 1967 in the Sinai. >>>>>>>>>>> >>>>>>>>>>>It must have been Hell to keep a garden during those times. >>>>>>>>>>> >>>>>>>>>>>Did they all eat jerky, or what? >>>>>>>>>> >>>>>>>>>> Worse -- worm-laden hardtack. >>>>>>>>> >>>>>>>>>Luxury! >>>>>>>>> >>>>>>>>>Why, I remember when I was a lad . . . we used to watch the local >>>>>>>>>churls >>>>>>>>>across the fences eating that well. >>>>>>>>> >>>>>>>>>We only had millings (and (occasionally) water) on Tuesdays and >>>>>>>>>Fridays. >>>>>>>> >>>>>>>> Grog and hardtack, life is good! >>>>>>> >>>>>>>?Viva la basura! >>>>>> >>>>>> Vivat les ordures! >>>>> >>>>>Vivara los trunctiato! >>>> >>>> das Leben ist gut! >>> >>>de Handel esta disgustipado! >> >> la vita ? buona! > >que grupo da merda! het leven is goed! -- Official Overseer of Kooks and Saucerheads for alt.astronomy Wee Davie Tholen is a grade-school lamer Trainer and leash holder of: Honest "Clockbrain" John nightbat "fro0tbat" of alt.astronomy Tom "TommY Crackpotter" Potter "Classic erroneous presupposition. Others developed websites so that they could have the Last Word, Deco. In the newsgroups, I could counter their lies." --David Tholen From ricaraoz at gmail.com Wed Sep 5 06:03:09 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 05 Sep 2007 07:03:09 -0300 Subject: REGULAR EXPRESSION In-Reply-To: <1188968632.077355.199740@y42g2000hsy.googlegroups.com> References: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> <1188968632.077355.199740@y42g2000hsy.googlegroups.com> Message-ID: <46DE7EDD.7080705@bigfoot.com> AniNair wrote: > On Sep 5, 4:35 am, Ricardo Ar?oz wrote: >> Steve Holden wrote: >>> AniNair wrote: >>>> hi.. I am trying to match '+ %&/-' etc using regular expression in >>>> expressions like 879+34343. I tried \W+ but it matches only in the >>>> beginning of the string Plz help Thanking you in advance... >>> Perhaps you could give a few example of strings that should and >>> shouldn't match? It isn't clear from your description what pattern you >>> are trying to find. >>> regards >>> Steve >> If it's operations between two numbers try : >> r'([\d.]+?)\s*([-+/*%&])([\d.]+)' >> It will give you 3 groups, first number, operation and second number >> (caveat emptor). > > > Hi.. Thanks alot for finding time to help a beginner like me. What I > am trying to do is validate the input i get. I just want to take > numbers and numbers only. So if the input is 23+1 or 2/3 or 9-0 or > 7/0 , I want to find it using reg exp. I know there are other ways to > do this... but i thought i will try this as i need to learn reg exp. I > tried \D+ , \W+, and \D+|\W+ .. Thanks once again... > Well \d will match a number and '.' inside [] will match a dot ;) so if you want only integer numbers ([\d.]*) should be replaced with (\d+) Only problem with the expression I sent is that it will match a number with more than one dot. HTH From aleax at mac.com Wed Sep 12 19:23:08 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 12 Sep 2007 16:23:08 -0700 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> <1i4bnbp.1l8sr3mjdojghN%aleax@mac.com> <1189630374.506503.190690@r34g2000hsd.googlegroups.com> Message-ID: <1i4c3p7.1o7gssi1ws1xa2N%aleax@mac.com> Carl Banks wrote: ... > How about this? The decorator could generate a bytecode wrapper that > would have the following behavior, where __setlocal__ and > __execute_function__ are special forms that are not possible in > Python. (The loops would necessarily be unwrapped in the actual > bytecode.) I'm not entirely sure how you think those "special forms" would work. Right now, say, if the compiler sees somewhere in your function z = 23 print z it thereby knows that z is a local name, so it adds a slot to the function's locals-array, suppose it's the 11th slot, and generates bytecode for "LOAD_FAST 11" and "STORE_FAST 11" to access and bind that 'z'. (The string 'z' is stored in f.func_code.co_varnames but is not used for the access or storing, just for debug/reporting purposes; the access and storing are very fast because they need no lookup). If instead it sees a "print z" with no assignment to name z anywhere in the function's body, it generates instead bytecode "LOAD_GLOBAL `z`" (where the string `z` is actually stored in f.func_code.co_names). The string (variable name) gets looked up in dict f.func_globals each and every time that variable is accessed or bound/rebound. If the compiler turns this key optimization off (because it sees an exec statement anywhere in the function, currently), then the bytecode it generates (for variables it can't be sure are local, but can't be sure otherwise either as they MIGHT be assigned in that exec...) is different again -- it's LOAD_NAME (which is like LOAD_GLOBAL in that it does need to look up the variable name string, but often even slower because it needs to look it up in the locals and then also in the globals if not currently found among the locals -- so it may often have to pay for two lookups, not just one). So it would appear that to make __setlocal__ work, among other minor revolutions to Python's code objects (many things that are currently tuples, built once and for all by the compiler at def time, would have to become lists so that __setlocal__ can change them on the fly), all the LOAD_GLOBAL occurrences would have to become LOAD_NAME instead (so, all references to globals would slow down, just as they're slowed down today when the compiler sees an exec statement in the function body). Incidentally, Python 3.0 is moving the OTHER way, giving up the chore of dropping optimization to support 'exec' -- the latter will become a function instead of a statement and the compiler will NOT get out of its way to make it work "right" any more; if LOAD_NAME remains among Python bytecodes (e.g. it may remain in use for class-statement bodies) it won't be easy to ask the compiler to emit it instead of LOAD_GLOBAL (the trick of just adding "exec 'pass'" will not work any more;-). So, "rewriting" the bytecode on the fly (to use LOAD_NAME instead of LOAD_GLOBAL, despite the performance hit) seems to be necessary; if you're willing to take those two performance hits (at decoration time, and again each time the function is called) I think you could develop the necessary bytecode hacks even today. > This wouldn't be that much slower than just assigning local variables > to locals by hand, and it would allow assignments in the > straightforward way as well. The big performance hit comes from the compiler having no clue about what you're doing (exactly the crucial hint that "assigning local variables by hand" DOES give the compiler;-) > There'd be some gotchas, so extra care is required, but it seems like > for the OP's particular use case of a complex math calculation script, > it would be a decent solution. Making such complex calculations even slower doesn't look great to me. > I understand where the OP is coming from. I've done flight > simulations in Java where there are lot of complex calculations using > symbols. This is a typical formula (drag force calculation) that I > would NOT want to have to use self.xxx for: > > FX_wind = -0.5 * rho * Vsq * Sref * (C_D_0 + C_D_alphasq*alpha*alpha + > C_D_esq*e*e) If ALL the names in every formula always refer to nothing but instance variables (no references to globals or builtins such as sin, pi, len, abs, and so on, by barenames) then there might be better tricks, ones that rely on that knowledge to actually make things *faster*, not slower. But they'd admittedly require a lot more work (basically a separate specialized compiler to generate bytecode for these cases). Alex From steve at holdenweb.com Sat Sep 1 09:03:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Sep 2007 09:03:51 -0400 Subject: list index() (OT) In-Reply-To: <46D95EEC.2000603@bigfoot.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1cnfd31du01el95u70o8mjn9cb5r5aluiu@4ax.com> <1188631457.050512.103060@y42g2000hsy.googlegroups.com> <46D95EEC.2000603@bigfoot.com> Message-ID: Ricardo Ar?oz wrote: > Paddy wrote: >> On Sep 1, 7:57 am, "Hendrik van Rooyen" wrote: >>> "Richie Hindle" wrote: >>>> But - the word for someone who posts to the internet with the intention of >>>> stirring up trouble derives from the word for what fishermen do, not from >>>> the word for something that lives under a bridge. It derives from "trolling >>>> for suckers" or "trolling for newbies". >>> So am I right in asserting that there is a difference in pronunciation >>> of the noun and the verb? >>> >>> He is a Troll - like the excellent frolic example >>> He likes to Troll - rhymes with roll? >>> >>> - Hendrik >> No difference. A troll is a troll is a troll. >> >> :-) >> >> - Paddy. > > > BTW people , the word for what fishermen do is T R A W L and not troll > (Ha! and I'm not a native English speaker). Just read the whole thread, or use a dictionary: in fishing, trolling and trawling are two different things; the first is done with a net, the second with a line. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From jstroud at mbi.ucla.edu Thu Sep 13 20:50:06 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 13 Sep 2007 17:50:06 -0700 Subject: Extended slicing and Ellipsis - where are they used? In-Reply-To: <1189699345.436400.233460@g4g2000hsf.googlegroups.com> References: <1189699345.436400.233460@g4g2000hsf.googlegroups.com> Message-ID: Rodney Maxwell wrote: > The following are apparently legal Python syntactically: > L[1:3, 8:10] > L[1, ..., 5:-2] > > But they don't seem to work on lists: >>>> l = [0,1,2,3] >>>> l[0:2,3] > Traceback (most recent call last): > File "", line 1, in > TypeError: list indices must be integers >>>> l[...] > Traceback (most recent call last): > File "", line 1, in > TypeError: list indices must be integers > > So where is this extended slicing used? AFAICT this syntax is not used in the standard library. However, the mega-beauty of it is that you can make use of it in your own classes: py> class Bob(list): ... def __getitem__(self, i): ... try: ... return [list.__getitem__(self, j) for j in i] ... except TypeError: ... return list.__getitem__(self, i) ... py> b = Bob(xrange(15, 30)) py> b[3, 5, 7, 13] [18, 20, 22, 28] James From fredrik at pythonware.com Wed Sep 26 12:10:20 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 18:10:20 +0200 Subject: Missing documentation for ElementTree? In-Reply-To: <496954360709260850u3aed1bc3n56f92726c0c542de@mail.gmail.com> References: <496954360709251539y2511a1cbnd25c6d3a0d368d2a@mail.gmail.com> <1190783252.777675.44180@r29g2000hsg.googlegroups.com> <496954360709260850u3aed1bc3n56f92726c0c542de@mail.gmail.com> Message-ID: Robert Dailey wrote: > This is the documentation for 3.0a1? This is exactly what I was looking > for. Thank you. > > @Gabriel > Your documentation is also useful, it never occurred to me to check the > ElementTree website for documentation. Since it came with Python I > expected it to be covered by the python documentation. Thanks. the Element interface section was accidentally omitted due to a weird operator error. looks like someone has finally gotten around to fix that in the development versions. From steve at REMOVE-THIS-cybersource.com.au Sat Sep 8 13:23:09 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Sep 2007 17:23:09 -0000 Subject: How to determine the bool between the strings and ints? References: <1189182688.290480.102350@o80g2000hse.googlegroups.com> <5kdjmcF31i6hU7@mid.uni-berlin.de> <1189193206.466633.148610@r34g2000hsd.googlegroups.com> Message-ID: <13e5mjt4cklq891@corp.supernews.com> On Sat, 08 Sep 2007 12:08:16 -0300, Ricardo Ar?oz wrote: >> if type(x) == type(True): >> ... print "bool" >> ... >> bool >> >> > Or just : > >>>> a = True >>>> type(a) == int > False [snip] You know, one or two examples was probably plenty. The other six or seven didn't add anything to your post except length. Also, type testing by equality is generally not a good idea. For example: class HexInt(int): """Like built-in ints, but print in hex by default.""" def __str__(self): return hex(self) __repr__ = __str__ You should be able to use a HexInt anywhere you can use an int. But not if your code includes something like this: if type(value) == int: do_something() else: print "Not an int!" (What do you mean my HexInt is not an int? Of course it is.) Better is to use isinstance(value, int). Better still is to do duck- typing, and avoid type() and isinstance() as much as possible. -- Steven. From steve at holdenweb.com Fri Sep 28 14:07:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 14:07:05 -0400 Subject: OCBC connection In-Reply-To: <1191000128.112881.111790@r29g2000hsg.googlegroups.com> References: <1191000128.112881.111790@r29g2000hsg.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Sep 28, 9:57 am, "Sugrue, Sean" wrote: >> I'm trying to make an odbc connection to postgresql which is on a server >> using python. >> Does anyone have a code snippet to make a basic connection with a select >> query? >> >> Sean > > Sean, > > This appears to be what you're looking for: > > http://www.devx.com/opensource/Article/29071 > > See also Python Database spec and module page: > > http://www.python.org/topics/database/ > Mike: This doesn't address the ODBC part of the inquiry. I was actually going to respond saying I wasn't aware of an ODBC driver for PostgreSQL (though I'd be surprised if there wasn't one). Using the psycopg2 module, which is my preferred PostgreSQL interface module, it's easy to answer: >>> curs = conn.cursor() >>> import psycopg2 as db >>> conn = db.connect(database="pycon", user="username", password="password", host="localhost", port=5432) >>> curs = conn.cursor() >>> curs.execute("SELECT orgid, orgname FROM organization") >>> from pprint import pprint # just for neatness >>> pprint(curs.fetchall()) [(1, 'AB Strakt'), (79, 'DevIS'), ... (113, 'Test Organization'), (19, 'Holden Web LLC')] >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From duncan.booth at invalid.invalid Mon Sep 24 09:31:34 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Sep 2007 13:31:34 GMT Subject: python variable assignement References: <1190628822.472242.272900@19g2000hsx.googlegroups.com> <1190635944.655293.38290@y42g2000hsy.googlegroups.com> Message-ID: mihai wrote: > > This is the code: > > begin = select_point() > if begin == None: > return > > end = select_point() > while end != None: > record = Record(begin, end) > id = add(record) > begin = end > end = select_point() > # here (sometimes) begin has the same value (or points to the > same object) like end, the newly selected one > > Is there a way to see if the names points to the same variables or > that there are different variables with the same values? You can check whether two names refer to the same object with the 'is' operator. So you would use: if begin is end: continue to skip over any duplicate > > The problem is that the problem is more like an bug, > it happens only in certain conditions, and I have no idea why. > > I have checked the values returned by select_point() and are different > in all the cases, > so the problem is with that variables names/values. Are you sure that nothing you do can change the list of points you are iterating over: usually iteration returning unexpected duplicates is because you inserted something new into the middle of the list. A few other unrelated points: the convention is to use 'is' when checking for None, and you can reduce the number of calls to 'select_point' if you use the 'iter' function. Putting those together: begin = select_point() if begin is None: return for end in iter(select_point, None): if begin is end: continue record = Record(begin, end) id = add(record) begin = end From exhuma at gmail.com Wed Sep 19 12:24:37 2007 From: exhuma at gmail.com (exhuma.twn) Date: Wed, 19 Sep 2007 09:24:37 -0700 Subject: psycopg2 or pygresql? In-Reply-To: References: <1190214385.994370.167750@r29g2000hsg.googlegroups.com> Message-ID: <1190219077.252577.259570@19g2000hsx.googlegroups.com> On Sep 19, 5:47 pm, Steve Holden wrote: > exhuma.twn wrote: > > Plain and simple. What would you use? > > > So far I have written everything with psycopg2. One thing that annoys > > me is that I cannot easily access the column names from a query. I > > know that this is not part of the DBAPI2 so I cannot expect the model > > to suport it. > > Yes it is. > > Execute a SELECT * FROM TABLE WHERE 1=0 and then examine > cursor.description. This allows you to introspect on database structure. > > > I quite like the "mogrify" method of psycopg2 very much. It's very > > useful for debugging. > > > And before someone says: "Use the DictCursor-factory to access column > > names". Yes I can do that. But a dict does not guarantee the same > > order of keys as the columns were specified in the query. > > See below. > > > The reason: I wrote a very simple Qt-Widget (inherited from > > QTableWidget) that takes a SQL query and displays the results. And I > > would like to have the columns ordered the same way as I specified in > > the query *with* a header-label. For now I hava a method on the widget > > which takes a query, *and* a list of labels. > > > I can live with that though. Although it itches me. > > > Would pygresql solve my dilemma? Or would you rather say: "Don't use > > pygresql!" ;) > > Here's a psycopg2-based session: > > >>> curs > > >>> curs.execute("SELECT * FROM Person WHERE 1=0") > >>> curs.description > (('psnid', 23, None, 4, None, None, None), ('psnfirstname', 1043, None, > 50, None, None, None), ('psnlastname', 1043, None, 50, None, None, > None), ('psndear', 1043, None, 50, None, None, None), ('psntitle', 1043, > None, 50, None, None, None), ('psnworkphone', 1043, None, 30, None, > None, None), ('psnworkextension', 1043, None, 20, None, None, None), > ('psnhomephone', 1043, None, 30, None, None, None), ('psnmobilephone', > 1043, None, 30, None, None, None), ('psnfaxnumber', 1043, None, 30, > None, None, None), ('psnemailname', 1043, None, 50, None, None, None), > ('psnreferredby', 1043, None, 50, None, None, None), ('psnlocid', 23, > None, 4, None, None, None), ('psnnotes', 1043, None, -1, None, None, None)) > > I believe if you use specific column names in your query they will > appear in the order given in the query also. > > I use this technique in > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 > > to print arbitrary query outputs. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline Apparently I am deaf dumb and blind.... :( Sorry. I grepped several times through the PEP for various other reasons, and this little bit escaped me. Thanks for being nice guys and answering anyhow. Much appreciated. From grante at visi.com Thu Sep 6 22:30:41 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Sep 2007 02:30:41 -0000 Subject: why should I learn python References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <1189117798.506367.278560@y42g2000hsy.googlegroups.com> Message-ID: <13e1duhl3evcg2c@corp.supernews.com> On 2007-09-06, windandwaves wrote: > On Sep 7, 9:50 am, James Stroud wrote: >> Seewww.python.org. Trust us all when we say that its the best. >> > > I get that feeling - yes. Question is: > > 1. what is it good for? Writing programs. > 2. why is it so good? Compared to languages like C/C++ it takes a lot less time to write a program in Python and results in programs that work. The programs are also a lot easier to maintain. And a lot more portable. -- Grant Edwards grante Yow! I am deeply CONCERNED at and I want something GOOD visi.com for BREAKFAST! From zach at REMOVEME.in.tu-clausthal.de Fri Sep 28 18:25:42 2007 From: zach at REMOVEME.in.tu-clausthal.de (Gabriel Zachmann) Date: Fri, 28 Sep 2007 22:25:42 +0000 (UTC) Subject: Bug with lists of pairs of lists and append() Message-ID: Well, could some kind soul please explain to me why the following trivial code is misbehaving? #!/usr/bin/python lst = [ 0, 1, 2 ] s = [] l = [ lst[0] ] r = lst[1:] while r: x = (l,r) print x s.append( x ) l.append( r.pop(0) ) print s The output I get is: ([0], [1, 2]) ([0, 1], [2]) [([0, 1, 2], []), ([0, 1, 2], [])] and the error is in the last line: the two pairs in the outer list are identical and they should be as the pairs on the first and the 2nd line, respectively! I think I'm going nuts -- for the life of me I don't see what's going on ... (I've been tracking down a bug in my larger python script, and the cause seems to boil down to the above snippet.) Thanks a lot in advance for any insights, etc. Best regards, Gabriel. From exhuma at gmail.com Mon Sep 24 10:35:58 2007 From: exhuma at gmail.com (exhuma.twn) Date: Mon, 24 Sep 2007 07:35:58 -0700 Subject: (pyqt) Parameters when connecting a signal to a method? Message-ID: <1190644558.386647.88270@22g2000hsm.googlegroups.com> Some code: ---------------------------------------------------------------------- def foobar(w): print w QtCore.QObject,connect( my_line_edit, QtCore.SIGNAL("returnPressed()"), foobar ) ---------------------------------------------------------------------- How can I get this to work so "foobar" prints out the sender of the signal (i.e. my_line_edit)? From bronger at physik.rwth-aachen.de Sat Sep 8 13:42:14 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 08 Sep 2007 19:42:14 +0200 Subject: /dev/null as a file-like object, or logging to nothing References: <87k5r1jdzq.fsf@wilson.homeunix.com> <5kg48jF33dv5U3@mid.uni-berlin.de> Message-ID: <87fy1pjbpl.fsf@wilson.homeunix.com> Hall?chen! Marc 'BlackJack' Rintsch writes: > On Sat, 08 Sep 2007 18:52:57 +0200, Torsten Bronger wrote: > >> Is there a portable and simply way to direct file-like IO to >> simply nothing? I try to implement some sort of NullLogging by >> saying > > `os.devnull`? Yes, but I wasn't really sure how portable it is, in particular, on Windows. So does open(os.devnull, "w").write("Schallalla") work on Windows like on Unix? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From jstroud at mbi.ucla.edu Sat Sep 15 17:58:15 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 15 Sep 2007 14:58:15 -0700 Subject: Needless copying in iterations? Message-ID: Hello all, I was staring at a segment of code that looked like this today: for something in stuff[x:y]: whatever(something) and was wondering if the compiler really made a copy of the slice from stuff as the code seems to suggest, or does it find some way to produce an iterator without the need to make a copy (if stuff is a built-in sequence type)? Or would it be more efficient to do the more clumsy (in my opinion): for i in xrange(x, y): whatever(stuff[i]) James From jeroen.hegeman at gmail.com Mon Sep 24 11:51:06 2007 From: jeroen.hegeman at gmail.com (Jeroen Hegeman) Date: Mon, 24 Sep 2007 17:51:06 +0200 Subject: Newbie completely confused In-Reply-To: <1190434069.108503.281930@y42g2000hsy.googlegroups.com> References: <1190434069.108503.281930@y42g2000hsy.googlegroups.com> Message-ID: <1122CE63-193C-4EF3-A2AC-3D9DE3DD88BE@gmail.com> > > Your code does NOT include any statements that could have produced the > above line of output -- IOW, you have not posted the code that you > actually ran. Oh my, I must have cleaned it up a bit too much, hoping that people would focus on the issue instead of the formatting of the output strings! Did you miss your morning coffee??? > Your code is already needlessly monstrously large. Which I realised and apologised for beforehand. > > And Python 2.5.1 does what? Strike 3. Hmm, I must have missed where it said that you can only ask for help if you're using the latest version... In case you're wondering, 2.5.1 is not _really_ that wide-spread as most of the older versions. > For handling the bit extraction stuff, either [snip] > (b) do a loop over the bit positions Now that sounds more useful. I'll give that a try. Thanks, Jeroen Jeroen Hegeman jeroen DOT hegeman AT gmail DOT com WARNING: This message may contain classified information. Immediately burn this message after reading. From ldo at geek-central.gen.new_zealand Mon Sep 24 04:07:24 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 24 Sep 2007 20:07:24 +1200 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> Message-ID: In message <1190413322.962737.53900 at r29g2000hsg.googlegroups.com>, chris.monsanto at gmail.com wrote: > A question: if you WERE to implement function definitions as normal > expressions, how would you go about embedding it within an expression? > > x = map(def a: > > > > , [1, 2, 3]) Perl can do it just fine: $x = map ( sub { ... }, [1, 2, 3] ); The fact that Python has difficulties is purely a demonstration of the limitations of indentation-controlled syntax, not a criticism of the concept itself. From semanticist at gmail.com Tue Sep 4 14:05:32 2007 From: semanticist at gmail.com (Miles) Date: Tue, 4 Sep 2007 14:05:32 -0400 Subject: Printing lists in columns In-Reply-To: <87wsv6bda3.fsf@mulj.homelinux.net> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> <1188913394.763871.218660@d55g2000hsg.googlegroups.com> <46dd69b1$0$24998$426a74cc@news.free.fr> <1188917550.261894.84010@k79g2000hse.googlegroups.com> <87wsv6bda3.fsf@mulj.homelinux.net> Message-ID: On 9/4/07, Hrvoje Niksic wrote: > Python isn't too happy about adding individual keyword arguments after > an explicit argument tuple. Try this instead: > > for row in izip_longest(*d, **dict(fillvalue='*')): > print ', '.join(row) Or simply: for row in izip_longest(fillvalue='*', *d): print ', '.join(row) -Miles From x_john at timney.eclipse.co.uk Tue Sep 11 09:35:58 2007 From: x_john at timney.eclipse.co.uk (John Timney (MVP)) Date: Tue, 11 Sep 2007 14:35:58 +0100 Subject: Car-ac-systems References: <1189511932.371621.112970@o80g2000hse.googlegroups.com> Message-ID: How do I control one with C# then! Thats not on your site, clearly not everything I need to know then. Waste of a site! Regards John Timney (MVP) http://www.johntimney.com http://www.johntimney.com/blog "knjaz" wrote in message news:1189511932.371621.112970 at o80g2000hse.googlegroups.com... > Here you can find everything you need to know about car air > conditioning > > http://car-ac-systems.blogspot.com/ > From martin at v.loewis.de Sat Sep 29 02:56:08 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 Sep 2007 08:56:08 +0200 Subject: Python and SSL In-Reply-To: <7x641u0zvl.fsf@ruckus.brouhaha.com> References: <1190959345.041723.108130@k79g2000hse.googlegroups.com> <46fd7e7b$0$18410$9b622d9e@news.freenet.de> <7x641u0zvl.fsf@ruckus.brouhaha.com> Message-ID: <46fdf708$0$2775$9b622d9e@news.freenet.de> >>> But how can I tell my Python program to trust my SSL certificate? >> Why do you want to tell it that? The SSL module will trust *any* >> server certificate, no need to tell it explicitly which ones to >> trust. > > Er, the whole idea of SSL is that you don't trust the connection. Please try to understand that OP's question. He got some error, and for some reason, he concluded that he needs to tell Python to trust the server certificate (most likely to make the error go away). I told him that he is likely wrong, and that Python already trusts his server certificate. I was not proposing any judgment on whether that's a good thing or not. In fact, I have no idea whether security was of any concern to the OP. Regards, Martin From deets at nospam.web.de Wed Sep 5 13:54:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Sep 2007 19:54:24 +0200 Subject: PythonAlley.com In-Reply-To: <1189012363.397845.174960@y42g2000hsy.googlegroups.com> References: <1189012363.397845.174960@y42g2000hsy.googlegroups.com> Message-ID: <5k88qtF2h32tU1@mid.uni-berlin.de> dkeeney schrieb: > The Python community would benefit from a moderated web-forum along > the lines of > perlmonks.org. > > The Python community online now seems to have two major segments, the > c.l.p newsgroup (here), > and a large selection of blogs. C.l.p is unmoderated and often > hostile. The bloggers > self-moderate reasonably well (to my observation), but the blogs, > individually and > in aggregate, look 'read-only' to newbies, in that questions are not > welcomed. > > A moderated forum that gives recognition to the experienced and > tolerance to newbies would be a good thing. You might consider this as hostility - but this forum _is_ very helpful to newbies & generally NOT hostile. Diez From wink at saville.com Thu Sep 27 23:52:57 2007 From: wink at saville.com (wink) Date: Fri, 28 Sep 2007 03:52:57 -0000 Subject: Asynchronous Messaging In-Reply-To: References: <1190807252.731074.141450@k79g2000hse.googlegroups.com> <1190819912.344267.52680@50g2000hsm.googlegroups.com> <1190868212.383316.20990@57g2000hsv.googlegroups.com> Message-ID: <1190951577.293881.44040@r29g2000hsg.googlegroups.com> > > That't not the reason. A Queue is built around a container, and it happens > to be a deque in the default implementation. But the important thing is > that a Queue is a synchronized object - it performs the necesary > synchronization to ensure proper operation even from multiple threads > attempting to use it at the same time. > So your comparison is meaningless, apart from telling that using mutexes > is not cheap. > > -- > Gabriel Genellina Interesting, from the documentation for deque says; "Deques support thread-safe, ..." which would seem to imply a mutex of some sort would be used. But in looking at collectionsmodule.c for 2.5.1 I don't see any mutex which would seem to imply there is one place else, maybe the GIL, or the documentation is incorrect. On the other hand looking at the code in Queue.py there is a more code plus the not_full Condition variable plus the call to _put (which is a call to the deque.append) plus a notify on the not_empty conditional, so it's not surprising it's slower. If and when I think Queue is a performance impediment to an mproc I'll take another look at it, for now lots of things to learn. Thanks, Wink From nagle at animats.com Sat Sep 29 00:14:37 2007 From: nagle at animats.com (John Nagle) Date: Sat, 29 Sep 2007 04:14:37 GMT Subject: Python and SSL In-Reply-To: <6cydncA2Jpv082DbnZ2dnUVZ_q6dnZ2d@comcast.com> References: <1190959345.041723.108130@k79g2000hse.googlegroups.com> <6cydncA2Jpv082DbnZ2dnUVZ_q6dnZ2d@comcast.com> Message-ID: Heikki Toivonen wrote: > Johny wrote: >> I need to use Python with SSL comunication betweeen servers. >> (I use hhtplib but I think urllib2 can also be used ) >> I think I need to use SSL root certificate and tell a program to >> trust this certificate. > > You can't do secure SSL with the builtin SSL support, you need to use a > third party module. There are a few available, including M2Crypto, TLS > Lite, pyOpenSSL and pyOpenSSL-extended. Since I am the maintainer of > M2Crypto I will naturally recommend that ;) > > http://chandlerproject.org/Projects/MeTooCrypto Any progress on getting M2Crypto 0.18 to build successfully on Fedora Core? John Nagle From gagsl-py2 at yahoo.com.ar Mon Sep 24 03:43:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Sep 2007 04:43:15 -0300 Subject: elementtree question References: Message-ID: En Sat, 22 Sep 2007 00:19:59 -0300, Mark T escribi?: > "Gabriel Genellina" wrote in message > news:mailman.898.1190412966.2658.python-list at python.org... >> En Fri, 21 Sep 2007 11:49:53 -0300, Tim Arnold >> escribi?: >> >>> Hi, I'm using elementtree and elementtidy to work with some HTML files. >>> For >>> some of these files I need to enclose the body content in a new div >>> tag, >>> like this: >>> >>>
>>> original contents... >>>
>>> [wrong code] > The above wraps the body element, not the contents of the body element. > I'm > no ElementTree expert, but this seems to work: [better code] Almost right. clear() removes all attributes too, so if the body element had any attribute, it is lost. I would remove children from body at the same time they're copied into newdiv. (This whole thing appears to be harder than one would expect at first) import xml.etree.cElementTree as ET source = """Test original contents... 2&3 some text

Another paragraph

""" tree = ET.XML(source) body = tree.find("body") newdiv = ET.Element('div', {'class':'remapped'}) for e in list(body.getchildren()): newdiv.append(e) body.remove(e) newdiv.text, body.text = body.text, '' newdiv.tail, body.tail = body.tail, '' body.append(newdiv) ET.dump(tree) -- Gabriel Genellina From thanosv at gmail.com Tue Sep 18 08:47:05 2007 From: thanosv at gmail.com (thanosv at gmail.com) Date: Tue, 18 Sep 2007 05:47:05 -0700 Subject: raw string In-Reply-To: References: Message-ID: <1190119625.913133.87320@19g2000hsx.googlegroups.com> On Sep 18, 5:20 am, Konstantinos Pachopoulos wrote: > Hi, > i am trying to execute the following query on a DB: > qe.execQuery(r"SELECT * FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY > '"' LINES TERMINATED BY '\n' FROM Commiter") > > However, whether i put the r in the front or not, i always get an error > about the "\n". > What's wrong? Try r"SELECT * FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' FROM Commiter" It works for me. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Sep 11 07:52:46 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 11 Sep 2007 13:52:46 +0200 Subject: cpython list __str__ method for floats References: <13ectngf3aeqrb0@corp.supernews.com> Message-ID: <5kndseF4iskqU1@mid.individual.net> [david] wrote: > returns poorly formatted values: Please explain. > >>>str(13.3) > '13.3' > >>>str([13.3]) > '[13.300000000000001]' This is quite a FAQ. str of a float returns the float, rounded to decimal precision. str of a list returns a square brackets enclosed enumeration of the contents (using repr on them). repr of a float returns the float in full precision. Regards, Bj?rn -- BOFH excuse #442: Trojan horse ran out of hay From ricaraoz at gmail.com Sat Sep 8 14:25:41 2007 From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=) Date: Sat, 08 Sep 2007 15:25:41 -0300 Subject: How to determine the bool between the strings and ints? In-Reply-To: <13e5mjt4cklq891@corp.supernews.com> References: <1189182688.290480.102350@o80g2000hse.googlegroups.com> <5kdjmcF31i6hU7@mid.uni-berlin.de> <1189193206.466633.148610@r34g2000hsd.googlegroups.com> <13e5mjt4cklq891@corp.supernews.com> Message-ID: <46E2E925.3020106@bigfoot.com> Steven D'Aprano wrote: ... .. . > You know, one or two examples was probably plenty. The other six or seven > didn't add anything to your post except length. > > Also, type testing by equality is generally not a good idea. For example: > > class HexInt(int): > """Like built-in ints, but print in hex by default.""" > def __str__(self): > return hex(self) > __repr__ = __str__ > > You should be able to use a HexInt anywhere you can use an int. But not > if your code includes something like this: > > if type(value) == int: > do_something() > else: > print "Not an int!" > > (What do you mean my HexInt is not an int? Of course it is.) > > Better is to use isinstance(value, int). Better still is to do duck- > typing, and avoid type() and isinstance() as much as possible. >>> type(a) == HexInt True That's what I wanted (though I don't know if that's what the OP wanted). BTW, sorry for the wasted bandwidth, didn't realize you might have such a small bandwidth that seven lines would be a hassle. We should also tell the blokes of the 'music' thread to stop it, I can imagine how mad that must get you. From dohertywa at gmail.com Mon Sep 17 16:07:31 2007 From: dohertywa at gmail.com (dohertywa) Date: Mon, 17 Sep 2007 13:07:31 -0700 Subject: Probstat Combination Objects and Persistence In-Reply-To: <1189969908.477201.137360@w3g2000hsg.googlegroups.com> References: <1189954886.324005.325240@22g2000hsm.googlegroups.com> <1189969908.477201.137360@w3g2000hsg.googlegroups.com> Message-ID: <1190059651.447947.121090@k79g2000hse.googlegroups.com> On Sep 16, 3:11 pm, Sidd wrote: > On Sep 16, 8:01 am, dohertywa wrote: > > > > > Hi: > > > I'm working with probstat module which does an excellent job for the > > project I'm working on. > > > I am passing the Combination objects I generate to generator functions > > that allow me to scale down the results. > > > I am trying to find a way however to store the end resultant > > Combination object. Try to pickle it, and Python segfaults. > > > I want to be able to store the Combination object at any point so I > > may operate on it later without having to repeat previous work. > > > Any suggestions? > > > TVKIA, > > Adam > > You might want to take a look at this tutorial:http://www.ibm.com/ > developerworks/library/l-pypers.html Thanks for the suggestion. Unfortunately I've already read the article and still find myself a bit of a loss as to a solution. From jon at turnthepage.org Wed Sep 12 12:55:03 2007 From: jon at turnthepage.org (Jon Rosebaugh) Date: Wed, 12 Sep 2007 11:55:03 -0500 Subject: Generating HTML References: Message-ID: <2007091211550316807-jon@turnthepageorg> On 2007-09-11 23:33:18 -0500, "Sebastian Bassi" said: > Hello, > > What are people using these days to generate HTML? I still use > HTMLgen, but I want to know if there are new options. I don't > want/need a web-framework a la Zope, just want to produce valid HTML > from Python. > Best, > SB. Other folks have suggested Mako, and that's an excellent option. But I'd like to also suggest Brev?: a html DSL. http://breve.twisty-industries.com/ html [ head [ title [ 'A Brev? Template' ] ], body [ h1 [ 'Briefly, Brev?' ], br, div ( style = 'text-align: center;' ) [ span [ ''' As you can see, Brev? maps very directly to the final HTML output. ''' ] ] ] ] From deets at nospam.web.de Fri Sep 28 15:05:03 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Sep 2007 21:05:03 +0200 Subject: C Source Code Generator For Test Cases References: <1191001738.456766.176050@n39g2000hsh.googlegroups.com> Message-ID: <5m51iuFbao07U1@mid.uni-berlin.de> gamename wrote: > Hi, > > Can anyone recommend a good method of using python to generate c > source code? I have tables of test cases to use as input to a > process which would generate the test's source code. The Cheetah tool > looks interesting. Has anyone used it? Any other suggestions? How about using c-types to access your C-stuff to test, and use python + the testcase-tables to invoke that? Diez From stef.mientki at gmail.com Sun Sep 23 16:24:12 2007 From: stef.mientki at gmail.com (stef mientki) Date: Sun, 23 Sep 2007 22:24:12 +0200 Subject: building a GUI In-Reply-To: <5lnp2rF90pqqU1@mid.uni-berlin.de> References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> <5lnp2rF90pqqU1@mid.uni-berlin.de> Message-ID: <46F6CB6C.3050609@gmail.com> Diez B. Roggisch wrote: > stef mientki schrieb: > >> Thomas Dybdahl Ahle wrote: >> >>> Den Sun, 23 Sep 2007 17:28:38 +0200 skrev stef mientki: >>> >>> >>>> yadin wrote: >>>> >>>> >>>> >>>>> if i were up to make a GUI chich are the advantages of choosing python >>>>> over matlab or java? >>>>> >>>>> >>>>> >>>> The best is Delphi, >>>> second is VB, >>>> >>>> >>> That sounds mostly like a personal preference :) >>> >>> >>> >> Well I prefer Python ( because of it's OS-independancy and it's open >> source), >> but Python is really (still) much worse for GUI designs. >> Just compare some parameters like: >> - ease of use >> - speed of development >> - support of features >> - availability of libraries >> - documentation >> > > Sounds like PyQt for me. Best GUI-designer I know, tremendous speed in > development, giant sized lib that does all kinds of stuff & is > brilliantly designed + professional grade docus. > Could well be, but I never looked at PyQt seriously, because of their weird license. cheers, Stef From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 18 12:24:02 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 18 Sep 2007 18:24:02 +0200 Subject: Using pseudonyms (was Re: Python 3K or Python 2.9?) In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46ee2d9d$0$26213$426a74cc@news.free.fr> <46ef893c$0$21882$426a34cc@news.free.fr> Message-ID: <46effb9a$0$20144$426a74cc@news.free.fr> Aahz a ?crit : > In article <46ef893c$0$21882$426a34cc at news.free.fr>, > Bruno Desthuilliers wrote: >> Aahz a ?crit : >>> In article <46ee2d9d$0$26213$426a74cc at news.free.fr>, >>> Bruno Desthuilliers wrote: >>>> But what, given that I'm an AOL user still thinking it's kewl to hide >>>> behind a pseudo, what else would you expect ? >>> What exactly is a "pseudo", pray tell? >> Sorry : a pseudonym (a nickname). > > You apparently missed the thrust of my sarcasm. Obviously, yes. From tgrav at mac.com Wed Sep 5 08:36:40 2007 From: tgrav at mac.com (Tommy Grav) Date: Wed, 5 Sep 2007 08:36:40 -0400 Subject: handling modules in packages Message-ID: <619B716A-C1EB-42DF-9702-E288AD04F613@mac.com> Hi, I am working on a package that contains a number of different modules: > ls pyAstro __init__.py constants.py conversion.py observation.py orbit.py transformation.py however, I find that several of the modules have the same import statements: orbit.py: import numpy import constants import conversion import observations observations.py: import numpy import constants import conversions import transformations The modules themselves are not overly large, but it bugs me to have to import numpy twice (or even more as the number of modules grow). Is there a way to import numpy once in the package (like in the __init__.py file) such that it is accessible to all the modules? Or is the multiple imports just something one has to live with? Thanks for any help or direction to webpages discussing this topic. Cheers Tommy From wolf_tracks at invalid.com Fri Sep 21 08:48:32 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 21 Sep 2007 12:48:32 GMT Subject: Drawing a 640x480 Raw Image In-Reply-To: References: <5lh5q2F87tctU1@mid.uni-berlin.de> Message-ID: Oops. What I think I'm looking for is a way to open a data file of records that are 640x480 that are gray scaled. I probably need something like an open and a read. Once I've got that, then I need to place the raw image into a draw area on the canvas, so that I can draw on the image. W. Watson wrote: > Very good. I'll give it a try. > > Marc 'BlackJack' Rintsch wrote: >> On Thu, 20 Sep 2007 20:49:59 -0700, W. Watson wrote: >> >>> W. Watson wrote: >>>> I'm getting a 640x480 greyscale image from a video device. I'd like >>>> to place it on a canvas and then draw on the image. Does PIL or some >>>> image facility allow me to do that? >>> Corrected misspelling in Subject. The image here is nothing more than >>> a 640x480 byte array. Each byte is a gra[e]yscale value. >> >> PIL can do this: >> >> from PIL import Image >> >> def main(): >> width = 640 >> height = 480 >> image = Image.new('L', (width, height)) >> data = [x * y % 256 for x in xrange(width) for y in xrange(height)] >> image.putdata(data) >> image.save('test.png') >> >> `data` can be any iterable with byte values. >> >> Ciao, >> Marc 'BlackJack' Rintsch > -- Wayne Watson (Nevada City, CA) Web Page: From ddwiggins at advpubtech.com Fri Sep 28 17:45:39 2007 From: ddwiggins at advpubtech.com (Don Dwiggins) Date: Fri, 28 Sep 2007 14:45:39 -0700 Subject: ANNOUNCE: wxPython 2.8.6.0 In-Reply-To: <46FC8C4B.8000808@alldunn.com> References: <46FC8C4B.8000808@alldunn.com> Message-ID: Robin Dunn wrote: > Announcing > ---------- > > The 2.8.6.0 release of wxPython is now available for download at > http://wxpython.org/download.php. This release is mostly about fixing > a number of bugs and inconsistencies in wxWidgets and wxPython. This raises a policy question for me. I'm currently on 2.8.3, not having had any clear need to upgrade for a while. Is there any reason why I shouldn't continue to track the releases, but not upgrade to them until I need something specific (a fix for a bug, a new feature I want, ...)? For example, if I don't upgrade to 2.8.x.y when it comes out, might I have trouble in the future upgrading to 2.8.x+9.w? BTW, since I haven't said it recently: thanks again for a really useful product and support forum for it! -- Don Dwiggins Advanced Publishing Technology From mail at timgolden.me.uk Mon Sep 10 10:12:30 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 10 Sep 2007 15:12:30 +0100 Subject: PyConUK 2007 Message-ID: <46E550CE.8070202@timgolden.me.uk> For those who don't follow the UK Python scene, we've just all come back from a *fantastic* weekend in Birmingham: the very first PyCon UK. Terrific kudos to John Pinner and the West Midlands Python team who made it all happen without any serious mishaps, including registration with badges, T-shirts etc. for 200 people, a sit-down dinner for 150, dozens of speakers, lightning talks and keynote speakers, a flawless WLAN, suitably cheap hotel accomodation, and a great atmosphere. The Blogs and photos are starting to appear: http://www.pyconuk.org/community/BlogsAndPhotos and although it was the UK conference, you may see quite a few European faces in there and even one or two from the States and further afield. Look forward to seeing you there next year! TJG From ricaraoz at gmail.com Fri Sep 14 22:31:29 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 14 Sep 2007 23:31:29 -0300 Subject: Python 3K or Python 2.9? In-Reply-To: <46e97917$0$9014$426a74cc@news.free.fr> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> <46e97917$0$9014$426a74cc@news.free.fr> Message-ID: <46EB4401.6070000@bigfoot.com> Bruno Desthuilliers wrote: > TheFlyingDutchman a ?crit : >> Well I'm with Bruce Eckel - there shouldn't be any argument for the >> object in the class method parameter list. > > def fun(obj, *args, **kw): > # generic code here that do something with obj > > import some_module > some_module.SomeClass.fun = fun > > This is why uniformity is important. > > But anyway, I think it's quite clear that Python won't drop the explicit > self, so it looks like you have to live with it or choose another language. > >> Bruce said that no other mainstream OO language is explicitly passing >> the object as a parameter to class methods. > > to methods. class methods gets the class as first parameter. > > Anyway, there are a lot of things that Python doesn't do like "other > mainstream OO languages", and that's a GoodThing. > > >> What I would like to have seen added to class definitions was the >> forced declaration of all object variables in the class outside of >> methods. I don't like the fact that they have to be, and can be >> created in any method on the fly. > > I definitively think you'd be happier with some other language. Hi, I'm new to Python, I don't even fully know the language, never done a full project in Python. What's more, probably I'll never will. But that's not the point, the point is I want YOU people to modify the language you know in and out, the program with which you've done many systems, I want you to change it to suit my whims, so that I'll be comfortable with the 3 ten liners I'll write. TIA From zzbbaadd at aol.com Wed Sep 19 14:07:48 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 19 Sep 2007 11:07:48 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <13f2hctdoob87e5@corp.supernews.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> <13f2hctdoob87e5@corp.supernews.com> Message-ID: <1190225268.547042.55370@d55g2000hsg.googlegroups.com> On Sep 19, 8:51 am, Steven D'Aprano wrote: > On Tue, 18 Sep 2007 18:09:26 -0700, TheFlyingDutchman wrote: > > How much faster/slower would Greg Stein's code be on today's processors > > versus CPython running on the processors of the late 1990's? > > I think a better question is, how much faster/slower would Stein's code > be on today's processors, versus CPython being hand-simulated in a giant > virtual machine made of clockwork? > > -- > Steven. Steven, You forgot this part: "And if you decide to answer, please add a true/false response to this statement - "CPython in the late 1990's ran too slow"'. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 26 03:54:51 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 26 Sep 2007 09:54:51 +0200 Subject: the address of list.append and list.append.__doc__ In-Reply-To: <1190780557.879816.13800@d55g2000hsg.googlegroups.com> References: <1190775258.351819.24930@22g2000hsm.googlegroups.com> <1190780557.879816.13800@d55g2000hsg.googlegroups.com> Message-ID: <46fa102d$0$26322$426a74cc@news.free.fr> HYRY a ?crit : >> No. a.append is a "bound method" - a method that already has an >> associated instance, that will be provided as the first argument to the >> method call. Bound methods are created "on the fly". >> > > Does this means there is no method to get the original methods from > the Bound methods created "on the fly"? There's no such thing as an "original method" - what's stored as an attribute of the class is a plain function. FWIW, you can get at this function quite easily - via the im_func attribute of the method. Now what I wonder is what you want to do with the internal identifier of a function or method ? (please not that the use of the memory address as an id is purely an implementation detail of CPython). From erik at myemma.com Wed Sep 19 17:43:52 2007 From: erik at myemma.com (Erik Jones) Date: Wed, 19 Sep 2007 16:43:52 -0500 Subject: Google and Python In-Reply-To: <1190235678.019823.315850@o80g2000hse.googlegroups.com> References: <1190228512.627109.308910@n39g2000hsh.googlegroups.com> <1190231094.276099.136250@22g2000hsm.googlegroups.com> <1190235678.019823.315850@o80g2000hse.googlegroups.com> Message-ID: <4C5C88E9-CDEA-4C7D-A890-A9C21E086BEE@myemma.com> On Sep 19, 2007, at 4:01 PM, TheFlyingDutchman wrote: > On Sep 19, 1:02 pm, Erik Jones wrote: >> is usually Apache at most sites? >> >> No an http server and application server are two different things. >> An http server services requests of a web server those requests can >> be for static files or for services of a local application in which >> case the request if forwarded on to the application. An application >> services requests of an application. They are separate concepts, >> often chained, although they are sometimes implemented together. >> What they are saying here is that they have built a highly optimizing >> custom web server in C++ that services web requests for services of >> applications written in any of the three listed languages. So, yes, >> in this case it is what is often Apache in other installations. >> > OK, thanks. Would you know what technique the custom web server uses > to invoke a C++ app (ditto for Java and Python) CGI is supposed to be > too slow for large sites. That's what SWIG is for: interfacing C++ with other languages. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From arnodel at googlemail.com Fri Sep 7 13:36:35 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 07 Sep 2007 10:36:35 -0700 Subject: getting the current function In-Reply-To: References: Message-ID: <1189186595.875441.241470@50g2000hsm.googlegroups.com> On Sep 7, 5:19 pm, Gary Robinson wrote: > > This all seems a bit too complicated. Are you sure you want to do > > this? Maybe you need to step back and rethink your problem. > > In version 2.1 Python added the ability to add function attributes -- seehttp://www.python.org/dev/peps/pep-0232/for the justifications. A counter probably isn't one of them, I just used that as a quick example of using thisfunc(). > > I've just never liked the fact that you have to name the function when accessing those attributes from within the function. And I thought there might be other uses for something like thisfunc(). > You can do this without fiddling with stack frames: def bindfunction(f): def bound_f(*args, **kwargs): return f(bound_f, *args, **kwargs) bound_f.__name__ = f.__name__ return bound_f # Use like this: @bindfunction def factorial(this_function, n): if n > 0: return n * this_function(n - 1) else: return 1 # Interactively: >>> factorial(5) 120 >>> fac = factorial >>> factorial = "spam" >>> fac(8) 40320 >>> -- Arnaud From max at alcyone.com Mon Sep 3 21:49:23 2007 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Sep 2007 18:49:23 -0700 Subject: Python is overtaking Perl In-Reply-To: <1188869347.102325.119830@w3g2000hsg.googlegroups.com> References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> <20070904024908.b8aca60c.sulsa@gazeta.pl> <1188869347.102325.119830@w3g2000hsg.googlegroups.com> Message-ID: Asun Friere wrote: > How do you figure that? Isn't the chart showing the frequency of > those particular terms combined as a fraction of the total search > volume on Google? Who knows? The graph has no labeling or calibration for the y-axis, so it's meaningless. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis However much you knock at nature's door, she will never answer you in comprehensible words. -- Ivan Turgenev, 1860 From fakeaddress at nowhere.org Thu Sep 27 04:11:29 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 27 Sep 2007 01:11:29 -0700 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190814263.104358.158090@n39g2000hsh.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> <1190799759.367001.106400@r29g2000hsg.googlegroups.com> <87fy11lo22.fsf@mulj.homelinux.net> <1190804538.469582.96950@22g2000hsm.googlegroups.com> <1190814263.104358.158090@n39g2000hsh.googlegroups.com> Message-ID: Mark Summerfield wrote: > The sorteddict API that has emerged so far is (1) apart from the > constructor, everything is identical to dict, (2) the constructor > takes the same args as sorted(), so if you want to seed with a dict or > with keywords you write sorteddict(dict(a=1,b=2), ...), (or you could > create a sorteddict and use update() since that takes the same args as > dict's constructor). > > Could your AVLTree support cmp and keys and reverse? I think you are expending too much effort on the no-brainers. Yes, AVL-trees can support cmp and keys and reverse. I cannot speak for Antoon, but have no doubt that adapting his code to do so is within his ability. Hrvoje Niksic is right that a simple layer over existing hashed dicts "dooms the PEP to rejection". Thus the candidate algorithms are the approximately-balanced tree structures: AVL trees, red-black trees, 2-3 trees, b-trees, splay trees, or skip-lists. Implementing these is non-trivial, but easily within the ability of many people here. Don't worry about the coding. -- --Bryan From reflex-dev-bounces at dcc.uchile.cl Wed Sep 5 23:06:26 2007 From: reflex-dev-bounces at dcc.uchile.cl (reflex-dev-bounces at dcc.uchile.cl) Date: Wed, 05 Sep 2007 23:06:26 -0400 Subject: Your message to Reflex-dev awaits moderator approval Message-ID: Your mail to 'Reflex-dev' with the subject Test Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://reflex.dcc.uchile.cl/mailman/confirm/reflex-dev/0ad35f04f7a6585b804b0244f8706633fac538bd From zzbbaadd at aol.com Fri Sep 28 14:58:26 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 11:58:26 -0700 Subject: Python 3.0 migration plans? In-Reply-To: References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> Message-ID: <1191005906.556751.261940@22g2000hsm.googlegroups.com> On Sep 28, 11:16 am, Jean-Paul Calderone wrote: > On Fri, 28 Sep 2007 11:04:39 -0700, TheFlyingDutchman wrote: > > [snip] > > >In this case I asked it as part of the original question and it was > >ignored. I have programmed in C and C++ and a little Pascal many years > >ago. I don't remember anything about Higher Order Functions and would > >like to see exactly how you do it and to verify the contention. > > Perhaps you could do a bit of independent research. Then your messages > to the group could contain more thoughtful questions and responses. > But you miss the fact that I am providing value to the group by providing unthoughtful questions and unthoughtful responses. By having most of the pocket protectors being thrown at me, I provide a diversion that allows others to speak more freely and without fear of reproach. From zzbbaadd at aol.com Mon Sep 17 03:23:47 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 17 Sep 2007 00:23:47 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> Message-ID: <1190013827.107324.111820@w3g2000hsg.googlegroups.com> > The other half of the confusion is cleared up by considering that > Python methods are ordinary functions that don't magically "know" in > which "class" context they are executing: they must be told via the > first parameter. > They can be told all they want by the compiler/runtime - implicitly - under-the-covers, out-of-sight. From f.guerrieri at gmail.com Wed Sep 19 03:35:20 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Wed, 19 Sep 2007 09:35:20 +0200 Subject: Sets in Python In-Reply-To: <1190185200.598314.216210@y42g2000hsy.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190163542.585160.16230@w3g2000hsg.googlegroups.com> <1190185200.598314.216210@y42g2000hsy.googlegroups.com> Message-ID: <79b79e730709190035m6536051dsb51b394eb20a7739@mail.gmail.com> On 9/19/07, Paddy wrote: > frozenset over turning the embedded list into a tuple? > The tuple would preserve order in the item (1,2) > a = set([1,2,3, (1,2)]) The OP was probably thinking in mathematical terms as in "the set of all the possible subsets of the set composed by 1, 2 and 3" and thus order would not be important. francesco From nagle at animats.com Tue Sep 4 14:31:50 2007 From: nagle at animats.com (John Nagle) Date: Tue, 04 Sep 2007 18:31:50 GMT Subject: FCGI app reloading on every request In-Reply-To: References: <46DCDE59.8060109@animats.com> Message-ID: Thorsten Kampe wrote: > * John Nagle (Mon, 03 Sep 2007 21:26:01 -0700) > >> I'm converting a web app from CGI to FCGI. The application works fine >>under FCGI, but it's being reloaded for every request, which makes FCGI >>kind of pointless. I wrote a little FCGI app which prints when the program is >>loaded and when it gets a request. And indeed, the program gets reloaded for >>each HTTP request. Something is probably misconfigured. But what? >>[...] >>On the Python side, I'm using Python 2.5 on Linux, with Alan >>Saddi's "fcgi.py" module. > > > Do you use fcgi.py or flup? Go for flup I think that's irrelevant. The Python app is being launched in CGI mode, indicating trouble on the Apache side. Anything executable in the cgi-bin directory is being launched as a CGI program. A file named "example.foo", if executable, will launch as a CGI program. Nothing launches with FCGI. Tried putting this in the .htaccess file: SetHandler fcgid-script Options ExecCGI allow from all ErrorDocument 403 "File type not supported." Even with that, a ".foo" file gets executed as a CGI script, and so does a ".fcgi" file. It's an Apache configuration problem. John Nagle From carsten at uniqsys.com Wed Sep 5 12:32:45 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 05 Sep 2007 12:32:45 -0400 Subject: sqlite3.OperationalError: Could not decode to UTF-8 column In-Reply-To: References: Message-ID: <1189009965.3378.26.camel@dot.uniqsys.com> On Wed, 2007-09-05 at 16:40 +0100, Filipe Sousa wrote: > Hi > > I'm trying to use sqlite with python 2.5 but I have this problem: > > Traceback (most recent call last): > File "converter.py", line 13, in > c_old.execute('select id_aluno, nome from aluno') > sqlite3.OperationalError: Could not decode to UTF-8 column 'nome' with > text 'Ana Margarida Fernandes Gon?alves de S?' > > The database was created with another program and all data is in > database is in latin1. Try setting conn.text_factory = str where conn is the name of your sqlite3 connection object. See http://docs.python.org/lib/sqlite3-Connection-Objects.html for more information. HTH, -- Carsten Haese http://informixdb.sourceforge.net From timr at probo.com Thu Sep 13 00:57:40 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 13 Sep 2007 04:57:40 GMT Subject: Error in random module, bad installation? References: <1189635238.655642.233240@g4g2000hsf.googlegroups.com> Message-ID: <9lghe31glgpq8ge20ko3t1nqui0h9oag2a@4ax.com> Andrew F wrote: >I'm a linux user and I just upgraded from 2.1 to 2.5 and changed the >location of a number of libraries and tools. > >So far I've tracked most errors, but this one has me scratching my >head : > >$ which python >/usr/local/bin/python >$ echo $PYTHONPATH >/usr/local/bin/python PYTHONPATH is supposed to point to the directory containing modules, NOT the directory containing the executable. It should be /lib/python2.5. However, Carsten had the real cause for your immediate problem. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From lasses_weil at klapptsowieso.net Thu Sep 13 10:16:03 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Thu, 13 Sep 2007 16:16:03 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <13eigagsuk74l55@corp.supernews.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189666095.727426.135170@o80g2000hse.googlegroups.com> <1189685403.306218.13270@22g2000hsm.googlegroups.com> <13eigagsuk74l55@corp.supernews.com> Message-ID: <46e94623$0$30375$9b4e6d93@newsspool4.arcor-online.net> Steven D'Aprano wrote: > On Thu, 13 Sep 2007 12:10:03 +0000, timothy.soehnlin at gmail.com wrote: > >> Why not use '_' as the self variable. It is minimal and achieves close >> to '.var', as '_.var' isn't that different. I know its a little >> perl-esque, but its not a bad convention if you are aiming to up >> readability of your code. > > I think the definitions of "up" or "readability" you are using are very > different from mine. To me, to up something means to increase it, and > readability means the ease of comprehension when reading something. You > seem to be using the opposite definition for one or the other. > > OK, making a pointless reply to pointless reply, but anyway: I see merit in using (_.foo + _.bar) * _.baz instead of (s.foo + s.bar) * s.baz because I'm trained to interpret the underscore as a synonym for one space. It's not particularly beautiful, but that is probably a matter of habituation. And that exact word is probably the reason why I'd still use self or s (explained by a comment, because I can get very dumb if I have to). It's a matter of taste, so there is no point in bashing a valid suggestion. /W (I am aware that I'm banging a philosophy on people's heads just as Steven did, so I'm no better, I know.) From ldo at geek-central.gen.new_zealand Sun Sep 9 02:49:12 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 09 Sep 2007 18:49:12 +1200 Subject: Python syntax wart References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> Message-ID: In message <46E390B7.2080808 at web.de>, Stefan Behnel wrote: > He means he has to use backslashes instead of parentheses here. > > Which is not true, you could easily rephrase this as: > > for link in GetEachRecord( > "links", > ....): > out.write( > .... > ) > > See? No backslash! But then you can no longer use indentation to display the two-dimensional structure of the statement. From fakeaddress at nowhere.org Sat Sep 1 07:25:34 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 01 Sep 2007 04:25:34 -0700 Subject: status of Programming by Contract (PEP 316)? In-Reply-To: References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <4866bea60708291013g56b3dea9m7abcf5e4e4f6e29c@mail.gmail.com> Message-ID: Steve Holden wrote: [...] > If I can blow my own trumpet briefly, two customers (each using over 25 > kLOC I have delivered over the years) ran for two years while I was away > in the UK without having to make a single support call. One of the > systems was actually locked in a cupboard all that time (though I have > since advised that client to at least apply OS patches to bring it up to > date). > This was achieved by defensive programming, understanding the user > requirements and just generally knowing what I was doing. On the one hand, nice work. Made your customers happy and kept them happy. Can't argue with success. On the other hand, 25K lines is tiny by software engineering standards. If a support call would have to go to you, then the project must be small. Software engineering is only a little about an engineer knowing or not knowing what he or she is doing; the bigger problem is that hundreds or thousand of engineers cannot possibly all know what all the others are doing. I work on large and complex systems. If I screw up -- O.K., face facts: *when* I screw up -- the chance of the issue being assigned to me is small. Other engineers will own the problems I cause, while I work on defects in code I've never touched. I wish I could own all my own bugs, but that's not how large and complex systems work. Root-cause analysis is the hard part. By the time we know what went wrong, 99.99% of the work is done. Design-by-contract (or programming-by-contract) shines in large and complex projects, though it is not a radical new idea in software engineering. We pretty much generally agree that we want strong interfaces to encapsulate implementation complexity. That's what design-by-contract is really about. There is no strong case for adding new features to Python specifically for design-by-contract. The language is flexible enough to support optionally-executed pre-condition and post-condition checks, without any extension. The good and bad features of Python for realizing reliable abstraction are set and unlikely to change. Python's consistency and flexibility are laudable, while duck-typing is a convenience that will always make it less reliable than more type-strict languages. -- --Bryan From acirulli at gmail.com Mon Sep 3 10:56:10 2007 From: acirulli at gmail.com (Andrea) Date: Mon, 03 Sep 2007 07:56:10 -0700 Subject: Problem with extremely small real number Message-ID: <1188831370.133673.205230@r29g2000hsg.googlegroups.com> Hi, I need to calculate this probability P!/{n \choose p}, varying both n and p, n takes values in this range [512:1024] and p in [2:12]. So i write this code in python: def factorial(n): result=1 if n==0: return 1 for i in xrange(1, abs(n)+1): result = i*result if n >= 0: return result else: return -result def binomial(n, k): assert n>0 and isinstance(n, (int, long)) and isinstance(k, (int,long)) if k < 0 or k > n: return 0 if k == 0 or k == n: return 1 return factorial(n) // (factorial(k) * factorial(n-k)) I want to call factorial(2)//binomial(1024,2) for example, in this way trivially I obtain 0 as probability, how can I obtain the probability forcing this division to output extremely small real numbers???? I want to produce a program that provide a set of data of this probability on varying n and p, in order to plot a surface with this data set with gnuplot, any comments or suggestion? thanks in advance, Andrea From bronger at physik.rwth-aachen.de Sat Sep 8 13:54:18 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 08 Sep 2007 19:54:18 +0200 Subject: /dev/null as a file-like object, or logging to nothing References: <87k5r1jdzq.fsf@wilson.homeunix.com> Message-ID: <87bqcdjb5h.fsf@wilson.homeunix.com> Hall?chen! Carsten Haese writes: > On Sat, 2007-09-08 at 18:52 +0200, Torsten Bronger wrote: > >> Is there a portable and simply way to direct file-like IO to >> simply nothing? [...] >> >> [...] > > This might work: > > class LogSink(object): > def write(self, *args, **kwargs): pass > def flush(self, *args, **kwargs): pass > > logging.basicConfig(stream=LogSink()) > > I haven't tested this thoroughly, so it's possible that there are > more methods that the stream is expected to implement. No, write and flush are enough. Thank, this works. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From Astley.lejasper at gmail.com Wed Sep 12 11:25:52 2007 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 12 Sep 2007 15:25:52 -0000 Subject: National grid to lat long conversion In-Reply-To: References: <1188295755.877801.217710@r29g2000hsg.googlegroups.com> Message-ID: <1189610752.426514.228230@g4g2000hsf.googlegroups.com> Hi, I was a bit limited with time so in the end used an online service with an API which is great for the limited number of look-ups I needed. It can be found at: http://www.nearby.org.uk/ It was also very useful for site for other conversions and lookups. I manage to find a couple of other examples in other languages which I might have used as the basis for some pythonification. PHP - http://www.megalithia.com/search/llfuncshighlight.php - http://www.jstott.me.uk/phpcoord/ Javascript - http://www.movable-type.co.uk/scripts/latlong-gridref.html Cheers Neil From gagsl-py2 at yahoo.com.ar Thu Sep 6 23:35:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Sep 2007 00:35:24 -0300 Subject: Passing a tuple to a function as multiple arguments References: <789865.44579.qm@web313.biz.mail.mud.yahoo.com> Message-ID: En Fri, 07 Sep 2007 00:02:12 -0300, Ben Warren escribi?: > Hello, > > Let's say I have a function with a variable number of arguments (please > ignore syntax errors): > > def myfunc(a,b,c,d,...): > > and I have a tuple whose contents I want to pass to the function. The > number of elements in the tuple will not always be the same. > > T = A,B,C,D,... > > Is there a way that I can pass the contents of the tuple to the function > without explicitly indexing the elements? Something like: > > myfunc(magic(T)) Use *T when calling the function: py> def myfunc(a, b, c, d=None, e=None): ... print a,b,c,d,e ... py> T = 1,2,3,4,5 py> myfunc(*T) 1 2 3 4 5 py> T = 1,2,3 py> myfunc(*T) 1 2 3 None None py> T = 1,2 py> myfunc(*T) Traceback (most recent call last): File "", line 1, in TypeError: myfunc() takes at least 3 arguments (2 given) A similar syntax works when defining a function: *args will receive all remaining positional arguments joined into a tuple: py> def otherfunc(a, b, *args): ... print a, b, args ... py> otherfunc(1,2,3,4,5) 1 2 (3, 4, 5) py> T = 1,2,3,4 py> otherfunc(*T) 1 2 (3, 4) py> otherfunc('a','b','c',*T) a b ('c', 1, 2, 3, 4) This is covered in the Python Tutorial at and you can read the nasty details here -- Gabriel Genellina From istvan.albert at gmail.com Wed Sep 12 10:39:46 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Wed, 12 Sep 2007 14:39:46 -0000 Subject: MemoryError on reading mbox file In-Reply-To: <1189589259.662667.149730@w3g2000hsg.googlegroups.com> References: <1189589259.662667.149730@w3g2000hsg.googlegroups.com> Message-ID: <1189607986.628841.215930@50g2000hsm.googlegroups.com> On Sep 12, 5:27 am, Christoph Krammer wrote: > string = self._file.read(stop - self._file.tell()) > MemoryError This line reads an entire message into memory as a string. Is it possible that you have a huge email in there (hundreds of MB) with some attachment encoded as text? Either way, the truth is that many modules in the standard library are not well equipped to deal with large amounts of data. Many of them were developed before gigabyte sized files were even possible to store let alone process. Hopefully P3K will alleviate many of these problems by its extensive use of generators. For now I would recommend that you split your mbox file into several smaller ones. (I think all you need is to split at the To: fields) and run your script on these individual files. i. From wizzardx at gmail.com Wed Sep 12 06:05:27 2007 From: wizzardx at gmail.com (David) Date: Wed, 12 Sep 2007 12:05:27 +0200 Subject: setattr vs readonly property In-Reply-To: <1189588059.059818.301090@y42g2000hsy.googlegroups.com> References: <1189588059.059818.301090@y42g2000hsy.googlegroups.com> Message-ID: <18c1e6480709120305x5cd22a3cnc59bc0aec18a9943@mail.gmail.com> > My main purpose for using setattr(object, attr, value) for assign > values from a dict that has some keys that may not be present on some > object's attibute, which makes it work for me. My problem is dealing > with read only attribute like sample_attribute = > property(f_get=_get_sample_attribute). what approach should I use? Or > is my first approach In the first place right? You could try catching the exception thrown when you attempt to assign to a read-only attribute. Although you may get consistency issues. ie your object doesn't have all the details from the dict, but the calling code expects them to be set. Perhaps you should provide "setter" methods for the properties also, so that your objects internal state gets set correctly. eg: in your class declaration: def setfoo(self, value): # Add code here to check 'value' and set internal 'foo' state correctly self._foo = value def getfoo(self): return self._foo foo = property(setfoo, getfoo) From kay.schluehr at gmx.net Sat Sep 22 05:44:35 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 22 Sep 2007 02:44:35 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <5lk2olF8gic1U5@mid.uni-berlin.de> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> Message-ID: <1190454275.282176.90830@k79g2000hse.googlegroups.com> On Sep 22, 10:40 am, Marc 'BlackJack' Rintsch wrote: > On Sat, 22 Sep 2007 00:47:37 -0700, Kay Schluehr wrote: > > On 22 Sep., 08:56, Paul Rubin wrote: > >> Kay Schluehr writes: > >> > If you feel you can transform it into another unambigous grammar > >> > mixing statements and expressions it's up to you. > > >> We got rid of the print statement for python 3.0. Why not get rid > >> of the rest of them too? Just use expressions for everything, as > >> works fine for plenty of other languages. > > > One might create a new dynamic functional+OO programming language, > > where small statements like print, assert, raise etc. all become > > functions and statements like while, for, with etc. become anonymous > > closures. > > Before someone starts to create such a thing he should take a look at Io > which has just objects and methods. > > http://www.iolanguage.com/ > > Ciao, > Marc 'BlackJack' Rintsch I checked out Io once and I disliked it. I expected Io's prototype OO being just a more flexible variant of class based OO but Io couples a prototype very closely to its offspring. When A produces B and A.f is modified after production of B also B.f is modified. A controls the state of B during the whole lifetime of B. I think parents shall not do this, not in real life and also not in programming language semantics. There was another, similar and also abandoned project a while ago heading for prototype OO called Prothon: http://mail.python.org/pipermail/python-announce-list/2004-March/002966.html When I remember correctly it was killed not because it was too ambitious but the author lost his vision and didn't want to grow Prothons ecosystem. From bj_666 at gmx.net Fri Sep 7 08:45:12 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2007 12:45:12 GMT Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> Message-ID: <5kcveoF31i6hU3@mid.uni-berlin.de> On Fri, 07 Sep 2007 12:03:23 +0000, Steven D'Aprano wrote: > I have an application that will be producing many instances, using them > for a while, then tossing them away, and I want each one to have a unique > identifier that won't be re-used for the lifetime of the Python session. > > I can't use the id() of the object, because that is only guaranteed to be > unique during the lifetime of the object. > > For my application, it doesn't matter if the ids are predictable, so I > could do something as simple as this: > > def unique_id(): > n = 1234567890 > while True: > yield n > n += 1 > > unique_id = unique_id() > > while Application_Is_Running: > make_an_object(id=unique_id()) > do_stuff_with_objects() > delete_some_of_them() > > which is easy enough, but I thought I'd check if there was an existing > solution in the standard library that I missed. For that easy solution you can use `itertools.count()`. Ciao, Marc 'BlackJack' Rintsch From quentel.pierre at wanadoo.fr Wed Sep 19 02:02:29 2007 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Wed, 19 Sep 2007 06:02:29 -0000 Subject: Processing drag & drop on the desktop In-Reply-To: <1uSdnaNGwMvgBXPbnZ2dnUVZ_tjinZ2d@comcast.com> References: <1189961614.510561.194610@w3g2000hsg.googlegroups.com> <1uSdnaNGwMvgBXPbnZ2dnUVZ_tjinZ2d@comcast.com> Message-ID: <1190181749.502414.195730@r29g2000hsg.googlegroups.com> On 17 sep, 17:08, Larry Bates wrote: > Pierre Quentel wrote: > > Hi all, > > > I would like to create an application on a Windows machine, such that > > when a document is dragged and dropped on the application icon on the > > desktop, the document is processed by the application > > > For instance, if I drag & drop an Outlook message or a PPT > > presentation, the application would propose to tag the document with > > keywords taken from a database > > > Is it possible to do this with a Python script, and how ? > > > Regards, > > Pierre > > If you write a python application and put a shortcut on the desktop, when you > drop any file on it in Windows it is passed into the program via the sys.argv > list as the second (e.g. sys.argv[1]) argument. If you drop multiple files, > they are passed in sys.argv[1] sys.argv[n]. All you need to do is to pick up > the filename and do your processing. > > -Larry- Masquer le texte des messages pr?c?dents - > > - Afficher le texte des messages pr?c?dents - Thanks for the answers, but it still doesn't work I tried to do this : create a Python script with ================ import sys out = open("dummy","wb") out.write(str(sys.argv)) out.close() =============== then put a shortcut to this script on the desktop When I drop a file on the shortcut, nothing happens (when I double- click on the shorcut, a console window opens and sys.argv is actually stored in the file) Am I missing something ? Regards, Pierre From vinay_sajip at yahoo.co.uk Tue Sep 25 08:38:35 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 25 Sep 2007 05:38:35 -0700 Subject: strange behavious of the logging module? In-Reply-To: References: <1190643051.084144.230220@o80g2000hse.googlegroups.com> <1190672978.233964.232900@g4g2000hsf.googlegroups.com> Message-ID: <1190723915.218110.170720@k79g2000hse.googlegroups.com> On 25 Sep, 09:40, Peter Otten <__pete... at web.de> wrote: > You could try setting > > logging._srcfile =logging.info.func_code.co_filename > > manually, but that might break other things. Or you recreate the pyc-files > of your distribution. Again, I don't know what might break... > Recreating .pyc files should not break anything - this will get done automatically, so deleting the .pyc and/or .pyo files in the Python/ Lib directory tree should be sufficient. See the issues linked to by http://bugs.python.org/msg24988 In these cases, deleting the .pyc/.pyo files solved the problem. Best regards, Vinay From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Sep 10 07:45:12 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 10 Sep 2007 13:45:12 +0200 Subject: Python syntax wart References: <1189405211.875217.176620@57g2000hsv.googlegroups.com> Message-ID: <5kkp28F46jjuU2@mid.individual.net> TheFlyingDutchman wrote: > It may be that a language that doesn't have a statement terminator > (which can be end-of-line) needs a statement continuation symbol. Which language could that be? I can hardly imagine making a complex program out of one statement. Regards, Bj?rn -- BOFH excuse #147: Party-bug in the Aloha protocol. From carsten at uniqsys.com Wed Sep 26 06:33:21 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 26 Sep 2007 06:33:21 -0400 Subject: %s shortcut? In-Reply-To: <1190775317.062210.234400@g4g2000hsf.googlegroups.com> References: <1190775317.062210.234400@g4g2000hsf.googlegroups.com> Message-ID: <1190802801.3397.17.camel@dot.uniqsys.com> On Wed, 2007-09-26 at 02:55 +0000, james_027 wrote: > hi i have something like this > > cursor.execute(""" > select c.name, > (select from ap_invoice i where Month(i.date) = 1 and > Year(i.date) = %s and i.customer_id = c.id and i.status != 'CAN') jan, > (select from ap_invoice i where Month(i.date) = 2 and > Year(i.date) = %s and i.customer_id = c.id and i.status != 'CAN') feb, > (select from ap_invoice i where Month(i.date) = 3 and > Year(i.date) = %s and i.customer_id = c.id and i.status != 'CAN') mar > from ap_customer c > order by %s""", > [year, order_by]) In addition to previously made suggestions of using parameter binding, I'd like to point out the following: 1) Aren't you missing at least one expression between "select" and "from" in your subqueries? I'd imagine you'd have to select sum(i.amount) or something like that. 2) Why do you use subqueries at all? I think it would be much more efficient to let the database return the months as rows instead of columns, and rearrange the results into columns in Python logic: cursor.execute(""" select c.name, month(i.date), sum(i.amount) from ap_customer c, ap_invoice i where i.customer_id = c.id and i.status != 'CAN' and year(i.date) = %s group by 1,2 order by %s""" % [year, order_by]) 3) Instead of doing a filter on year(i.date), you should try "i.date between start_date and end_date" (where start_date and end_date are supplied appropriately). That way, the database might be able to use an index on the date column, which it might not otherwise be able to do. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From zzbbaadd at aol.com Thu Sep 6 01:54:55 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Wed, 05 Sep 2007 22:54:55 -0700 Subject: Using wild character In-Reply-To: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> References: <1189054805.447871.213150@y42g2000hsy.googlegroups.com> Message-ID: <1189058095.671230.262190@o80g2000hse.googlegroups.com> On Sep 5, 10:00 pm, Sreeraj wrote: > hi, > > I am a beginner in Python. I wish to know how can i filter a list of > strings using wild characters.ie > Lets say i have list countries = > ["india","africa","atlanta","artica","nigeria"]. I need only the list > of string starting with 'a'. > > thank you > > Sreeraj The most thorough answer would no doubt involve regular expressions, but they can be unpleasant. To do a "string*" type wildcard filter as in your request: myList = ["india","africa","atlanta","artica","nigeria"] newList = [ item for item in myList if item.startswith("a") ] To do a "*string" wildcard filter use the endswith() function instead of startswith() and to do a *string* type wildcard filter use the find() function > -1. From munncha at gmail.com Sun Sep 23 21:51:46 2007 From: munncha at gmail.com (Kurtis Heimerl) Date: Sun, 23 Sep 2007 18:51:46 -0700 Subject: Preemption in python In-Reply-To: References: <9a4753250709221928s5768b15emecfd71a0f476cce@mail.gmail.com> <1190572311.5703.4.camel@thinkpad> <9a4753250709231210l701a2cccge014732c79a5fdf9@mail.gmail.com> Message-ID: <9a4753250709231851x12885c96s62b11ef0dc823bdc@mail.gmail.com> Thanks a ton! Just for the eventual webcrawler that logs this, the gtk package requires a separate thread init function to allow python threads to play nice. On 9/23/07, Gabriel Genellina wrote: > > En Sun, 23 Sep 2007 16:10:03 -0300, Kurtis Heimerl > escribi?: > > > I'll explain a bit more. This thread is spawned, I also have the main > > thread > > running a gtk windowed gui. The gui has it's own threads to deal with > > button > > presses and such. The problem is that the gui never seems to let anyone > > else > > run. Only on button presses that cause blocking calls ( > > ossaudiodev.audio.read for instance) does the reader thread print > > anything. > > Google for "python gtk threading tutorial" > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Wed Sep 19 03:31:57 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 19 Sep 2007 09:31:57 +0200 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> Message-ID: <87k5qn5cwi.fsf@mulj.homelinux.net> Ben Finney writes: > Evan is claiming that "the next class in the MRO _is_ a superclass", > apparently by his definition or some other that I've not seen. The definition of superclass is not the issue, the issue is "superclass *of which class*"? You expect super(A, self) to iterate only over superclasses of A, even when self is an instance of a subtype of A. What really happens is that super(A, self) yields the next method in type(self)'s MRO, which can and does cause include classes that are not by any definition superclasses of A. All of those classes are, however, superclasses of the instance's type. I think it is not possible to have super(A, self) only call superclasses of A and at the same time having multiple inheritance work without calling some methods in the hierarchy twice or not at all. Guido's paper at http://tinyurl.com/qkjgp explains the reasoning behind super in some detail. >> I agree that the documentation for super is somewhat misleading (and >> obviously wrong), > > Well, that's the first time someone has acknowledged that in this > thread, so I guess this is something. For the record, I also agree with that. The documentation should document in some detail that super(type, obj) yields superclasses of type(obj), not of type, and that the "type" argument is only used for super to be able to locate the next type in the list. >> I wouldn't use such an extreme word as 'madness', but I totally agree >> that this should be corrected. Care to submit a doc patch ? > > I don't understand what practical uses 'super' is intended for It's intended for cooperative multiple inheritance, a la CLOS's call-next-method. From mail at timgolden.me.uk Thu Sep 20 09:10:34 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 20 Sep 2007 14:10:34 +0100 Subject: how to convert xml file to word document. In-Reply-To: <1190293176.702616.235480@e9g2000prf.googlegroups.com> References: <1190293176.702616.235480@e9g2000prf.googlegroups.com> Message-ID: <46F2714A.5010008@timgolden.me.uk> prajwala wrote: > I want to convert xml file to a word document using python. Is > there > any built in module available? > or Is there any other way to convert xml file to word document. Insofar as it is textual, an xml file *is* a Word document. Just open it up in Word and see. I assume you mean something else, but at the moment you're not telling us what that is. TJG From steve at REMOVE-THIS-cybersource.com.au Tue Sep 11 18:27:02 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 11 Sep 2007 22:27:02 -0000 Subject: Enum class with ToString functionality References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <87bqca9hrw.fsf@benfinney.id.au> <1189472591.797327.189180@w3g2000hsg.googlegroups.com> Message-ID: <13ee5hmhmgr3d14@corp.supernews.com> On Mon, 10 Sep 2007 18:03:11 -0700, TheFlyingDutchman wrote: >> I'd like to know if the Cheeseshop package 'enum' is useful to you. Any >> constructive feedback would be appreciated. >> >> > > Looking at the documentation it looks excellent. But I don't understand > the 0.4.2 version number, particularly when you refer to it as robust. Perhaps Ben should have followed the usual practice of commercial, closed- source software developers and started counting his version numbers at one instead of zero, miss a few releases, use randomly large increments occasionally, and ended up with a current version number of 2.7.1 for the exact same level of functionality. Or he could have called it "Enum XP" (for "eXtra Programming" perhaps) or "Enum 2007". The next minor release could be "Enum 2008", and the next major update could be called "Enum Professional Capowie!!!". -- Steven. From enleverlesX.XmcX at XmclaveauX.com Wed Sep 26 05:59:23 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Wed, 26 Sep 2007 11:59:23 +0200 Subject: PyS60 References: <1190731662.584011.105500@o80g2000hse.googlegroups.com> Message-ID: <46fa325c$0$5098$ba4acef3@news.orange.fr> Hi! I am also interested by Python on Symbian-series 60 @+ Michel Claveau From python.list at tim.thechases.com Sun Sep 30 09:51:11 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 30 Sep 2007 08:51:11 -0500 Subject: Optparse and help formatting? In-Reply-To: <13fv8ia94nq69d3@corp.supernews.com> References: <87abr423hu.fsf@benfinney.id.au> <13fv8ia94nq69d3@corp.supernews.com> Message-ID: <46FFA9CF.3030604@tim.thechases.com> >> def format_option(self, option): >> # The help for each option consists of two parts: >> # * the opt strings and metavars > [snip] > > Tim, I notice you're using lots of # lines as comments to describe the > function. Perhaps you should consider using docstrings instead. > > Pardon me if I'm telling you what you already know... Yes, I do know about and use docstrings, and no, no offense taken. You'll have to persuade the [Debian/Python] maintainer of optparse.py from whom I pilfered the code. :) tim at rubbish:~$ sed -n '/def format_option(/{N;N;N;N;N;p}' /usr/lib/python2.4/optparse.py def format_option(self, option): # The help for each option consists of two parts: # * the opt strings and metavars # eg. ("-x", or "-fFILENAME, --file=FILENAME") # * the user-supplied help string # eg. ("turn on expert mode", "read data from FILENAME") -tim From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 17 11:00:24 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 17 Sep 2007 17:00:24 +0200 Subject: Python "with" In-Reply-To: References: Message-ID: <46ee9686$0$9002$426a74cc@news.free.fr> Laurent Pointal a ?crit : (snip) > Note3: Its funny to see how Python users tries to change the language, s/Python users/some new Python users/, IMHO. From grante at visi.com Wed Sep 12 19:40:43 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 12 Sep 2007 23:40:43 -0000 Subject: I want py2exe not to create library.zip References: Message-ID: <13egu7rmilu2ia4@corp.supernews.com> On 2007-09-12, Laszlo Nagy wrote: > I want py2exe not to create library.zip. setup ( [...] options = {"py2exe": {"skip_archive":1}} ) -- Grant Edwards grante Yow! Am I accompanied by a at PARENT or GUARDIAN? visi.com From steve at holdenweb.com Tue Sep 11 19:55:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 19:55:30 -0400 Subject: common/static code In-Reply-To: References: Message-ID: <46E72AF2.1090908@holdenweb.com> brien colwell wrote: > hey all, > > I have a slew of functions that are shared across several scripts. > What's the best way to factor them out into a single location? > > many thanks > Define the functions in a module (e.g. myModule.py) then import them as from myModule inport fun1, fun2, fun3 regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From gibo at gentlemail.com Fri Sep 7 09:06:57 2007 From: gibo at gentlemail.com (GiBo) Date: Sat, 08 Sep 2007 01:06:57 +1200 Subject: Best practice prompting for password Message-ID: <46E14CF1.8090706@gentlemail.com> Hi, what's the best practice to securely prompt user for password on console in Python? IIRC some programs like SSH do a lot to ensure that the input comes from TTY and is not redirected from somewhere and several other checks. In the case of OpenSSH even the password prompt is always displayed regardless if the output is redirected to a file or not. Any pointers to best practice or code snippet of python password prompt? Thanks Gibo From raychorn at hotmail.com Thu Sep 20 19:13:14 2007 From: raychorn at hotmail.com (Python Maniac) Date: Thu, 20 Sep 2007 16:13:14 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> Message-ID: <1190329994.504531.235220@i38g2000prf.googlegroups.com> On Sep 20, 3:57 pm, "Matt McCredie" wrote: > On 9/20/07, Python Maniac wrote: > > > I am new to Python however I would like some feedback from those who > > know more about Python than I do at this time. > > Well, you could save some time by not applying the scramble one line > at a time (that is if you don't mind losing the line endings in the > scrambled version). For that to be effective though, you probably want > to open in binary mode. Also, your scramble can be written using list > comprehension. > > [code] > def scramble(s, key=0x80): > return ''.join([chr(ord(c) ^ key) for c in s]) > > output = scramble(f.read()) > [/code] > > If you use xor (^) as above, you can use the same method for scramble > as descramble (running it again with the same key will descramble) and > you can use an arbitrary key. Though, with 255 combinations, it isn't > very strong encryption. > > If you want stronger encryption you can use the following AESish algorithm: > > [code] > import random > def scramble(s, key): > random.seed(key) > return ''.join([chr(ord(c) ^ random.randint(0,255)) for c in s]) > [/code] > > This allows you to use much larger keys, but with a similar effect. > Still not strong enough to be unbreakable, but much better than the > origional. It is strong enough that someone knowing how you scrambled > it will have trouble unscrambling it even if they don't know the key. > > Matt So far I like what was said in this reply however my ultimate goal is to allow the scramble method to be more than what is shown above. I considered using XOR however XOR only works for the case shown above where the scramble method simply sets or removes the MSB. What I want to be able to do is set or reset the MSB in addition to performing a series of additional steps without negatively impacting performance for the later cases when the MSB is not the only technique being employed. Hopefully this sheds more light on the goal I have in mind. BTW - My original code is able to scramble a 20 MB file in roughly 40 secs using a Dell E6600 2.4 GHz. When I began writing the code for this problem my best runtime was about 65 secs so I know I was heading in the right direction. I was about to begin the process of using the D Language and pyd to gain better performance but then I thought I might also take this opportunity to learn something about Python before delving into D. Obviously I could simply code the whole process using D but that defeats the purpose for using Python in the first place and so I would tend to limit my low-level coding to the task of scrammbling each line of text. The ironic thing about this exorcise was the fact that the optimization techniques that worked for Python caused the Ruby version I coded to decrease performance. It seems Ruby has some definite ideas about what it feels is optimal that it ain't got much to do with what I would consider to be traditional optimization techniques where Ruby is concerned. For instance, Ruby felt the putc method was less optimal than the write method which makes no sense to me but that's life with Ruby. From mridula.ccpl at gmail.com Sat Sep 22 03:24:06 2007 From: mridula.ccpl at gmail.com (Mridula Ramesh) Date: Sat, 22 Sep 2007 12:54:06 +0530 Subject: calling the function of one class from another class Message-ID: <33dffc910709220024l74b14267v93564df10f5af9a6@mail.gmail.com> hi. i currently have code structured like this: classA(): > def __init__(): > .............. > .............. > > def fnc1(): > .................... > .................... > > > classB(): > def __init__(): > ........................ > ........................ > classA.fnc1() #this is where i get an error > TypeError: unbound method fnc1() must be called with classA instance as first argument (got nothing instead) when i do fnc1(classA) i get: NameError: global name 'fnc1' is not defined am i violating some programming rule by trying to call fnc1 in classB? i am only now learning OO alongside python, so i'm not sure! also, can someone please tell me where to go for more articles on the classes and functions and calling them from other places? thanks a lot! mridula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Tue Sep 11 10:44:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 10:44:10 -0400 Subject: newbie: stani's python editor if-else In-Reply-To: <588D53831C701746A2DF46E365C018CE01D2CB3A@LITEXETSP001.etrsouth.corp.entergy.com> References: <1189517164.302630.307850@w3g2000hsg.googlegroups.com> <588D53831C701746A2DF46E365C018CE01D2CB3A@LITEXETSP001.etrsouth.corp.entergy.com> Message-ID: Hamilton, William wrote: >> -----Original Message----- >> From: python-list-bounces+whamil1=entergy.com at python.org > [mailto:python- >> list-bounces+whamil1=entergy.com at python.org] On Behalf Of >> kyosohma at gmail.com >> Sent: Tuesday, September 11, 2007 8:26 AM >> To: python-list at python.org >> Subject: Re: newbie: stani's python editor if-else >> >> On Sep 10, 11:24 pm, madzientist wrote: >>> hi, >>> >>> two quick questions: >>> >>> a) i am using SPE (latest version) and for some reason, when i type, >>> say >>> >>> if 1==2: >>> print "not equal" >>> else: >>> print "equal" >>> >>> the else is at the same indentation level as the preceding print >>> statement, and i get a syntax error >>> >>> why doesn't spe automatically put the else at the level of the if >>> statement ? what am i dong wrong ? once i manually change the >>> indentation, the code snippet runs perfectly. >>> >>> b) if this is not the group for such elementary questions, please do >>> let me know. >>> >>> thanks !!!! >>> >>> suresh >> I agree with Steve. I have yet to see an IDE for Python (or anything >> else) that unindents statements. Even IDLE, the Official IDE for >> Python, doesn't do that. >> > > IDLE (At least, IDLE 1.0.5) unindents in obvious situations. I think > it's only on break, continue, pass, and return statements, but there may > be others. > Wing and Scite also do that, but Emacs seems to have the nicest behavior. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From claird at lairds.us Thu Sep 13 16:20:26 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 13 Sep 2007 20:20:26 +0000 Subject: automatic parallelization References: <46E99488.20909@uni-oldenburg.de> Message-ID: In article <46E99488.20909 at uni-oldenburg.de>, Michael Schlenker wrote: >Mikhail Teterin schrieb: >> While C/C++ and Fortran have OpenMP (http://www.OpenMP.org/), there is >> nothing comparable in Tcl (nor, as far as I know, in the two other >> scripting languages). >> >> Or is there? I'd like to, for example, have a version of foreach loop, that >> would split the tasks between concurrently executing threads in order to >> scale to the number of available CPUs: > >For CPython you don't get any benefit from extra CPUs even if you tried >(unless the code inside your loop is specially written C code), due to >the GIL. > >For Perl i don't know, their threading model was a bit heavy last time i >looked, but i might be off with that, so maybe its doable in Perl. > >For Tcl you would at least get the benefit of multiple CPUs, but its >more message passing based thread model is probably not the best for >autoparallelization like OpenMP (but you could use the tsv:: api for >shared vars if you want to). > >> >> For example: >> >> pforeach image $images { >> set exif($image) [extract_exif $image] >> } >> >> The script would be the same on a single- and a multi-CPU computer, but >> would automatically take advantage of multiple processors, when possible. > >Its doable in principle, but as with OpenMP you need extra annotations >to make it workable. > >If you have an event style script in Tcl you might be easier able to use >threads, as the thread::send -async api fits very well with the event >based style. . . . There are a LOT more possibilities one might pursue, depending on the details of Mr. Teterin's intent. I'm fond of Linda , Parallel Python only one of several initiatives which aspire to exploit multicores, and so on. From ldo at geek-central.gen.new_zealand Sat Sep 22 07:58:10 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 22 Sep 2007 23:58:10 +1200 Subject: Writing Object Data to Disk References: Message-ID: In message , Amit Kumar Saha wrote: >> > From: Lawrence D'Oliveiro > >> > In message , >> > Amit Kumar Saha wrote: >> > >> > > I would like to know if "Pickling" the class object is the only >> > way of writing it to disk for persistent storage. >> > >> > Also tying your external data representation to your >> > internal program structure (objects) makes it harder to change the >> > program in future. > > Actually, language independence is really not a consideration here. I am > happy at having it tied to Python :-) Even so, ignoring the issue of future changes is folly. From gagsl-py2 at yahoo.com.ar Tue Sep 18 10:37:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Sep 2007 11:37:23 -0300 Subject: Memory Problem References: <5la11gF71rf0U2@mid.uni-berlin.de> <200709181558.43026.cscheit@lstm.uni-erlangen.de> Message-ID: En Tue, 18 Sep 2007 10:58:42 -0300, Christoph Scheit escribi?: > I have to deal with several millions of data, actually I'm trying an > example > with > 360 grid points and 10000 time steps, i.e. 3 600 000 entries (and each > row > consits of 4 int and one float) > Of course, the more keys the bigger is the dictionary, but is there a > way to > evaluate the actual size of the dictionary? Yes, but probably you should not worry about it, just a few bytes per entry. Why don't you use an actual database? sqlite is fast, lightweight, and comes with Python 2.5 >> > # add row i and increment number of rows >> > self.rows.append(DBRow(self, self.nRows)) >> > self.nRows += 1 This looks suspicious, and may indicate that your structure contains cycles, and Python cannot always recall memory from those cycles, and you end using much more memory than needed. -- Gabriel Genellina From ladynikon at gmail.com Fri Sep 14 17:12:12 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 14 Sep 2007 17:12:12 -0400 Subject: Just bought Python in a Nutshell In-Reply-To: References: <1189784843.896396.108960@g4g2000hsf.googlegroups.com> Message-ID: <59f9c5160709141412q1098a4cbi989b6eed2f2cc899@mail.gmail.com> Luckily that site still had one left .. so i brought it :D. I can always use another good and CHEAP book. Danyelle From apardon at forel.vub.ac.be Fri Sep 14 05:49:18 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Sep 2007 09:49:18 GMT Subject: An ordered dictionary for the Python library? References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> <1189753968.917636.310120@19g2000hsx.googlegroups.com> Message-ID: On 2007-09-14, Mark Summerfield wrote: > On 14 Sep, 02:35, J?rgen Urner wrote: >> Puh, what a discussion... most common use case I can think of is >> >> >> d = {'a': 1, 'b': 2, 'c': 3} >> >> for key in d: >> >> # do something that relies on order of keys as specified in the constructor >> >> It's a bit tireing having to type >> >> >> for key in sorted(d.keys()): >> >> do_somethig_with(d[key]) >> >> instead of a trustfully >> >> >> for value in d.values(): >> >> do_somethig_with(value) >> >> As far as I can see much cleaner. No black magic needed ++ sort the >> dict >> to another order and rely on the sort order being stable would be a >> really >> a nice thing to have. >> >> My 2 cents, J?rgen > > What I envisage is: > > d = ordereddict(a=1, x=20, b=35, m=4) > # some time later > d["e"] = 15 > # later still > d["b"] = 70 > d.keys() # returns ['a', 'b', 'e', 'm', 'x'] > d.values() # returns [1, 70, 15, 4, 20] > which seems to be exactly what my avltree module mentioned earlier provides. >>> from avltree import Tree >>> d=Tree(a=1, x=20, b=35, m=4) >>> d["e"] = 15 >>> d["b"] = 70 >>> d.keys() ['a', 'b', 'e', 'm', 'x'] >>> d.values() [1, 70, 15, 4, 20] -- Antoon Pardon From jstroud at mbi.ucla.edu Mon Sep 17 21:51:49 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 17 Sep 2007 18:51:49 -0700 Subject: Try this In-Reply-To: References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> Message-ID: Steve Holden wrote: > mensanator at aol.com wrote: >> Makes you wonder what other edge cases aren't >> handled properly. >> >> Makes you wonder why Microsoft doesn't employ >> professional programmers. >> > Makes *me* wonder why you haven't got better things to do with your time. Contributing to this thread is only slightly worse than just reading it in terms of wasting one's... Just a moment, I'm having an epiphany! From steve at holdenweb.com Thu Sep 6 14:47:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Sep 2007 11:47:36 -0700 Subject: Help setting default class attributes In-Reply-To: <1189101393.484939.216840@g4g2000hsf.googlegroups.com> References: <1189099594.432512.278950@22g2000hsm.googlegroups.com> <1189101393.484939.216840@g4g2000hsf.googlegroups.com> Message-ID: attn.steven.kuo at gmail.com wrote: > On Sep 6, 10:26 am, rh0dium wrote: >> Hi all, >> >> I have the following piece of code and I wanted to set the default >> attributes based on a dictionary. What I am looking for is a way to >> take PIPODEFAULTS and assign each one as an attribute for the class >> pipo. Can someone show me how to do this by iterating over the >> PIPODEFAULTS and assign them. What I would expect to be able to do is >> call the class and modify them. >> >> example: >> a = pipo() >> print a.caseSensitivity >> "preserve" >> >> a.caseSensitivity = "lower" >> print a.caseSensitivity >> "lower" >> > > > I infer from your example that you want > to set default attributes for *instances of* class pipo > (not for class pipo itself). > > Use setattr: > > class pipo(object): > PIPODEFAULTS = {'caseSensitivity':'preserve', > 'cellMapTable':'checkPolygon', # etc > } > def __init__(self, *args, **kwargs): > for attr, value in pipo.PIPODEFAULTS.iteritems(): > setattr(self, attr, value) > > a = pipo() > b = pipo() > print a.caseSensitivity > a.caseSensitivity = 'lower' > print a.caseSensitivity > print b.caseSensitivity > > -- > Hope this helps, > Steven > > This is actually way over-complicated. Remembering that the MRO will look in the class to resolve the name of an attribute it doesn't find in the instance you can simply use the class as a repository for the defaults: >>> class pipo(object): ... caseSensitivity = 'preserve' ... cellMapTable = 'checkPolygon' ... # ... ... >>> p1 = pipo() >>> p2 = pipo() >>> p1.caseSensitivity 'preserve' >>> p2.caseSensitivity = "lower" >>> p1.caseSensitivity 'preserve' >>> p2.caseSensitivity 'lower' >>> You could extend the class to allow per-instance defaults to be set in the __init__() method too (untested): class pipo(object): caseSensitivity = "preserve" cellMapTable = 'checkPolygon' def __init__(self, ..., **kw): self.__dict__.update(kw) p1 = pipo(caseSensitivity='lower') regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From m.n.summerfield at googlemail.com Wed Sep 12 13:07:13 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Wed, 12 Sep 2007 17:07:13 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189605843.866907.117370@w3g2000hsg.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <13efnmi4n959a59@corp.supernews.com> <1189601205.503841.327170@o80g2000hse.googlegroups.com> <1189605250.186948.303130@50g2000hsm.googlegroups.com> <1189605843.866907.117370@w3g2000hsg.googlegroups.com> Message-ID: <1189616833.231659.323740@50g2000hsm.googlegroups.com> On 12 Sep, 15:04, Michele Simionato wrote: > On Sep 12, 3:54 pm, Mark Summerfield > wrote: > > > > > On 12 Sep, 13:46, Michele Simionato > > > Actually I meant by key order, so insertion order doesn't matter at > > all. If you need a dictionary-like data structure that respects > > insertion order you could use a list of (key, value) tuples. > > > Another respondent asked about use cases. > > > I have found time and again that I needed (key, value) pairs where the > > key is some string that provides a representation for human readers > > and the value is some internal key (e.g., database ID) that the system > > uses internally. In these cases I often need to present the user with > > a list of items from which to choose and want to present them in > > sorted order. Naturally, I could use an ordinary dict and then do > > this: > > > for string in sorted(d.keys()): > > process(string) > > > But what happens when I need to do this a *lot* and when the number of > > items is hundreds or a few thousands? I'm having to sort again and > > again, since it is often the case that the items in the list changes > > during the runtime of the application. So my solution in C++ is to use > > an ordered dictionary (a map in C++ jargon), which in Python means I > > can simply write: > > > for string in od.keys(): > > process(string) > > For your use case I would wrap a list [(key, value)] with a dict-like > object and I would use the bisect module in the standard library to > keep > the inner list ordered. > > M.S. Actually, in my own ordereddict I wrap a dict and keep the keys in order using the bisect module. This works fine, but I imagine that a C-based implementation based on B*trees or skiplists would be a lot faster. In response to some of the following emails, I note one responder says such a class is trivial to implement. Yes, and so presumably is defaultdict, but the latter is in the standard library. One of the "problems" of Python is that the range of skills of its users varies from casual "amateur" programmers to guru professionals and everywhere inbetween. Sure at somewhere on that continuum implementing *anything* is "trivial", but for some users it is worthwhile to have it out of the box. What I like about ordered dictionaries is the ability to have sorted data without sorting. It lets me have multiple sort orders. For example, in some programs I give the user the choice of how they want their data ordered and can provide such orderings without sorting, simply by maintaining a set of parallel data structures with keys being ordered and values being pointers (object references in Python) to the relevant values. This costs in memory (but not much since no values are duplicated and the values are usually large the keys usually small). Psuedocode example: class Person: def __init__(self, name, payrollno, grade, dept): self.name = name # etc For each person created: personFromName["%s\t%012d" % (person.name.lower(), person.payrollno)] = person personFromPayrollNo[person.payrollno] = person personFromGrade["%s\t%012d" % (person.grade, person.payrollno)] = person personFromDept["%s\t%012d" % (person.dept, person.payrollno)] = person So now I have four orderings with no sorting. (I have to disambiguate to avoid duplicates and to provide subordering.) If I have 10,000 people I would potentially have to resort 10,000 instances whenever the user chose a new sort order: this way I just have to iterate over the right ordered dictionary. So I do feel that there are good use cases, and I think that for some Python users having this in the library would be a genuine benefit. Most of the use cases I envisage involve lots of insertions at start up, relatively few during runtime, and lots of iterations over the data as the user changes their view of it. Of course Python does have an ordered dictionary, it is just not necessarily always installed. You can use the bsdbd3 module's btopen() method and pass None as filename to get an in-memory Btree, but I believe (not sure) that there may be length limits on the keys. From zzbbaadd at aol.com Thu Sep 13 12:26:15 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 13 Sep 2007 09:26:15 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: <1i4dddf.piaojwz9lz40N%aleax@mac.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> Message-ID: <1189700775.661780.292150@50g2000hsm.googlegroups.com> Well I'm with Bruce Eckel - there shouldn't be any argument for the object in the class method parameter list. But since Python 3 was "code-named" 3000 (implying but not delivering big changes... I don't think it required big changes) and since it still has an explicit object parameter it's a given that it's not gonna happen in any revisions. Bruce said that no other mainstream OO language is explicitly passing the object as a parameter to class methods. But Perl does it as well. I think the label "mainstream OO language" is as valid being applied to Perl as it is to Python. What I would like to have seen added to class definitions was the forced declaration of all object variables in the class outside of methods. I don't like the fact that they have to be, and can be created in any method on the fly. From bignose+hates-spam at benfinney.id.au Sat Sep 1 03:23:04 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 01 Sep 2007 17:23:04 +1000 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> <6ftgd35rd1g4mddqg2f44d7svd4r85ev17@4ax.com> <13dhvs3p5drsd99@corp.supernews.com> Message-ID: <87ejhic0iv.fsf@benfinney.id.au> Dennis Lee Bieber writes: > I suppose you also add an extra "i" to aluminum We're not out to rewrite the table of elements. There's no such thing as "aluminum", and "aluminium" always has just the two "i"s. -- \ "Rightful liberty is unobstructed action, according to our | `\ will, within limits drawn around us by the equal rights of | _o__) others." -- Thomas Jefferson | Ben Finney From stdazi at gmail.com Sat Sep 29 15:32:12 2007 From: stdazi at gmail.com (stdazi) Date: Sat, 29 Sep 2007 19:32:12 -0000 Subject: Program inefficiency? In-Reply-To: References: Message-ID: <1191094332.393736.231390@w3g2000hsg.googlegroups.com> On Sep 29, 6:07 pm, Michael.Coll-Ba... at VerizonWireless.com wrote: > You did not mention the OS, but because you are using > "pathname\editfile.txt", it sounds like you are using an MS OS. From > past experience with various MS OSes, I found that as the number of > files in a directory increases the slower your process runs for each > file. how so? From bj_666 at gmx.net Fri Sep 7 16:15:48 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2007 20:15:48 GMT Subject: How to determine the bool between the strings and ints? References: <1189182688.290480.102350@o80g2000hse.googlegroups.com> <5kdjmcF31i6hU7@mid.uni-berlin.de> <1189193206.466633.148610@r34g2000hsd.googlegroups.com> Message-ID: <5kdprjF31i6hU8@mid.uni-berlin.de> On Fri, 07 Sep 2007 12:26:46 -0700, Zentrader wrote: > Looks like a "feature" of isinstance() is to consider both True and 1 as > booleans, but type() distinguishes between the two. That's not a "feature", it is just OOP. `bool` is a subclass of `int` therefore every `bool` instance is also an instance of `int`. There's nothing special about it. In [57]: issubclass(bool, int) Out[57]: True In [58]: bool.__base__ Out[58]: Ciao, Marc 'BlackJack' Rintsch From arragon at NOSPAMlineone.net Wed Sep 5 11:18:11 2007 From: arragon at NOSPAMlineone.net (David Ross) Date: Wed, 05 Sep 2007 16:18:11 +0100 Subject: ZSI sample and issues with the WSDL Message-ID: First two appologies, this is probably not a Python question, more SOAP. And second, there is every possibilty I am terminally confused having looked at this for two days now. What I want is to create a Python SOAP server. I am using the sample which comes with ZSI, namely the Echo.wsdl and associated files. I then follow the instructions in the readme, and I CAN get a python client and server to communicate. But when I take the WSDL file and try to create a VB.NET program: >wsdl.exe /language:VB /out:myProxyClass.vb Echo.wsdl I get: Error: Unable to import binding 'EchoServer' from namespace 'urn:ZSI:examples'. - Unable to import operation 'Echo'. - Specified cast is not valid. So I tried to set up the wsdl to point to my domain: I get a the same error: Error: Unable to import binding 'EchoServer' from namespace 'http://www.me.org/Namespaces'. - Unable to import operation 'Echo'. - Specified cast is not valid. My problem is that I'm not sure how to edit the ZSI example. Worse, this is pretty much as simple as it seems to get ;-( Any pointers would be greatfully received. I know I should ask in the MS forumns, but I was hoping someone would understand the ZSI example better than I seem to. Cheers David ---- Note anti-spam in email address... From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Sep 17 11:41:47 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 17 Sep 2007 17:41:47 +0200 Subject: Use GUI for Python References: <1190043073.093736.272750@k79g2000hse.googlegroups.com> Message-ID: <5l7lhrF69pc5U1@mid.individual.net> koutoo at hotmail.com wrote: > I am new to python as I have been a VB programmer. I am used to > the GUI interface, and was wondering if I had to choose between a > GUI for Python, which one should I go with? Simple: The one you like most. Since this is an FAQ, I'll just list some popular GUI toolkits for Python: - TKinter (included) - wxPython - PyQt If you search the archives you'll find several discussions involving these and others. Regards, Bj?rn -- BOFH excuse #130: new management From tundra at tundraware.com Sat Sep 1 22:22:18 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Sat, 01 Sep 2007 21:22:18 -0500 Subject: So what exactly is a complex number? In-Reply-To: References: <451mq4-les.ln1@ozzie.tundraware.com> Message-ID: Grzegorz S?odkowicz wrote: > >> Here is a simple explanation (and it is not complete by a long shot). >> >> A number by itself is called a "scalar". For example, when I say, >> "I have 23 apples", the "23" is a scalar that just represents an >> amount in this case. >> >> One of the most common uses for Complex Numbers is in what are >> called "vectors". In a vector, you have both an amount and >> a *direction*. For example, I can say, "I threw 23 apples in the air >> at a 45 degree angle". Complex Numbers let us encode both >> the magnitude (23) and the direction (45 degrees) as a "number". >> >> There are actually two ways to represent Complex Numbers. >> One is called the "rectangular" form, the other the "polar" >> form, but both do the same thing - they encode a vector. >> >> Complex Numbers show up all over the place in engineering and >> science problems. Languages like Python that have Complex Numbers >> as a first class data type allow you do to *arithmetic* on them >> (add, subtract, etc.). This makes Python very useful when solving >> problems for engineering, science, navigation, and so forth. >> >> >> HTH, >> > You're mixing definition with application. You didn't say a word about > what complex numbers are, not a word about the imaginary unit, where I was trying to motivate the idea by means of analogy. This is a legitimate thing to do. It helps lead people to a conceptual understanding long before they understand the minutae. I am well aware of the imaginary unit and from whence complex analysis springs. I just didn't think that was the best place to start explicating the *concept*. I find concrete examples that then can lead to theoretical underpinnings a better way to go than the reverse. It is so hard to grasp that learning happens in layers, and that each layer need not be complete or even precise? Evidently you've either never taught (or were very bad at it). You have to motivate concept and interest before you can get to the precise detail. For instance, you start with Newtonian physics, not quantum physics. The entry level physics classes ignore things like the the non-linear behavior of springs, or the effects when you don't actually do things in a vacuum. By your definition these lectures would be "wrong" .. but they're not. They are attempting to introduce a topic painlessly. And that's what I was doing. > does it come from, why is it 'imaginary' etc. Since we're being arses > here I'd hazard a guess you were educated in the USA where doing without > understanding has been mastered by teachers and students alike. You're I was initially educated in Europe where being rude was sometimes encouraged to mask insecurity with a false sense of self-importance. I was later educated in both Canada and the US wherein I learned both they "why" and the how". -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From wizzardx at gmail.com Sun Sep 9 11:02:50 2007 From: wizzardx at gmail.com (David) Date: Sun, 9 Sep 2007 17:02:50 +0200 Subject: Spell-checking Python source code In-Reply-To: <46E32273.2050304@bigfoot.com> References: <1189285495.185657.88010@o80g2000hse.googlegroups.com> <46E314FD.7030200@bigfoot.com> <18c1e6480709081444x69c4d23cx65f7c9b62eda8271@mail.gmail.com> <46E32273.2050304@bigfoot.com> Message-ID: <18c1e6480709090802t654abc98r3c2639c752a9568d@mail.gmail.com> > tokenize.tokenize( > file.readline, > processStrings > ) > > How would you go about writing the output to a file? I mean, I would > like to open the file at main level and pass a handle to the file to > processStrings to write to it, finally close output file at main level. > Probably a class with a processString method? tokenize.tokenize() takes a callable object as it's second arg. So you can use a class which you construct with the file, and you give it an appropriate __call__ method. http://docs.python.org/ref/callable-types.html Although with a short script a global var may be simpler. From deets at nospam.web.de Fri Sep 28 12:49:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Sep 2007 18:49:16 +0200 Subject: Python 3.0 migration plans? References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> <1190968707.799398.232550@19g2000hsx.googlegroups.com> <5m4126FbgjabU1@mid.uni-berlin.de> <7x3awyu6sy.fsf@ruckus.brouhaha.com> Message-ID: <5m4pkcFboneqU1@mid.uni-berlin.de> Paul Rubin wrote: > "Diez B. Roggisch" writes: >> All serious languages are turing-complete. So can we put away with this >> non-sense argument right away, please? > > Actually the so called "total" languages aren't Turing-complete. I > think Coq is an example: every Coq function must return a value. So Please, Paul. There is no need to hijack every thread to show off your mad functional and wicked staticly typed programming language skillz. We had that discussion at a different time, and you very well know that with serious I didn't mean "can be used to program rockets that don't fall of the earth", but that aren't toy-languages used to solve real-world problems. Diez From bignose+hates-spam at benfinney.id.au Wed Sep 19 22:52:30 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 20 Sep 2007 12:52:30 +1000 Subject: cmsg cancel <87r6kuw0dw.fsf@benfinney.id.au> Message-ID: <87d4wevyj5.fsf@benfinney.id.au> I am canceling my own article. From sjmachin at lexicon.net Sat Sep 22 02:51:00 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Sep 2007 16:51:00 +1000 Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <46f49740$0$32514$4c368faf@roadrunner.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> Message-ID: <46f4bb56@news.eftel.com.au> On 22/09/2007 1:44 PM, Carl Banks wrote: > Anyone with me here? (I know the deadline for P3 PEPs has passed; this > is just talk.) > > Not many people are bit-fiddling these days. One of the main uses of bit > fields is flags, but that's not often done in Python because of keyword > arguments and dicts, which are lot more versatile. Another major use, > talking to hardware, is not something oft done in Python either. You need to get out more often :-) Python's bitwise operators are useful for and *used* for: (1) packing and unpacking arcane structs used in communication protocols and in proprietary file formats (2) trial implementations of pseudocode from academic papers, before transliterating to pyrex or C E.g. main loop for a bit-parallel O(N) algorithm for a Levenshtein distance: for c in t: pm_new = pm[ord(c)] d0 = (((pm_new & vp) + vp) ^ vp) | pm_new | vn hp = vn | ~(d0 | vp) hn = d0 & vp if hp & mask: x += 1 if hn & mask: x -= 1 hp = (hp << 1) | 1 vp = (hn << 1) | ~(d0 | hp) vn = d0 & hp return x > > It seems like this occasional usage wouldn't justify having built-in > operators on its own. And with the int/long unification, it makes a bit > less sense to think of integers as a bit field. "to think of integers as a bit field" makes no sense to me. Possibly you meant "to think of an integer as a collection of bit fields" -- but this is putting the cart before the horse. Simply: if the data is a collection of bit fields, and the data is held in an int or a long or the unification thereof, then you need bitwise operators to extract/pack the bit fields. > Python has these > operators because of its heritage, but Python continues to move away from > the bad habits of its ancestors (integer division and so on), and I > wonder if this isn't another one. > > Of course I'm not suggesting to get rid of bitwise operations altogether; > just make them builtin functions: "x & 1" becomes "bitwise_and(x,1)" and > so on. Function call overhead?? No thanks. E.g. from real working code: r = Rowinfo() # Using upkbits() is far too slow on a file # with 30 sheets each with 10K rows :-( # upkbits(r, bits2, ( # ( 0, 0x00000007, 'outline_level'), # ( 4, 0x00000010, 'outline_group_starts_ends'), # ( 5, 0x00000020, 'hidden'), # ( 6, 0x00000040, 'height_mismatch'), # ( 7, 0x00000080, 'has_default_xf_index'), # (16, 0x0FFF0000, 'xf_index'), # (28, 0x10000000, 'additional_space_above'), # (29, 0x20000000, 'additional_space_below'), # )) # So: r.outline_level = bits2 & 7 r.outline_group_starts_ends = (bits2 >> 4) & 1 r.hidden = (bits2 >> 5) & 1 r.height_mismatch = (bits2 >> 6) & 1 r.has_default_xf_index = (bits2 >> 7) & 1 r.xf_index = (bits2 >> 16) & 0xfff r.additional_space_above = (bits2 >> 28) & 1 r.additional_space_below = (bits2 >> 29) & 1 > Is it worth it to make such a change? It would remove a lot of operators > (11 by my count), vastly simplifying syntax, Which, IMHO, is no small > thing. New numerical types would have fewer operations to support. Specious argument. A new numerical type doesn't have to support bitwise operations now, if they make no sense for that type. > And > let's face it: unlike arithmetic opertaions, there's not a lot of > different meanings for bit operations. And it would also, um, make new > special characters available *cough*. > > Obviously, how widespread their usage is would matter. But keep in mind > it would also be easy to convert the code automatically, because the > Python parser could reliably find all bitwise operations reliably. (The > problem would be types that overloaded them to be something other than > bitwise operations: I'm looking at you, set. That could very well be a > deal breaker. I've never approved of things with completely different > meanings being deliberately overloaded to have the same spelling; this is > one reason why.) Too late. That instance of Pandora's box had its lid nailed open ab initio. > > If anyone says, "But that takes away an easy test for oddness (x&1)!", > or, "But you can multiply powers of two using left shift! Isn't that > cool?", I'm not buying it. Those are gimmicks. Arithmetic operations > should be done with arithmetic operators. The bitwise operators make the > code much less readable, especially to people unfamiliar with this usage. Agreed, but this is beside the point. People will write obfuscated code using any and every operator or built-in that you give them. In case you hadn't guessed by now: -1 Cheers, John From david at nospam.spam Tue Sep 11 21:50:49 2007 From: david at nospam.spam (david) Date: Wed, 12 Sep 2007 11:50:49 +1000 Subject: cpython list __str__ method for floats In-Reply-To: <5kndseF4iskqU1@mid.individual.net> References: <13ectngf3aeqrb0@corp.supernews.com> <5kndseF4iskqU1@mid.individual.net> Message-ID: <13eehfo8nr5eu1d@corp.supernews.com> Bjoern Schliessmann wrote: > [david] wrote: >> returns poorly formatted values: > > Please explain. > >> >>>str(13.3) >> '13.3' >> >>>str([13.3]) >> '[13.300000000000001]' > > This is quite a FAQ. > > str of a float returns the float, rounded to decimal precision. > > str of a list returns a square brackets enclosed enumeration of the > contents (using repr on them). repr of a float returns the float in > full precision. > > Regards, > > > Bj?rn > > contents (using repr on them). repr of a float returns the float in > full precision. But of course it doesn't, as illustrated, which is the whole point. It returns a string at greater than full precision. Leaving aside the question of why str should return repr, 13.300000000000001 is not 'the float in full precision': it is an arbitrary translation of the float. The idea that 13.3 is a 'rounded' value for the number, and that 13.300000000000001 is not a 'rounded' value of the number, is a common error of intuitive mathematics. I hope that when you say that this is a FAQ, you don't mean that the community has solidified on this naive interpretation :~) [david] From gagsl-py2 at yahoo.com.ar Tue Sep 4 19:46:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Sep 2007 20:46:19 -0300 Subject: doctest and decorators References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> <200709042316.08263.python@cx.hu> <2bfa72fa0709041452o72d9a98fp939852d061a2cda3@mail.gmail.com> <200709050009.46380.python@cx.hu> <2bfa72fa0709041529g9d5ac22hce3a55d5357b1a1c@mail.gmail.com> Message-ID: En Tue, 04 Sep 2007 19:29:11 -0300, Daniel Larsson escribi?: > On 9/5/07, Ferenczi Viktor wrote: >> >> > > @functools.wraps(f) >> > > Pass the function to be wrapped by the decorator to the wraps >> function. >> > Ooops, right. That doesn't change the fact that decorated functions >> get >> > hidden from doctest though. > > > I have no issue when the decorator is defined in the same module as the > decorated function, my problem is running doctests on functions using an > imported decorator. Having to implement the decorator in every source > module > isn't very practical. Try splitting your module in two, as I did, and run > with -v, and you'll see the problem. Looks like a bug. doctest is failing to recognize that the decorated function belongs to the module being tested. A simple patch: In doctest.py, method _from_module, near line 840, you have these lines: elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) Move them up, just before the line: elif inspect.isfunction(object): This works fine in this case, but I'm not sure whether this breaks in other circumstances (but I can't think of a case when using inspect.getmodule() would not be appropiate). PS: I can't see any tests for decorated functions (except @classmethod/@staticmethod) in the library test suite. I'll try to add some and submit a patch. -- Gabriel Genellina From cyril.giraudon at gmail.com Fri Sep 21 13:54:57 2007 From: cyril.giraudon at gmail.com (cyril giraudon) Date: Fri, 21 Sep 2007 10:54:57 -0700 Subject: Parameterize formatting string Message-ID: <1190397297.236691.137220@19g2000hsx.googlegroups.com> Hello, I 'd like to know if a std::setw() equivalent function exists in python ? i thought of something like : a = 16 "%ai" % 12 But it is not correct. Any Idea ? Thanks a lot, Cyril. From gonhidi at gmail.com Sat Sep 1 05:19:38 2007 From: gonhidi at gmail.com (=?ISO-8859-1?Q?Gonzalo_HIGUERA_D=CDAZ?=) Date: Sat, 1 Sep 2007 11:19:38 +0200 Subject: Ayuda In-Reply-To: <008c01c7eb37$0895eb80$0500000a@wf6840f5e6a1e4> References: <008c01c7eb37$0895eb80$0500000a@wf6840f5e6a1e4> Message-ID: <411f59bd0709010219t131ec526sb9935ffd1b564494@mail.gmail.com> 2007-08-30, Dr. Jos? Contreras : > Gente Inteligente y Distinguida, soy un aficionado y apelo a Ustedes, para > resolver ?ste problema. Para WebMaster de Google, me solicita instalar o > ejecuci?n de pit?n, c?mo comprender?n no dispongo de ning?n guru de web, por > lo que solicito en la medida de sus posibilidades me ayuden a ejecutar pit?n > para WebMaster, para ingresar a sitemap.xlm. Les saludo con distinguida > consideraci?n y respeto. Jos? > > Si son tan amables, les agradecer? cualquiera sea la Repuesta, en Espa?ol o > castellano. Gracias Entiendo que desea usar la herramienta Google Sitemap Generator para generar el fichero sitemap.xml.gz. De ser ?ste el caso, en el servidor donde se alberga el sitio web es necesario lo siguiente: 1.- Que haya instalada una versi?n adecuada de Python (m?nimo: 2.2; recomendable: 2.3 ? posterior). No es necesario ning?n m?dulo de integraci?n con el programa que sirve las p?ginas web. 2.- Tener acceso por l?nea de comandos con permisos suficientes como para poder ejecutar Python y para ver la estructura de directorios que define el sitio web a indexar. Para ambos puntos, quien mejor puede indicarle las posibilidades es el personal del servicio de hospedaje y/o administradores del servidor web. Salud. -- Gonzalo HIGUERA D?AZ From dfedoruk at gmail.com Thu Sep 13 09:05:58 2007 From: dfedoruk at gmail.com (Dmitri Fedoruk) Date: Thu, 13 Sep 2007 13:05:58 -0000 Subject: lxml + mod_python: cannot unmarshal code objects in restricted execution mode Message-ID: <1189688758.587404.139360@r29g2000hsg.googlegroups.com> Hello everyone, I'm developing a mod_python application that is based on XML\XSLT transforming. I used 4Suite libraries for that, but as the speed was unacceptable for me, I switched to lxml. Everything became much easier and 10 times faster, but I've encountered the subject problem. In brief - all my data and xslt are stored and transferred in UTF-8. With 4Suite everything was fine all the time. With lxml it works fine from the console, but inside mod_python it occasionaly dies, ~ one time out of three. Strange - the same code with the same data works or dies by its own means. As far as I have found, there was a similar problem with PyXML and encodings module, but there was no clear solution. So, my configuration is the following: Python 2.5.1 Server version: Apache/2.2.4 (FreeBSD) mod_python-3.3.1 And the relevant parts of my code are these: def extApplyXslt(xslt, data, logger ): try: strXslt = urllib2.urlopen(xslt).read() # i have to read the xslt url to the python string except urllib2.HTTPError, e: ....... except urllib2.URLError, e: ............. try: xslt_parser = etree.XMLParser() xslt_parser.resolvers.add( PrefixResolver("XSLT") ) # and now I have to use the string; a more elegant solution, anyone? f = StringIO(strXslt) xslt_doc = etree.parse(f, xslt_parser) # and here where the problem comes transform = etree.XSLT(xslt_doc) except Exception, exc: logger.log(logging.CRITICAL, exc.__str__() ) try: result_tree = transform(data) return etree.tostring(result_tree, 'utf-8') except Exception, exc: print "xslt processing error!", exc.__str__() return "" It dies with the message 'cannot unmarshal code objects in restricted execution mode'. By profiling I detected the point where problem occurs: transform = etree.XSLT(xslt_doc) So, I would be grateful for any suggestions how to get rid of this. I'd really like to use lxml. Maybe I should initialize the xslt processor in somehow other way? Thanks in advance, Dmitri From xcolwell at gmail.com Tue Sep 11 18:37:00 2007 From: xcolwell at gmail.com (brien colwell) Date: Tue, 11 Sep 2007 15:37:00 -0700 Subject: common/static code Message-ID: hey all, I have a slew of functions that are shared across several scripts. What's the best way to factor them out into a single location? many thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From taleinat at gmail.com Wed Sep 12 04:37:49 2007 From: taleinat at gmail.com (Tal Einat) Date: Wed, 12 Sep 2007 01:37:49 -0700 Subject: Excel process still running after program completion - SOLVED In-Reply-To: <1189531772.257865.292510@k79g2000hse.googlegroups.com> References: <1189525558.721174.198370@19g2000hsx.googlegroups.com> <1189531603.894247.218710@r29g2000hsg.googlegroups.com> <1189531772.257865.292510@k79g2000hse.googlegroups.com> Message-ID: <1189586269.487303.234660@50g2000hsm.googlegroups.com> On Sep 11, 8:29 pm, Chris wrote: > On Sep 11, 1:26 pm, Chris wrote: > > > > > On Sep 11, 12:59 pm, "Hamilton, William " wrote: > > > > > From: Chris > > > > > I have a python script that is driving Excel and using the win32com > > > > module. However, upon program completion there's still an Excel.exe > > > > process running in the background that I must terminate through Task > > > > Manager. Reading up on other threads indicate that maybe I still have > > > > some Excel objects referenced within my code. Is this why the process > > > > doesn't terminate? > > > > > The related (I hope) parts of my code is here. > > > > > x1App = Dispatch("Excel.Application") > > > > Book1 = x1App.Workbooks.Open(ExcelLogPath+"\\outputLog-template.xls") > > > > x1App.Visible = 1 > > > > for sheets in Book1.Worksheets: > > > > if sheets.Name == file_name: > > > > sheetExists = True > > > > if sheetExists != True: > > > > activeSheet = > > > > Book1.Worksheets.Add(After=Book1.Worksheets(1)) > > > > activeSheet.Name = file_name > > > > testNum[file_name] = 0 > > > > Book1.Worksheets(file_name).Select() > > > > Book1.ActiveSheet.Cells(1+(testNum[file_name]*20),1).Value = "Original > > > > File Name" > > > > Book1.ActiveSheet.Cells(2+(testNum[file_name]*20),1).Value = > > > > file_name > > > > Book1.ActiveSheet.Pictures().Insert(output).Select() > > > > Book1.SaveAs(Filename=path) > > > > x1App.ActiveWorkbook.Close(SaveChanges=0) > > > > x1App.Quit() > > > > del x1App > > > > del Book1 > > > > del activeSheet > > > > > What am I missing? > > > > In my Excel projects, I terminate it with: > > > > xlBook.Close() > > > xlApp.Quit() > > > > I haven't had a problem with Excel staying open after the program ends. > > > > (On a tangent, I want to find the person who thought it was a good idea > > > to use the same symbol in a font for 1, l, and I and do some unpleasant > > > things.) > > > > -- > > > -Bill Hamilton > > > That doesn't really fix the problem as I'm pretty sure its identical > > code for > > x1App.ActiveWorkbook.Close(SaveChanges=0) > > > I think where my problem lies is within my for each loop where I > > search to see if the worksheet with the name already exists > > for sheets in Book1.Worksheets: > > if sheets.Name == file_name: > > sheetExists = True > > > Since I'm assuming that it creates objects for each of the sheets and > > I don't delete them... > > Which I'm right... I added this code and now there's no EXCEL.EXE > process after my script completes > > for sheets in Book1.Worksheets: > if sheets.Name == file_name: > sheetExists = True > sheets = None > del sheets You just need to 'del sheets' once after the loop, no need to do it in every iteration. After your original loop the 'sheets' variable still pointed to the last sheet object, probably causing it not to be properly cleaned up. This is the only thing that your change fixes, but it is simpler (and more readable) to just do it once after the loop. (Please add SOLVED or FIXED to the subject when your issue has been resolved, so that people like me don't read the whole thread only to find that their help is no longer needed.) - Tal From zzbbaadd at aol.com Fri Sep 7 02:09:58 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 06 Sep 2007 23:09:58 -0700 Subject: startswith( prefix[, start[, end]]) Query In-Reply-To: <46e00d7e$0$16413$426a74cc@news.free.fr> References: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> <46e00d7e$0$16413$426a74cc@news.free.fr> Message-ID: <1189145398.081080.59580@r34g2000hsd.googlegroups.com> > Else, you could as well write your own testing function: > > def str_starts_with(astring, *prefixes): > startswith = astring.startswith > for prefix in prefixes: > if startswith(prefix): > return true > return false > What is the reason for startswith = astring.startswith startswith(prefix) instead of astring.startswith(prefix) From tuomas.vesterinen at pp.inet.fi Tue Sep 4 06:34:54 2007 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Tue, 04 Sep 2007 10:34:54 GMT Subject: Undeterministic strxfrm? Message-ID: Python 2.4.3 (#3, Jun 4 2006, 09:19:30) [GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> def key(s): ... locale.setlocale(locale.LC_COLLATE, 'en_US.utf8') ... return locale.strxfrm(s.encode('utf8')) ... >>> first=key(u'maupassant guy') >>> first==key(u'maupassant guy') False >>> first '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xf5\xb79' >>> key(u'maupassant guy') '\x18\x0c \x1b\x0c\x1e\x1e\x0c\x19\x1f\x12 $\x01\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x01\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x01\xb5' >>> May be this is enough for a sort order but I need to be able to catch equals too. Any hints/explanations? From metawilm at gmail.com Tue Sep 25 02:25:45 2007 From: metawilm at gmail.com (metawilm at gmail.com) Date: Mon, 24 Sep 2007 23:25:45 -0700 Subject: Nested For and While Statements In-Reply-To: <1190664644.936871.57050@57g2000hsv.googlegroups.com> References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> <1190664644.936871.57050@57g2000hsv.googlegroups.com> Message-ID: <1190701545.148197.191090@o80g2000hse.googlegroups.com> On Sep 24, 10:10 pm, Zentrader wrote: > > Your for loops both use the same counting index. > > Since those variables are local to the for loop, No, "for" loops don't introduce a scope. The one variable named "j" is shared. > for j in range( 10 ): > print j, "first loop" > for j in range( 5 ): > print " ", j, "2nd loop" The reason it does work as hoped, is that the generators, including those created by the call to "range", keep internal state to know the next value to yield. The existence or current value of iteration variables like "j" is completely irrelevant. Here, the first the call to "range" creates a generator, and binds j to the first value yielded, which is 0. Then the second range- generator is created, iterated over using the same variable. Then the first generator is asked for its second value (= 1), and j is bound to that regardless its current value. - Willem From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Sep 20 11:34:55 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 20 Sep 2007 17:34:55 +0200 Subject: Lookup values from one table to another based on a value In-Reply-To: <1190298876.689060.44540@d55g2000hsg.googlegroups.com> References: <1190298876.689060.44540@d55g2000hsg.googlegroups.com> Message-ID: <46f2930a$0$9505$426a74cc@news.free.fr> koutoo at hotmail.com a ?crit : > If I wanted to accomplish looking up values from one table based on a > value from another table or file, how would I go about doing this in > Python? Would I build a dictionary or an array? > > exp: > > Table1: > > Site = 103 > Lane = 2 > Dir = ? # Get this from Table2 > > Table2: > > Site, Lane, Direction, > 103, 1, 1 > 103, 2, 1 > 103, 3, 5 > 103, 4, 5 > > Normally in Access I would just use a Dlookup and be done with it, or > use a Recordset in VB. Thanks guys. What about using a database ? Like SQLite ? Else, the canonical data structure for quick lookups is of course the dict. From lew at lewscanon.com Wed Sep 19 17:52:59 2007 From: lew at lewscanon.com (Lew) Date: Wed, 19 Sep 2007 17:52:59 -0400 Subject: The meaning of a = b in object oriented languages In-Reply-To: References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> <1190098656.030658.66380@57g2000hsv.googlegroups.com> <_4OdnQm5joyO1m3bnZ2dnUVZ_tuonZ2d@comcast.com> Message-ID: Lew wrote: >> Java is a strongly-typed, compiled language which means it does more >> static type checking and thus would reject treating a as both an array >> and a String. >> In that environment the programmer must choose one or the other. Ken Bloom wrote: > In this Java example, a and b are statically typed to be of type Object. > Both Strings and Arrays [sic] descend from Object. (And primatives [sic] like > integers and the like will be autoboxed into descendants of Object). That doesn't make Strings and arrays assignment compatible, and besides, it isn't so. It was not stated by the OP that they were statically typing the variable to Object. In fact, their example used a type "Animal". They also used the syntax "a[1]", which is not possible in Java with a variable of type Object. So clearly a and b are /not/ statically typed to Object. Unless you meant "/if/ a and b are statically typed [to] Object" that the assignment will work, which is true but of sharply limited usefulness. In that case, you are a) defeating Java's type system and b) not getting the benefit of the Stringness or arrayness of the variable. This is in contrast to the dynamically-typed languages wherein the variable will behave like an object of the runtime type, unlike in Java. Back to the OP's example: Summercool wrote: >> so that's why a[1] = "foobar" will change what b will display, but >> a = "foobar" will not change what b will display. Again, this cannot be done in Java. The same variable a cannot be set to a String and still be used with array syntax. -- Lew From brian.e.munroe at gmail.com Mon Sep 3 11:03:25 2007 From: brian.e.munroe at gmail.com (Brian Munroe) Date: Mon, 03 Sep 2007 15:03:25 -0000 Subject: Adding attributes stored in a list to a class dynamically. In-Reply-To: <13do3c36rlqn873@corp.supernews.com> References: <1i3t9va.1jkz4om1sajk8pN%aleax@mac.com> <1188769303.724140.248630@d55g2000hsg.googlegroups.com> <13dmehro14cjp05@corp.supernews.com> <1188794274.562413.70140@k79g2000hse.googlegroups.com> <13do3c36rlqn873@corp.supernews.com> Message-ID: <1188831805.550310.295170@g4g2000hsf.googlegroups.com> On Sep 3, 6:34 am, Steven D'Aprano wrote: > The underscore versions are for customizing the lookup process, not for > dynamically looking up names. If your class needs to do something non- > standard when you write obj.name, you might need to write methods > __getattr__ etc. > I absolutely understand that much. > > In a nutshell: getattr() etc. are for looking up attributes dynamically > when you don't know the name of the attribute until runtime. __getattr__ > etc. are for looking up attributes when you need to compute the value on > the fly. (But an easier, less troublesome way of doing that > is with properties.) > If I think about this in the context of a property, which in my newbie mind gives you the ability to 'override' the standard behavior when getting, setting or I suppose deleting a specific attribute. I think I understand what you meant by 'compute the value on the fly', the keyword being *compute*? thanks for taking the time to explain this (over and over, heh!) -- brian From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 24 07:23:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 24 Sep 2007 13:23:03 +0200 Subject: sorting a list numbers stored as strings In-Reply-To: <1190632366.863711.100680@y42g2000hsy.googlegroups.com> References: <1190632366.863711.100680@y42g2000hsy.googlegroups.com> Message-ID: <46f79e04$0$30457$426a34cc@news.free.fr> aine_canby at yahoo.com a ?crit : > hi, > > I have the following list - > > ["1", "11", "2", "22"] > > how do I sort it like this - > > ["1", "2", "11", "22"] source = ["1", "11", "2", "22"] result = [t[1] for t in sorted((int(item), item) for item in source)] print result From robin at NOSPAMreportlab.com Sat Sep 22 10:28:17 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sat, 22 Sep 2007 15:28:17 +0100 Subject: Odd files; just left behind? In-Reply-To: References: <878x725ts7.fsf@pobox.com> <46F191DF.7000908@jessikat.plus.net> <46f2bd9b$0$20143$426a74cc@news.free.fr> <46F38FBC.7090903@chamonix.reportlab.co.uk> Message-ID: <46F52681.5090409@jessikat.plus.net> Robert Kern wrote: ....... > > They're a cache. they're actually the files that get used by the installed extension in this case (MySQLdb). .......... >> >> it would seem simpler to have the .so files inside the site-packages and there's >> the question of why this folder has to be obfuscated (name starts with .). Even >> if these files are "resources" why should they be assumed to belong to the user? > > Because they are unpacked at runtime by the user that imported the module. > Usually, they won't have write access to site-packages. > in this particular case the python being used was installed with a user prefix eg /myhome/PYTHON so everything belongs to the user; extensions installed by the same user can surely be installed in those folders. Upon checking I find that the same installs which produced the ~/.python-eggs files also managed to put the eggs like MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg inside the various site-packages directories. I see no reason why the binary resources shouldn't be unpacked to site-packages at install time. It seems reasonable that since install time is the only time an egg install can reasonably expect to write to the install area then that's when these resources should be unpacked. The zipapp install system referred to by John Lee does it that way because in practice we find we do need to install on CD's etc. What happens if I as a naive idiot install an egg to a write once file system? I suppose the assumption is that we don't mind such files being created in the user's space. Spewing stuff all over some else's disk at run time instead of doing it once at install is wrong and may not even be possible. It also allows for the carefully crafted binary extensions to be substituted by anyone with write permission to the cache folder. -- Robin Becker From http Thu Sep 20 15:32:52 2007 From: http (Paul Rubin) Date: 20 Sep 2007 12:32:52 -0700 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87odfxjgjy.fsf@pobox.com> Message-ID: <7x4phpt9nf.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > Seriously for a moment, I read something recently (maybe here?) about > an Apple study that claimed to show that people who perceived keyboard > bindings as being much faster than mouseing did not, on average, take > less time to complete the actions that were studied (they took more > time, in fact). The plausible explanation for this was that people's > subjective perception of time is affected by the greater mental work > involved in typing (as opposed to mousing) for a given action. I think mousing takes more mental work than typing, and that's why it subjectively seems slower even if a stopwatch shows it to be faster. I have IM text chats with my officemate all the time even though he's sitting about 4 feet away from me and I could easily talk to him and that would probably be faster. But text chat needs less mental effort since it doesn't take my attention away from symbols on the screen, i.e. when the chat topic is something simple, I don't lose mental context of the program I'm working on and then have to spend time getting the context back. In that sense, text chats save time compared with regular conversations even though they're slower. Of course if the chat subject gets complicated and starts needing careful thought, then it's better to switch to conversation, and sometimes we both simultaneously realize that and start talking to each other or using the whiteboard. From fabiofz at gmail.com Mon Sep 10 09:02:42 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 10 Sep 2007 10:02:42 -0300 Subject: Setting stdout encoding In-Reply-To: <1189416350.069995.220250@w3g2000hsg.googlegroups.com> References: <1189416350.069995.220250@w3g2000hsg.googlegroups.com> Message-ID: > > > Does someone know if there's a way to explicitly set the stdout/stderr/ > stdin > encoding that python should use? > > The encoding can be set using the C API for file objects - from Python > code, use ctypes: > > Yeap, but that would leave me with the original problem: I need to run a script to run the original script I want to run...(and not being compatible with other python implementations). Isn't there any way to set that externally (like environment variable, args to the interpreter or anything else like that)? Thanks, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Sep 20 05:25:04 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Sep 2007 09:25:04 -0000 Subject: Mixin classes and single/multiple inheritance References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> <877immvye0.fsf_-_@benfinney.id.au> <1190257864.945639.199230@k79g2000hse.googlegroups.com> <87y7f2uhpp.fsf@benfinney.id.au> <1190262607.684957.49610@57g2000hsv.googlegroups.com> <87myviuee5.fsf@benfinney.id.au> Message-ID: <13f4f3g682udg28@corp.supernews.com> On Thu, 20 Sep 2007 14:52:50 +1000, Ben Finney wrote: > Can you give a code example of how you think mixins should be > implemented in Python, assuming the absence of multiple inheritance? I'll take a shot at it... use automatic delegation to the mixin class. class Parrot(object): def fly(self): return "The parrot can fly short distances." def talk(self): return "I'm pining for the fjords." class Albatross(object): def fly(self): return "The albatross is known to fly enormous distances." # Now I want a talking Albatross, without using multiple inheritance. class TalkingAlbatross(Albatross): def __init__(self, *args, **kwargs): # avoid triggering __setargs__ self.__dict__['mixin'] = Parrot() # avoid using super() so Ben doesn't get cranky self.__class__.__base__.__init__(self, *args, **kwargs) def __getattr__(self, name): return getattr(self.mixin, name) def __hasattr__(self, name): return hasattr(self.mixin, name) def __delattr__(self, name): return delattr(self.mixin, name) def __setattr__(self, name, value): return setattr(self.mixin, name, value) Am I close? -- Steven. From f.guerrieri at gmail.com Sat Sep 29 10:58:07 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Sat, 29 Sep 2007 16:58:07 +0200 Subject: Python 3.0 migration plans? In-Reply-To: <1191005046.213630.13340@57g2000hsv.googlegroups.com> References: <1190993122.979034.305060@50g2000hsm.googlegroups.com> <1190997769.002795.59450@57g2000hsv.googlegroups.com> <5m4qc2Fbbk19U1@mid.uni-berlin.de> <1191000394.828693.285210@k79g2000hse.googlegroups.com> <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005046.213630.13340@57g2000hsv.googlegroups.com> Message-ID: <79b79e730709290758p63c200a9q175e9456a6ee3688@mail.gmail.com> On 9/28/07, TheFlyingDutchman wrote: > Correct me if I am wrong, but none of those examples showed something > in C++ similar to a decorator in Python - that is, unique syntax in > the language for implementing a Higher Order Function. One thing I > will say about those examples is that they make Python decorators look > sweet! That is exactly one of the points in having decorators, as far as I can tell. Namely, that higher order functions are easily implemented, if and when needed. Francesco From nagle at animats.com Sat Sep 29 11:25:49 2007 From: nagle at animats.com (John Nagle) Date: Sat, 29 Sep 2007 08:25:49 -0700 Subject: Python and SSL In-Reply-To: <7x641u0zvl.fsf@ruckus.brouhaha.com> References: <1190959345.041723.108130@k79g2000hse.googlegroups.com> <46fd7e7b$0$18410$9b622d9e@news.freenet.de> <7x641u0zvl.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Martin v. L?wis" writes: >>> But how can I tell my Python program to trust my SSL certificate? >> Why do you want to tell it that? The SSL module will trust *any* >> server certificate, no need to tell it explicitly which ones to >> trust. > > Er, the whole idea of SSL is that you don't trust the connection. So > failing to authenticate the other end is a security failure and SSL > should not be used that way. From RFC 4346: > > Warning: Completely anonymous connections only provide protection > against passive eavesdropping. Unless an independent > tamper-proof channel is used to verify that the finished > messages were not replaced by an attacker, server > authentication is required in environments where active > man-in-the-middle attacks are a concern. Right. The key point here is that Python's standard SSL module doesn't actually check the validity of SSL certificates. It just makes client connections without checking. It will happily connect to sites offering totally bogus certificates, even ones with the wrong domain name. M2Crypto actually checks. M2Crypto has much better functionality, but it's rather hard to build. John Nagle From ricaraoz at gmail.com Thu Sep 6 13:22:21 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 06 Sep 2007 14:22:21 -0300 Subject: Text processing and file creation In-Reply-To: <2dc0c81b0709051003n6b81493ah373ce626e172309e@mail.gmail.com> References: <1189008809.718361.45790@g4g2000hsf.googlegroups.com> <2dc0c81b0709051003n6b81493ah373ce626e172309e@mail.gmail.com> Message-ID: <46E0374D.5060102@bigfoot.com> Shawn Milochik wrote: > On 9/5/07, malibuster at gmail.com wrote: >> I have a text source file of about 20.000 lines. >> >From this file, I like to write the first 5 lines to a new file. Close >> that file, grab the next 5 lines write these to a new file... grabbing >> 5 lines and creating new files until processing of all 20.000 lines is >> done. >> Is there an efficient way to do this in Python? >> In advance, thanks for your help. >> Maybe (untested): def read5Lines(f): L = f.readline() while L : yield (L,f.readline(),f.readline(),f.readline(),f.readline()) L = f.readline() in = open('C:\YourFile','rb') for fileNo, fiveLines in enumerate(read5Lines(in)) : out = open('c:\OutFile'+str(fileNo), 'wb') out.writelines(fiveLines) out.close() or something similar? (notice that in the last output file you may have a few (4 at most) blank lines) From jfine at pytex.org Wed Sep 19 10:52:55 2007 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 19 Sep 2007 15:52:55 +0100 Subject: Metatest 0.1.0 References: <1190130384.753009.142150@i13g2000prf.googlegroups.com> <46F006D5.3060609@pytex.org> <1190147863.968759.229330@g4g2000hsf.googlegroups.com> <46F05FB1.7070807@pytex.org> <1190196516.575165.175880@50g2000hsm.googlegroups.com> Message-ID: <46F137C7.6080607@pytex.org> Kay Schluehr wrote: > On 19 Sep., 01:30, Jonathan Fine wrote: > > >>>there is no fundamental reason why it can't be separated from >>>eeconsole.py. >> >>OK. That might be a good idea. > > > Ironically, I liked the idea of having more expressive assert > statements - a discussion you brought up. But this requires either > syntcatical analysis in the general case ( EE and assert magic ) some > particular API ( Ben Finney ) or a somewhat restricted, but fully > embedded, domain specific language ( Metatest ). > > Here is what I got after an hour of hacking and filtering assert. > Additional remarks are in line comments: Thank you for doing this coding, and providing an example of its use. It seems to me that /writing the tests/ and /running the tests/ are two distinct, although linked, matters. When programming, we are interested in running the tests. When designing, we are interested in writing the tests. And when looking at someone else's modules, we are interested in /reading the tests/. Both Metatest and EasyExtend show that we have some freedom in how we choose to write our tests. What I am interested in doing is developing and promoting a /language for writing tests/. This has both a formal side and also conventions and examples of its use. We would, of course, like that language to be Pythonic (if not exactly Python, although that would be a distinct advantage). I think we can do this without having to think too much about implementation (although it would be useful to have experience of using the language). I also think that some sort of 'filter' between the user and the Python commmand line would be useful. GNU readline is a simple, and effective, example of the sort of thing I have in mind. Thank you for discussing this with me, Kay and Ben. -- Jonathan From george.sakkis at gmail.com Thu Sep 6 23:22:49 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 07 Sep 2007 03:22:49 -0000 Subject: Passing a tuple to a function as multiple arguments In-Reply-To: References: Message-ID: <1189135369.981396.76350@r29g2000hsg.googlegroups.com> On Sep 6, 11:02 pm, Ben Warren wrote: > Hello, > > Let's say I have a function with a variable number of arguments (please ignore syntax errors): > > def myfunc(a,b,c,d,...): > > and I have a tuple whose contents I want to pass to the function. The number of elements in the tuple will not always be the same. > > T = A,B,C,D,... > > Is there a way that I can pass the contents of the tuple to the function without explicitly indexing the elements? Yes: myfunc(*T) More details at http://docs.python.org/tut/node6.html#SECTION006730000000000000000 HTH, George From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 7 11:51:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 07 Sep 2007 17:51:59 +0200 Subject: How to determine the bool between the strings and ints? In-Reply-To: References: Message-ID: <46e17398$0$31716$426a34cc@news.free.fr> Jorgen Bodde a ?crit : > Hi All, > > I have a dictionary with settings. The settinfgs can be strings, ints > or bools. I would like to write this list dynamically to disk in a big > for loop, unfortunately the bools need to be written as 0 or 1 to the > config with WriteInt, the integers also with WriteInt and the strings > with a simple Write. > > The list is something like; > > options[A] = True > options[B] = 1 > options[C] = "Hello" > > I wanted to use isinstance to determine if it is a bool or an int or a > string. However I am confused trying it out in the interactive editor; > >>>> a = False >>>> if isinstance(a, bool): > ... print "OK" > ... > OK >>>> if isinstance(a, int): > ... print "OK" > ... > OK > > I don't get it. is the bool derived from 'int' in some way? Obviously : yes !-) > What is > the best way to check if the config I want to write is an int or a > bool ? >>> isinstance(0, bool) False >>> isinstance(1, bool) False >>> But anyway, I don't get the point, since "the bools need to be written as 0 or 1 to the config with WriteInt, the integers also with WriteInt". So you just don't care if it's a bool or not ? Or did I miss something ? From jura.grozni at gmail.com Tue Sep 18 23:46:01 2007 From: jura.grozni at gmail.com (azrael) Date: Wed, 19 Sep 2007 03:46:01 -0000 Subject: Help, I'm going mad with this Message-ID: <1190173561.822713.200070@d55g2000hsg.googlegroups.com> Meanwhile I tried about 5 different implementations of the otsu threshold algorithm. I'll go mad. Please help me. I don't know what to do. I even tried to implement it from c and java, but no way. nothing. I've been reading about 5 ppt presentations and 4 pdf's and I failed. Can someone look at this code. If needed I can paste 3 other codes. Testing list: def otsu(hi): border=len(hi) for i in range(border): if hi[i]!=0:break for j in range(border-1,0-1,-1): if hi[j] != 0:break li=[] for k in range(i+1,j+1): q1=sum(hi[i:k]) q2=sum(hi[k:j+1]) v1=var(hi[i:k]) v2=var(hi[k:j+1]) a=q1*v1 + q2*v2 li.append(a) m,n=li[0],i for k in range(len(li)): if li[k]>m: m=li[k] n=k if __name__=="__main__": otsu(histogram) histogram= [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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 2, 1, 2, 0, 1, 3, 3, 3, 3, 1, 3, 1, 3, 5, 2, 3, 3, 3, 6, 3, 4, 5, 4, 9, 6, 11, 6, 10, 3, 11, 9, 9, 12, 22, 18, 34, 22, 28, 32, 25, 34, 38, 34, 54, 65, 106, 160, 167, 203, 282, 364, 446, 637, 816, 1022, 1264, 1456, 1646, 1753, 1845, 1922, 2203, 2231, 1973, 2245, 2369, 2349, 2258, 2130, 2066, 1835, 1640, 1554, 1414, 1179, 1024, 974, 938, 838, 785, 756, 803, 921, 952, 865, 722, 625, 608, 547, 498, 412, 438, 408, 413, 415, 339, 366, 330, 320, 293, 315, 368, 411, 434, 500, 531, 538, 552, 665, 811, 869, 998, 1021, 1075, 1080, 1030, 934, 926, 1074, 942, 941, 1014, 1440, 2966, 5301, 2729, 3400, 5563, 13096, 9068, 6045, 2813, 686, 180] Well, this list is a example list that i have exported. for this list the result the threshold should be at 218. Thanks From __peter__ at web.de Mon Sep 24 03:03:02 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Sep 2007 09:03:02 +0200 Subject: strange behavious of the logging module? References: Message-ID: Christian Meesters wrote: > Also, adding %(funcName)-8s to the formatter in basigConfig does not work > for me: instead of the functions name the level in lower case gets inserted > into the logfile. When you call logging.info(...), "info" actually is the function name. As a workaround use logging.getLogger(...).info(...). It would still be a good idea to file a bug report. Peter From wolf_tracks at invalid.com Thu Sep 20 23:24:40 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 21 Sep 2007 03:24:40 GMT Subject: An Editor that Skips to the End of a Def In-Reply-To: References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> Message-ID: Is vim just an editor or is it capable of running and debugging a program, as well? W. Watson wrote: > Maybe I'll take a look. When I left the world of Unix/Linux 10 years > ago, emacs went with it, as did vi. > > Paul Rudin wrote: >> "W. Watson" writes: >> >>> Thanks, but no thanks. The learning curve is way too steep. >> >> Up to you but, these days emacs comes with all sorts of >> pointing-clicky-menu-y type things - you don't really have to learn >> anything to get started. >> >> (It even gives useful advice on top-posting if you use it as a news >> client :/) > -- Wayne Watson (Nevada City, CA) Web Page: From bert at bertisevil.tv Tue Sep 18 20:48:27 2007 From: bert at bertisevil.tv (Evil Bert) Date: Tue, 18 Sep 2007 17:48:27 -0700 Subject: Sets in Python In-Reply-To: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> Message-ID: sapsi wrote: > 2) This is not related, but is there i neat way (without pop and list > comprehension) to convert a set into a list? I say neat because i'm > guessing using list comprehension might turn out be slow and there > might be other methods which are faster. a = set([1, 2, 3, 4]) b = list(a) From steven.bethard at gmail.com Mon Sep 24 15:19:49 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Sep 2007 13:19:49 -0600 Subject: Can a base class know if a method has been overridden? In-Reply-To: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> References: <1190647436.423328.217670@w3g2000hsg.googlegroups.com> Message-ID: Ratko wrote: > I was wondering if something like this is possible. Can a base class > somehow know if a certain method has been overridden by the subclass? You can try using the __subclasses__() method on the class:: >>> def is_overridden(method): ... for cls in method.im_class.__subclasses__(): ... func = cls.__dict__.get(method.__name__) ... if func is not None and func != method.im_func: ... return True ... return False ... >>> class A(object): ... def foo(self): ... return 'A.foo' ... def bar(self): ... return 'A.bar' ... >>> class B(A): ... def foo(self): ... return 'B.foo' ... >>> is_overridden(A.foo) True >>> is_overridden(A.bar) False Given a method from the base class, is_overridden gets the base class, and then looks through every subclass of that class. If the function object for the subclass is ever different from that of the base class, then the base class's method must have been overridden. STeVe From steve at REMOVE-THIS-cybersource.com.au Wed Sep 12 08:52:55 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 12 Sep 2007 12:52:55 -0000 Subject: An ordered dictionary for the Python library? References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> Message-ID: <13efo979vs6b44e@corp.supernews.com> On Wed, 12 Sep 2007 09:51:02 +0200, stef wrote: > If you're going to extend the dictionary, there's one other flag I'm > continuously missing: "case-insensitive" key. Completely untested and probably buggy as anything, but here's an absolutely minimal case-insensitive dictionary. class CaselessDict(dict): def __setitem__(self, key, value): super(CaselessDict, self).__setitem__(key.lower(), value) def __getitem__(self, key): return super(CaselessDict, self).__getitem__(key.lower()) -- Steven. From apardon at forel.vub.ac.be Sat Sep 29 09:49:45 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Sep 2007 13:49:45 GMT Subject: sorteddict [was a PEP proposal, but isn't anymore!] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190829592.800804.242260@50g2000hsm.googlegroups.com> <1190881576.186259.313720@57g2000hsv.googlegroups.com> <1190897445.179828.291720@y42g2000hsy.googlegroups.com> Message-ID: On 2007-09-27, gatti at dsdata.it wrote: > Is this a practical use case? When are sequential visits of all > elements in order frequently suspended to make insertions and > deletions, with a need for efficient lookup by key? Does it need to be a sequential visit of *all* elements? Suppose you have a mapping of start times to tasks. You can then want to iterate over all tasks that need to be started between noon en 4 pm next monday. If you have a hashtable you still will need to sort all the keys even if you will visit only 10%. If you have a tree you can just visit the specified keys. -- Antoon Pardon From kelvie at ieee.org Sun Sep 23 16:15:10 2007 From: kelvie at ieee.org (Kelvie Wong) Date: Sun, 23 Sep 2007 13:15:10 -0700 Subject: building a GUI In-Reply-To: <5lnp2rF90pqqU1@mid.uni-berlin.de> References: <1190557293.266783.251480@y42g2000hsy.googlegroups.com> <5lnp2rF90pqqU1@mid.uni-berlin.de> Message-ID: <94ccbe710709231315s314971acpddbeb7eac0178fd8@mail.gmail.com> On 9/23/07, Diez B. Roggisch wrote: > > stef mientki schrieb: > > Thomas Dybdahl Ahle wrote: > >> Den Sun, 23 Sep 2007 17:28:38 +0200 skrev stef mientki: > >> > >>> yadin wrote: > >>> > >>> > >>>> if i were up to make a GUI chich are the advantages of choosing > python > >>>> over matlab or java? > >>>> > >>>> > >>> The best is Delphi, > >>> second is VB, > >>> > >> > >> That sounds mostly like a personal preference :) > >> > >> > > Well I prefer Python ( because of it's OS-independancy and it's open > > source), > > but Python is really (still) much worse for GUI designs. > > Just compare some parameters like: > > - ease of use > > - speed of development > > - support of features > > - availability of libraries > > - documentation > > Sounds like PyQt for me. Best GUI-designer I know, tremendous speed in > development, giant sized lib that does all kinds of stuff & is > brilliantly designed + professional grade docus. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > I'll have to agree completely here, Qt is just so great to work with. It makes my day job (I have to do it in C++) much more bearable. Phil Thompson (who maintains PyQt) is also very responsive and updates frequently even if you haven't bought a commercial licence for it. I also have to agree that the Qt Designer is the best I've ever had to work with, and I can't think of an instance where Qt Assistant wasn't open on one desktop or another. -- Kelvie -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Sep 30 23:47:29 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Sep 2007 23:47:29 -0400 Subject: Using fractions instead of floats References: <1191202509.853059.222530@k79g2000hse.googlegroups.com><1191206183.441075.167450@57g2000hsv.googlegroups.com><52c50880709302007g4103c6c6h9b09ee376fa77998@mail.gmail.com> <52c50880709302010n7cbc070fn6223bd94a67542dd@mail.gmail.com> Message-ID: "Andres Riofrio" wrote in message news:52c50880709302010n7cbc070fn6223bd94a67542dd at mail.gmail.com... | a question: Is there a way to make 5/2 return something other than an | integer? >>> from __future__ import division >>> 1/2 0.5 >>> 5/2 2.5 tjr From mitko at qlogic.com Wed Sep 5 18:58:20 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Wed, 5 Sep 2007 15:58:20 -0700 Subject: Need help with strange segfault Message-ID: <20070905155820.4e9379bf@opal.pathscale.com> I am attempting to get a working wrapper around the TransactionSet class from the rpm module but I am getting unexplained segfaults in /usr/bin/python. The reason why I am working on a wrapper is that I want to have a single RPM abstraction module which is thread-safe and does not tie up the RPM database. So here is my wrapper class: class Transaction: def __init__ (self, db=None): self.ts = None self.ts_lock = Lock () self.db = db self.func = None # This method will acquire the lock, record the TransactionSet # method being called by the caller and return the pointer to # the call_ts_func () function, which will do all the work. def __getattr__ (self, name): self.ts_lock.acquire () self.func = name return self.call_ts_func # This method serves as a wrapper around the actual TransactionSet # method being called. It will open the database, call the # TransactionSet method, close the databse, and then release the # lock acquired in the __getattr__ () function. def call_ts_func (self, *args): if not self.ts: if self.db: rpm.addMacro ("_dbpath", self.db) self.ts = rpm.TransactionSet () self.ts.openDB () if self.db: rpm.delMacro ("_dbpath") func = self.ts.__getattribute__ (self.func) rs = func (*args) self.func = None self.ts.clean () self.ts.closeDB () del self.ts self.ts = None self.ts_lock.release () return rs I am getting what appears to be a correct value in rs but as soon as I try to access it from the caller function, Python segfaults. Any help would be appreciated? -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== Any programming language is at its best before it is implemented and used. From bignose+hates-spam at benfinney.id.au Mon Sep 24 21:06:44 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 25 Sep 2007 11:06:44 +1000 Subject: vim - what's a smarttab? References: <1190624225.926815.149720@50g2000hsm.googlegroups.com> Message-ID: <878x6vpn8b.fsf@benfinney.id.au> 7stud writes: > Alternatively, what is a smarttab? (Marco has already shown that you can read the Vim help for this topic, so I won't repeat that.) There's no such thing as "a smarttab", and that's not what the option means. It's the name of an option that enables or disables a certain behaviour. You can think if it, rather, as "smart handling of the key". -- \ Rommel: "Don't move, or I'll turn the key on this can of Spam!" | `\ -- The Goon Show, _Rommel's Treasure_ | _o__) | Ben Finney From jjl at pobox.com Thu Sep 20 15:23:56 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 20 Sep 2007 19:23:56 GMT Subject: cannot create my own dict References: <46f17c26$0$26298$426a74cc@news.free.fr> Message-ID: <87d4wdjg38.fsf@pobox.com> "A.T.Hofkamp" writes: [...] > I can derive from dict, but the problem with that is that I start with a > read/write dictionary, and I can only hope to plug all holes to prevent my data > from leaking out. > By starting from 'object', I certainly don't have that problem, I start with a > closed bucket and punch holes in it in a controlled way. > (I rather have the program drop dead due to not having enough access than > have it continue with too much access causing havoc 500 statements later in a > totally unrelated area.) > > Rather than write a bunch of code like > > def __contains__(self, val): > return val in self.mydict > > I thought I'd simply do > > self.__contains__ == self.d.__contains__ > > which is exactly the same but less work (or so I thought), and possibly > slightly faster. > > Well, no such luck thus :-( UserDict.DictMixin http://docs.python.org/lib/module-UserDict.html John From gherzig at fmed.uba.ar Thu Sep 20 19:26:46 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 20 Sep 2007 20:26:46 -0300 Subject: executing list of methods (and collecting results) Message-ID: <46F301B6.10801@fmed.uba.ar> Hi all. Im in this situation: I want to perform several kind of (validating) methods to a given value. Lets say i have a class named Number, and the following methods: is_really_a_number(), is_even(), is_greater_than_zero(), and so on. All of them returning booleans. I want the collect_validators() method is to execute any of the above methods, and collect their names as items of a list (wich will be the collect_validators() return value). My first approach is: [code] def collect_validators(self): v_dict = { 'is_really_a_number': is_really_a_number, 'is_even': is_even, 'is_greater_than_zero', is_greater_than_zero } for name, meth in v_dict.items(): result = meth() if result: yield name [/code] I wondering if is this a good pattern to apply, i like the way it looks like, at least to me it looks `natural', but...im calling every method twice here? One in v_dict and again on the dict iteration? Any suggestion will be great! Thanks! Gerardo From Shawn at Milochik.com Tue Sep 11 16:46:52 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Tue, 11 Sep 2007 16:46:52 -0400 Subject: Difference between two times (working ugly code, needs polish) Message-ID: <2dc0c81b0709111346p6ef754a4v30882cea06020aee@mail.gmail.com> I have done what I wanted, but I think there must be a much better way. Given two timestamps in the following format, I just want to figure out how far apart they are (in days, seconds, whatever). Format: YYYY-MM-DD_MM:SS Example: 2007-09-11_16:41 It seems to me that to do what I want, I need to convert a string into a number (time.mktime()), such as this: 1189543487.0 Once I have that, I can just subtract one from the other and do whatever I want. The ugly part is converting something like 2007-09-11_16:41 to the numeric equivalent. Below is my code. Any suggestions? Thanks in advance. Here is what I have (works): #runTimeStamp is the current time, set when the script begins execution def recAge(lastUpdate, runTimeStamp): import re oneDay = 60 * 60 * 24 lastUpdate = re.sub(r'\D+', ',', lastUpdate) lastUpdate = lastUpdate + ",0,0,0,0" lastUpdate = [int(x) for x in lastUpdate.split(',')] lastUpdate = time.mktime(tuple(lastUpdate)) runTimeStamp = re.sub(r'\D+', ',', runTimeStamp) runTimeStamp = runTimeStamp + ",0,0,0,0" runTimeStamp = [int(x) for x in runTimeStamp.split(',')] runTimeStamp = time.mktime(tuple(runTimeStamp)) return (runTimeStamp - lastUpdate) / oneDay From bjorn.kempen at gmail.com Sat Sep 15 15:21:50 2007 From: bjorn.kempen at gmail.com (buffi) Date: Sat, 15 Sep 2007 19:21:50 -0000 Subject: Python statements not forcing whitespace is messy? Message-ID: <1189884110.006272.240840@50g2000hsm.googlegroups.com> Am I the only one that thinks that python statements should force whitespace before and after them? Right now this is not enforced and for an example these statements are valid print"hello" "foo"if"bar"else"foobar" for(x,y)in[(1,2),(3,4)]:print(x,y) [(y)for(x,y)in[("foo",2),("bar",4)]if"foo"in(x)] ...and so on. I know that writing code like this really shouldn't be done but wouldn't it be a good idea to enforce the use of whitespace around statements? (I wrote a short blog post about this here http://blog.buffis.com/?p=55 but thought I would post here as well to see what other developers think) - Bj?rn Kemp?n From a24900 at googlemail.com Tue Sep 11 13:13:37 2007 From: a24900 at googlemail.com (Hunter Gratzner) Date: Tue, 11 Sep 2007 17:13:37 -0000 Subject: Car-ac-systems In-Reply-To: References: <1189511932.371621.112970@o80g2000hse.googlegroups.com> Message-ID: <1189530817.997394.156890@w3g2000hsg.googlegroups.com> [top posting fixed] > "Lew" wrote in message > > news:YaadnYyTWsmTAnvbnZ2dnUVZ_iydnZ2d at comcast.com... > > I'm starting to see "blogspot" as a synonym for "spam". On Sep 11, 4:33 pm, "John Timney \(MVP\)" wrote: > Thats all it is. It may have been a usefully intended resource once, but > they have no controls whatsoever. Its time someone closed it down. Blogspot, aka blogger getting closed down is very unlikely. It is a Google company. And just as Google doesn't care about Usenet spam originating via Google Groups, Google also doesn't care about spammers on Blogspot/Blogger. All they care about is making AdSense money. From hat at se-162.se.wtb.tue.nl Tue Sep 25 03:30:56 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 25 Sep 2007 09:30:56 +0200 Subject: An Editor that Skips to the End of a Def References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> Message-ID: On 2007-09-25, Lawrence D'Oliveiro wrote: > In message , Neil Cerutti wrote: > That's like saying, about a program that, when given "2 + 2", outputs "5", > that _of course_ it knows the correct answer is "4", it just chooses > to "modify" the answer before outputting it. > > Why does it "choose" to modify your position when you exit insert mode? Does > the phrase "broken as designed" mean anything to you? Try to insert 1 character in the middle of a line. You'll end up at the same position. Now press 'j' (one line down), then '.' (do it again). I believe that's why. Great when you have nicely formatted columns of code underneath each other. (try doing that with your GUI editor with 2 strokes per line of code). Of course, the same works for a find/edit cycle ('n', check whether edit is appropiate, and if so: '.') This combining of commands is what makes the editor powerful. The cost of that power is a command/insert mode and a steep learning curve. You may not like the keyboard interface, but that doesn't mean the editor is not well-designed for its task. In the same way, having the ability to use multiple input devices doesn't automatically make the editor better. For example, ever wondered why you on earth you need CTL-C and CTL-V to copy/paste? Why not simply select with the mouse, then right-click to paste? All editors have their good and their bad sides. Assuming that anything you don't like is badly designed is a bit too simple in my opinion. > And the downside is that the largest single proportion of those commands end > up being variations on "enter insert mode". Because most of the keystrokes > you enter during an editing session are in fact text to be input into the > file, not commands to manipulate that text. So in a modal editor, having to Depends on what you are doing. When entering new code, yes. When maintaining code, no (lots of small changes). In one way or another, you'll have to tell the editor what you want. The cost of that is either a command/insert mode (vi/vim), a CTL/SHIFT/META-key combination (emacs), or mouse/menu/submenu/subsubmenu (GUI editors). I don't know what is best. Probably a matter of taste. Albert From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 19 06:36:29 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 12:36:29 +0200 Subject: super() doesn't get superclass In-Reply-To: <876427zhzq.fsf@benfinney.id.au> References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> Message-ID: <46f0fba0$0$29605$426a34cc@news.free.fr> Ben Finney a ?crit : > Bruno Desthuilliers writes: > >> Ben Finney a ?crit : >>> Evan Klitzke writes: >>>> On Tue, 2007-09-18 at 14:15 +1000, Ben Finney wrote: >>>>> [the 'super' function] doesn't return the superclass, it returns >>>>> the next class in the MRO, whether that's a superclass or not. >>>> The next class in the MRO _is_ a superclass. >>> [demonstration that the next class in the MRO is not necessarily a >>> superclass] >>> >>> You seem to be saying that now suddenly D *is* a superclass of >>> A. >> I don't see such an assertion in Evan's answer. Chapter and verse >> ??? > > I've trimmed the quoting to make it clearer. > > Evan is claiming that "the next class in the MRO _is_ a superclass", > apparently by his definition or some other that I've not seen. The next class in the MRO *is* a superclass of the *instance*. Else it wouldn't be in the MRO !-) > I've shown a fairly simple multiple-inheritance hierarchy where the > next class in the MRO is not an ancestor of the subject class, It's an ancestor of the class of the instance on which the method is called. > Either "superclass of A" is equivalent to "ancestor class of A", or > it's not. I maintain that many programmers will expect that it is, but > Evan's assertion says otherwise. It can't be both. > >>> That's certainly not what users will think of when they think >>> "superclass" though. >> If a class X is in the MRO of call Y, then X is a superclass of Y. s/call/class/, of course. > That goes completely against what Alex Martelli told me, which was > that "superclass" can be thought of as synonymous with "ancestor". Pardon ??? I repeat: if class X is in the MRO of class Y, then X is a superclass of class Y. Which indeed makes X an ancestor of Y. >> I agree that the documentation for super is somewhat misleading (and >> obviously wrong), > > Well, that's the first time someone has acknowledged that in this > thread, so I guess this is something. OTHO, I don't think anyone here stated that the doc was right !-) >> but it still *give access to* (at least one of) the superclass(es). > > Only if you allow "some class somewhere in the inheritance tree, even > one this class never inherited from directly or indirectly" to be in > the definition of "superclass". By definition, if the class is in the inheritence tree, then this class is inherited from directly or indirectly. FWIW, I've never caught super() calling a class that was not in the inheritence tree of the instance passed to it... If you noticed such a thing, then by all mean fill a bug report. > I'm arguing that what people mean by "superclass" is "a direct or > indirect ancestor class", and it's highly misleading to imply that by > the function name what that's not what the function does. Please remember that super() is usually called with *2* arguments : the class in which the method is defined (let's call this class C), *and* an instance. This instance may be an instance of a *subclass* of C. So the MRO to consider is the MRO *of the instance*. Else, super would be totally useless. >>>>> After reading the rest of the article, I'm amazed that 'super' >>>>> as currently implemented is in Python at all. >> If you have a better solution for handling multiple inheritence, >> please share with us. > > My concern is to at least not *directly mislead* the programmer > through a badly-named Or badly documented > function class. super is not a function, it's a class. > If 'super' can invoke a non-superclass super won't never "invoke" anything that's not in the MRO of the *instance* passed to it. > ? if instead it gets "the next class in the MRO" ? then this is at the > least badly-named. Possibly, but this is another point. >> FWIW, after all the articles I've read explaining why Python is >> badly designed, badly implemented, and totally flawed, I do wonder >> why this language exists at all !-) > > In most of those arguments I'm firmly on the side of the Python > designers. Not on this one. Well, I understand that you disagree with both the documention and the name of super. As far as I'm concerned, the mere fact that this discussion happens is probably a sign that there's something to be fixed here - at least wrt documentation, possibly wrt/ naming. But the *feature* by itself is certainly something we do want to keep, whatever some may argue. >>> I don't want to break the inheritance chain. I want the >>> superclass, >> A soon as you have either multiple inheritence and/or an inheritence >> tree with depth > 1, there's no such thing as "the" superclass. wrt/ >> your exemple, object, A, B, C and D are *all* superclasses of E. > > Yes, they are. But my example was not "get the superclass of E", but > "get the superclass of A". You wrote: """ If I define a class hierarchy as follows:: class A(object): pass class B(object): pass class C(A): pass class D(B): pass is it true to say that "D is a superclass of A"? No, because they're entirely unrelated except that they inherit from 'object'. The superclass of 'A' is 'object'. How about this: class E(C, D): pass In this instance, the MRO now has D following A; but the superclass of 'A' is still 'object'. """ If I understand correctly, your concerns are with the superclass*es* of E, not with the superclass of A. > The *only* ancestor of 'A' in the example is 'object', Yes. > so I expect > "superclass of A" to *always* get 'object'. But that's not what > happens! superclass of A is object, no problem. But the next (according to the MRO you defined) superclass of an instance of E is not necessarily A... > Instead, it *sometimes* gets 'object', and *sometimes* gets 'D' ? > depending on who has inherited from a class that isn't even 'A'! > That's what makes 'super' definitely misnamed, Badly documented, and (very) possibly (as this whole thread illustrates) misnamed... > and practically > unusable. And perfectly usable. At least once you understand what it's for. >> The next class in the MRO is (usually and AFAICT) the most direct >> superclass. > > Demonstrably not, in the examples given in > . > >> I wouldn't use such an extreme word as 'madness', but I totally agree >> that this should be corrected. Care to submit a doc patch ? > > I don't understand what practical uses 'super' is intended for There's a whole article on it on python.org: http://www.python.org/download/releases/2.2/descrintro/#cooperation The goal is to call the correct "next" method according to MRO. Indeed, it could have been name "call_next_method". > (only > that they don't seem to match any of my needs), If all you want is to get at the direct ancestor of the *class* in wich a method is defined, the solution is well-known and quite obvious: call this class directly. ie: class A(object): def __init__(self): print "A.__init__" class B(object): def __init__(self): A.__init__(self) print "B.__init__" Note that in this case, you'll get exactly the same result with : class B(object): def __init__(self): super(B, self).__init__() print "B.__init__" super is only useful when MI comes in play - which BTW is not that common in Python. From nir1408 at gmail.com Fri Sep 21 06:28:08 2007 From: nir1408 at gmail.com (Nir) Date: Fri, 21 Sep 2007 10:28:08 -0000 Subject: pdb attach? In-Reply-To: References: Message-ID: <1190370488.359297.86510@w3g2000hsg.googlegroups.com> On Sep 20, 3:26 pm, Hynek Hanke wrote: > Hello, > > please, is there something like 'attach' in pdb yet? My application uses > threads > and when it freezes (e.g. due to a deadlock situation), I'd like to get > the traceback > of all threads and inspect at which point did the application get into > problems. > Or could I send a signal to such a python process so that it would > output backtraces > from all threads before terminating? > > Because currently, if a thread runs into deadlock problems (or a thread > fails on > an exception and the other thread can't join it), I have no way of > determining > what went wrong. > > Such processes are not possible to terminate via CTRL-C in the > interpreter, so > I can't get the backtrace this way. Furthermore, I also need todebug > subprocesses, > so these are difficult to invoke interactively. > > I'm happy for any suggestions. > > Thank you, > Hynek Hanke Try to debug with winpdb: http://www.digitalpeers.com/pythondebugger/ Any feedback will be appreciated. From jgardner.jonathangardner.net at gmail.com Thu Sep 6 16:58:28 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Thu, 06 Sep 2007 20:58:28 -0000 Subject: initializing cooperative method In-Reply-To: <1189102680.957512.152950@k79g2000hse.googlegroups.com> References: <1189095131.853954.233660@r34g2000hsd.googlegroups.com> <13e0bgg5lo0p2ec@corp.supernews.com> <1189102680.957512.152950@k79g2000hse.googlegroups.com> Message-ID: <1189112308.681310.219730@y42g2000hsy.googlegroups.com> On Sep 6, 11:18 am, jelle wrote: > Ai, calling super(Abstract) is just getting object, sure... > > However, I'm still curious to know if there's a good idiom for > repeating the argument in __init__ for the super(Concrete, > self).__init__ ? > If you don't know what the arguments are, you can use *args and **kwargs. class Concrete(Abstract): def __init__(self, *args, **kwargs): super(Concrete, self).__init__(*args, **kwargs) From pavlovevidence at gmail.com Fri Sep 7 20:58:33 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 07 Sep 2007 17:58:33 -0700 Subject: Speed of Python In-Reply-To: References: Message-ID: <1189213113.384354.86980@50g2000hsm.googlegroups.com> On Sep 7, 12:42 pm, "wang frank" wrote: > Hi, > > While comparing the speed of octave and matlab, I decided to do a similar > test for python and matlab. The result shows that python is slower than > matlab by a factor of 5. It is not bad since octave is about 30 time slower > than matlab. > > Here is the result in matlab: > Elapsed time is 0.015389 seconds. > > and in Python:>>> t=timeit.Timer("bench1.bench1(10)","import bench1") > >>> t.repeat(1,1) > > [0.071012377266015392] > > Here is the bench1.py: > import math > def bench1(n): > for i in range(n): > for j in range(1000): > m=j+1 > z=math.log(m) > z1=math.log(m+1) > z2=math.log(m+2) > z3=math.log(m+3) > z4=math.log(m+4) > z5=math.log(m+5) > z6=math.log(m+6) > z7=math.log(m+7) > z8=math.log(m+8) > z9=math.log(m+9) > return z9 > > Is my conclusion correct that Python is slower than matlab? Whoa, there, chief, that's a pretty lofty conclusion to make based on one benchmark. A blanket speed comparison between Matlab and Python isn't productive: they each have their own strengths speedwise. (Conversely, a blanket comparison is productive programmingwise. Matlab has almost no strengths relative to Python in that department. But that's another question entirely. :) Roughly speaking, I'd say your average single-pass calculation script is going to be faster in Matlab than in Python. However, Python (with help from numpy) has more opportunities for optimization, especially if you're using large matrices. And if you need to take it up a notch, Python has very good ways to integrate numerical C and Fortran code. > Are there any > way to speed it up? It seems Python automatically created bench1.pyc. Does > Python automatically execute the bench1.pyc to speed it up? Yes, as others have explained. Carl Banks From robert.kern at gmail.com Thu Sep 6 17:12:33 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 06 Sep 2007 16:12:33 -0500 Subject: Python and CUDO In-Reply-To: <46E05DC0.7090102@glocalnet.net> References: <46E05DC0.7090102@glocalnet.net> Message-ID: Veronika Lindstrand Kant wrote: > Hi! > I just wonder if there are any plans for building any support using > NIVIDAS CUDO plattform into python? Not into Python itself, but we are working on interfacing with NVIDIA's CUDA, yes (presuming you actually meant "NVIDIA's CUDA" rather than "NIVIDAS CUDO"). http://code.google.com/p/pystream/ -- 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 DustanGroups at gmail.com Thu Sep 20 07:03:12 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 20 Sep 2007 11:03:12 -0000 Subject: Sets in Python In-Reply-To: <_cmIi.3452$ZA5.919@nlpi068.nbdc.sbc.com> References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <_cmIi.3452$ZA5.919@nlpi068.nbdc.sbc.com> Message-ID: <1190286192.103681.235270@w3g2000hsg.googlegroups.com> On Sep 19, 10:58 pm, Bryan Olson wrote: > Bad news: Python 3000 has no immutable type for byte-strings. > The new bytes type cannot serve for dict keys or set members. > Many things one would want to hash are unhashable -- for > example, the results of the hash functions in hashlib. Are you serious???? From joshua at eeinternet.com Mon Sep 17 18:13:32 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Mon, 17 Sep 2007 14:13:32 -0800 Subject: why does Configparser change names to lowercase ? References: <46EAED39.9080209@gmail.com> Message-ID: On Friday 14 September 2007 12:21, stef mientki wrote: > Why does Configparser change names to lowercase ? > > As Python is case sensitive (which btw I don't like at all ;-) > but now when really need the casesensitivity, > because it handles about names which should be recognized by human, > it changes everything to lowercase ???? > > thanks, > Stef Mientki According to the ConfigParser docs: "All option names used in interpolation will be passed through the optionxform() method just like any other option name reference. For example, using the default implementation of optionxform() (which converts option names to lower case), the values "foo %(bar)s" and "foo %(BAR)s" are equivalent." So, it seems it would be trivial so sublcass ConfigParser, and reimplement optionxform() Hope that helps. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From lasses_weil at klapptsowieso.net Fri Sep 7 05:46:38 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Fri, 07 Sep 2007 11:46:38 +0200 Subject: unexpected behavior: did i create a pointer? In-Reply-To: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> Message-ID: <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> gu wrote: > hi to all! > after two days debugging my code, i've come to the point that the > problem was caused by an unexpected behaviour of python. or by lack of > some information about the program, of course! i've stripped down the > code to reproduce the problem: > > [snip FAQ] Yes, basically you *created* a pointer. That's all that python has: pointers. When saying >>> a = AnyOldObject() >>> b = a then 'a' and 'b' are different /names/ for the /very same/ object (try "a is b", or "id(a)==id(b)"). This is really a FAQ (once a week or so?), but for the life of me I can't find the right words for a google query. TO THE TROOP: What keywords would you attach to that question? /W From paul at boddie.org.uk Thu Sep 6 06:56:26 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 06 Sep 2007 03:56:26 -0700 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? In-Reply-To: References: Message-ID: <1189076186.590996.190380@o80g2000hse.googlegroups.com> On 5 Sep, 21:02, Kenneth McDonald wrote: > The reading I've done so far on Python 3 (alpha announcement, meta-PEP, > some other PEPs) is generally encouraging, but there doesn't seem to be > much on cleaning up the syntax, which has become uglier over time as > features have been added on to an original syntax that wasn't designed > to support them. It seems to me (from what little I've read--I admit > that it's impossible to know for sure without experimenting quite a bit, > for which I don't currently have the time) that new features such as > multimethods might just make things more confusing (especially for > newbies) in a lot of ways, without appropriate syntactic support. I think there's been a widespread "kitchen sink" mentality around the Python language for some time, which is where the multimethods proposal, amongst others, fits in here. If we look at a selection of PEPs, this trend is quite evident even amongst those accepted for inclusion: PEP 3102 (Keyword-Only Arguments) - provides some benefits, but with an odd syntax and still more gymnastics for each function call. PEP 3104 (Access to Names in Outer Scopes) - syntactically a very large bikeshed indeed, but will keep the closure-happy people happy. PEP 3105 (Make print a function) - laudable, but leads to the not particularly flattering observation that someone made about Python 3.0 breaking "hello world". "Real men" don't use print, apparently, but a print function will presumably let them show their gentler side (or embrace the dark side). PEP 3107 (Function Annotations) - otherwise known as the freedom for developers to annotate the hell out of functions for the purpose of stating type information explicitly, although they're not really for that, apparently. Expect n lines of decorators plus n lines of function signature in shinier code bases. Eventually, we get to PEP 3113 (Removal of Tuple Parameter Unpacking) which is a clean-up. Meanwhile, PEP 3108 (Standard Library Reorganization) gets a mere wave of the hand with respect to core development priorities. Oh sure, we've got Python Eggs and can potentially unbundle everything these days - although I note that the CPython runtime itself doesn't get more modular and is seemingly resistant to attempts to make it easier to cross-compile - so perhaps one of Python's biggest selling points (the batteries included, now corroding in the battery compartment) isn't that important. I'll accept that the new I/O system (PEP 3116) could be beneficial, and I don't underestimate the effort put in by Martin von L?wis and others to tidy up and clarify certain awkward matters (PEPs 3120, 3121, 3131), but as people increasingly demand more innovation from the runtime, what we get is stuff like the renaming of various methods and PEP 3101 (Advanced String Formatting). > Currently the most obvious example of this is Python 2.5's way of > defining properties, which is ugly. leads often to writing of > unnecessary code, and certainly doesn't make property code clear to a > reader. Contrast this to the way properties (things that look like an > instance variable but are actually bound to methods) are handled in Ruby > and (IIRC, this also does a decent job) C#. Despite my own feeling that properties are overrated, possibly due to experience with languages and systems whose developers don't fear showing method invocations off, I guess this is just one area where some backward incompatibility breakage could have produced a "high value" syntax enhancement. > On the other hand, it does seem that some new syntactic support for > other features will be added, so perhaps I'm just missing whichever PEPs > talk about going back and adding cleaner syntax for existing features...? I've tried to track the things people previously complained about and any remedies for those things in Python 3000. See here for details: http://wiki.python.org/moin/PythonWarts > Finally, another thing I've perhaps missed, but I can't see anything in > what I've gone through, about correcting of of what I see to be one of > Python's most long-standing really serious flaws, which is the lack of > an official standard documentation markup syntax for writing > documentation in code. I'm not really a fan of docstring markup languages and tend to switch as much of that off as possible in tools like epydoc. This comes from having to work on code bases with documentation comments like the following: /** * TODO - What does this function do? * @param horse Horse The Horse * @param dereferencer SpecialDereferencer The SpecialDereferencer * @param options AnimalOptions AnimalOptions */ void Paddock::InitP97(Horse& horse, SpecialDereferencer* dereferencer, AnimalOptions options) I've not completely abandoned the hope that one day we'll get half decent type information in generated documentation without having to write it over and over again in docstrings, even for Python code. Paul From Scott.Daniels at Acm.Org Mon Sep 10 23:36:05 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 10 Sep 2007 20:36:05 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: References: Message-ID: <13ec37dri08s7a3@corp.supernews.com> Bryan Olson wrote: > Dotan Cohen wrote: ... >> Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or >> the other in error? > > Turbo C is correct here with respect to the C standard. Python > is correct with respect to the Python Reference Manual. > > They also disagree about integer division. C rounds toward zero; > Python rounds downward. > > In C: -111 / 10 evaluates to -11 > In Python: -111 / 10 evaluates to -12 C, which was designed as a "high level assembly language," does not tightly define the results of / and % for negative numbers. Instead it defines the result for positive over positive, and constrains the result for the others. The reason is simple: most CPUs available at the time provided a single operation that produced both the quotient and the remainder, but some produced -1 for -3 / 2, and others produced 1 for -3 / 2. Either result is justifiable, but the most common use of division and remainder is positive / positive, and it would be a shame to generate a test for every division and modulus just to cover the negative / positive case. You would be slowing down the majority of code to satisfy the (usually non-existant) corner case. -Scott David Daniels Scott.Daniels at Acm.Org From llasram at gmail.com Thu Sep 20 10:31:41 2007 From: llasram at gmail.com (Marshall T. Vandegrift) Date: Thu, 20 Sep 2007 10:31:41 -0400 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <876427zhzq.fsf@benfinney.id.au> <46f0fba0$0$29605$426a34cc@news.free.fr> <1190199134.791808.267110@22g2000hsm.googlegroups.com> <1190256493.827576.139470@r29g2000hsg.googlegroups.com> Message-ID: <87zlzhh0he.fsf@seneca.iss.local> Michele Simionato writes: > I am not against mixins (even if I am certainly very much against the > *abuse* of mixins, such as in Zope 2). What I would advocate (but I > realize that it will never happen in Python) is single inheritance + > mixins a la Ruby. Ruby might be a bad example here. Although the Ruby language syntax only supports single inheritance, mixins are implemented as multiple inheritance under the hood. That is, inheriting from a class and including a class as a mixin modifies the sub-/mixing class in exactly the same way. -Marshall From schlenk at uni-oldenburg.de Thu Sep 13 15:50:32 2007 From: schlenk at uni-oldenburg.de (Michael Schlenker) Date: Thu, 13 Sep 2007 21:50:32 +0200 Subject: automatic parallelization In-Reply-To: References: Message-ID: <46E99488.20909@uni-oldenburg.de> Mikhail Teterin schrieb: > While C/C++ and Fortran have OpenMP (http://www.OpenMP.org/), there is > nothing comparable in Tcl (nor, as far as I know, in the two other > scripting languages). > > Or is there? I'd like to, for example, have a version of foreach loop, that > would split the tasks between concurrently executing threads in order to > scale to the number of available CPUs: For CPython you don't get any benefit from extra CPUs even if you tried (unless the code inside your loop is specially written C code), due to the GIL. For Perl i don't know, their threading model was a bit heavy last time i looked, but i might be off with that, so maybe its doable in Perl. For Tcl you would at least get the benefit of multiple CPUs, but its more message passing based thread model is probably not the best for autoparallelization like OpenMP (but you could use the tsv:: api for shared vars if you want to). > > For example: > > pforeach image $images { > set exif($image) [extract_exif $image] > } > > The script would be the same on a single- and a multi-CPU computer, but > would automatically take advantage of multiple processors, when possible. Its doable in principle, but as with OpenMP you need extra annotations to make it workable. If you have an event style script in Tcl you might be easier able to use threads, as the thread::send -async api fits very well with the event based style. Michael From steve at holdenweb.com Sat Sep 1 03:08:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Sep 2007 03:08:31 -0400 Subject: list index() (OT) In-Reply-To: <007f01c7ec65$605e6700$03000080@hendrik> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com><46d674c2$0$417$426a34cc@news.free.fr><1188496588.750629.208100@g4g2000hsf.googlegroups.com><1188497498.3468.60.camel@dot.uniqsys.com><021801c7eba2$ad429640$03000080@hendrik> <1cnfd31du01el95u70o8mjn9cb5r5aluiu@4ax.com> <007f01c7ec65$605e6700$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Richie Hindle" wrote: > >> But - the word for someone who posts to the internet with the intention of >> stirring up trouble derives from the word for what fishermen do, not from >> the word for something that lives under a bridge. It derives from "trolling >> for suckers" or "trolling for newbies". > > So am I right in asserting that there is a difference in pronunciation > of the noun and the verb? > > He is a Troll - like the excellent frolic example > He likes to Troll - rhymes with roll? > I think you are seeking consistency where none exists. I don't believe anyone uses different pronunciations for the noun and the verb (which I guess will make those who *do* come out of the woodwork in double-quick time). Where's Godwin's Law when yo need it? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From fakeaddress at nowhere.org Sun Sep 9 21:06:59 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 10 Sep 2007 01:06:59 GMT Subject: Modul (%) in python not like in C? In-Reply-To: References: Message-ID: Dotan Cohen wrote: > FIrst of all, how is the % symbol (as in 70%6=4) called in English? The operator is usually called "mod". (The symbol is usually called "percent".) I reserve "modulo" for its usage in mathematics. 70 modulo 6 is an equivalence class containing infinitely many integers. In math talk, 4 is the least residue of 70 modulo 6. > Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or > the other in error? Turbo C is correct here with respect to the C standard. Python is correct with respect to the Python Reference Manual. They also disagree about integer division. C rounds toward zero; Python rounds downward. In C: -111 / 10 evaluates to -11 In Python: -111 / 10 evaluates to -12 > Is this a known gotcha? I tried to google the > subject however one cannot google the symbol %. I think it's a known gotcha. I cited the refs in another post. -- --Bryan From brusstoc at gmail.com Sat Sep 15 10:15:20 2007 From: brusstoc at gmail.com (brusstoc at gmail.com) Date: Sat, 15 Sep 2007 14:15:20 -0000 Subject: Can You Program? In-Reply-To: <1189679878.271415.88700@w3g2000hsg.googlegroups.com> References: <1189679878.271415.88700@w3g2000hsg.googlegroups.com> Message-ID: <1189865720.546424.155860@d55g2000hsg.googlegroups.com> On Sep 13, 3:37 am, hats... at gmail.com wrote: > We are offering $2000 USD for the best website developed withwww.hatspin.com > > Are you up to it?? Hey, thanks for spamming our group. Perhaps you should try again after you learn proper HTML coding. Results from http://validator.w3.org/ : Failed validation, 26 Errors Really, really doubt that you are doing anything but trying to gather e-mails. My 12 year old has made better sites. Oh, and does jobslide.com know that you are linking to images on their site? I'll be mentioning that to them, just so you know. Please, put down the keyboard and step away from the computer...... From bj_666 at gmx.net Sat Sep 22 17:24:39 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2007 21:24:39 GMT Subject: too many values with string.split References: Message-ID: <5llfgnF8gic1U10@mid.uni-berlin.de> On Sat, 22 Sep 2007 17:00:47 -0400, Shawn Minisall wrote: > I'm trying to unpack a list of 5 floats from a list read from a file and > python is telling me 5 variables are too many for the string.split > statement. Please post the *real* message which I suspect is something like 'too many values to unpack', which is the other way around. The 5 names are not enough to take all the items from the split. > #read in data line by line > for line in infile: > mylist = string.split(line) Functions in the `string` module that are also available as methods on strings are deprecated. > firstName[counter] = mylist[0] > lastName[counter] = mylist[1] > grades[counter] = float(mylist[2]) > print firstName[counter], > lastName[counter],":","\t\t",grades[counter] > #increment counter > counter = counter + 1 Do you really need the counter? Can't you just append the values to the lists? > #calculates and prints average score > grades = str(grades) > num1, num2, num3, num4, num5 = string.split(grades,",") > average = float(num1 + num2 + num3 + num4 + num5) / 5 This is very strange. You have a list of floats (I guess), convert that list to a string, split that string at commas, concatenate the *strings* between commas and then try to convert it to a `float`!? This is likely not what you want and should fail in most cases anyway. Ciao, Marc 'BlackJack' Rintsch From dnhkng at googlemail.com Sat Sep 8 11:59:41 2007 From: dnhkng at googlemail.com (Dr Mephesto) Date: Sat, 08 Sep 2007 15:59:41 -0000 Subject: creating really big lists In-Reply-To: References: <874pi92tr4.fsf@mulj.homelinux.net> <1189057626.943757.210420@d55g2000hsg.googlegroups.com> <1189063849.118900.327540@22g2000hsm.googlegroups.com> <1189192606.119578.100820@r34g2000hsd.googlegroups.com> Message-ID: <1189267181.964313.302520@g4g2000hsf.googlegroups.com> On Sep 8, 3:33 am, "Gabriel Genellina" wrote: > En Fri, 07 Sep 2007 16:16:46 -0300, Dr Mephesto > escribi?: > > > hey, that defaultdict thing looks pretty cool... > > > whats the overhead like for using a dictionary in python? > > Dictionaries are heavily optimized in Python. Access time is O(1), > adding/removing elements is amortized O(1) (that is, constant time unless > it has to grow/shrink some internal structures.) > > -- > Gabriel Genellina well, I want to (maybe) have a dictionary where the value is a list of 5 lists. And I want to add a LOT of data to these lists. 10?s of millions of pieces of data. Will this be a big problem? I can just try it out in practice on monday too :) thanks From aboudouvas at panafonet.gr Mon Sep 3 06:31:58 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 03 Sep 2007 03:31:58 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <87tzqc9jda.fsf@benfinney.id.au> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1188803759.498517.198900@g4g2000hsf.googlegroups.com> <87tzqc9jda.fsf@benfinney.id.au> Message-ID: <1188815518.958139.17390@w3g2000hsg.googlegroups.com> I was wondering (and maybe i still do) about this GIL "problem". I am relatively new to Python (less than a year) and when i started to think about it i said: "Oh, this IS a problem". But when i dig a little more, i found that "Ah, maybe it isn't". I strongly believe that the best usage of multiple cores processor will be achieved if programming languages are modified to support this on their "hearts". Code blocks that would be identified by the compiler and run in parallel and such things. Laboratories are working on these stuff but i do not expect something in the very-near future. So, as i mentioned above, there are solutions for that right now ("parallel python" and others) that enabled us with little effort to spawn a new python interpreter, thus allowing the OS to schedule it on a different core and do the job this way relatively cheap. I wouldn't recommend going to IronPython despite the fact that the CLR better utilize MP. The reason for this is that i would NEVER give up the freedom that CPython gives me by exchange "better" usage of the MP and platform lock-in. From paul.hankin at gmail.com Wed Sep 26 07:23:39 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 26 Sep 2007 11:23:39 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <87sl51lshd.fsf@mulj.homelinux.net> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> Message-ID: <1190805819.406334.24730@k79g2000hse.googlegroups.com> On Sep 26, 9:51 am, Hrvoje Niksic wrote: > Duncan Booth writes: > > I that's the point though: you can't write one implementation that has good > > performance for all patterns of use > > An implementation of sorted dict using a balanced tree as the > underlying data structure would give decent performance in all the > mentioned use cases. For example, red-black trees search, insert, and > delete in O(log n) time. But dicts do search, insert and delete in O(1) time, so using some variety of balanced tree will give you much worse performance when you're doing regular dict operations. -- Paul Hankin From db3l.net at gmail.com Sat Sep 1 01:59:43 2007 From: db3l.net at gmail.com (David Bolen) Date: Sat, 01 Sep 2007 01:59:43 -0400 Subject: HowTo Use Cython on a Windows XP Box? References: <1188618022.208258.15620@22g2000hsm.googlegroups.com> <1188623610.532790.114000@o80g2000hse.googlegroups.com> Message-ID: David Lees writes: > Yes, you are correct in understanding my question. I thought my post > was clear, but I guess not. I will go try the pyrex list. You might also try looking for references to distutils support for non-MS compilers, since Pyrex (and presumably Cython) uses distutils under the covers to build the final extension. I'm pretty sure there is support in recent Python releases for using mingw rather than MSVC for most extensions (there may be problems with using certain Python APIs that depending on specific C RTL structures like files). As to using VC, yes, it does have to be VC 7.1, e.g,. Visual Studio 2003. You can't use 2005, as MS didn't maintain runtime compatibility. I'm sure there are a number of threads about that also available. If I recall correctly, VC 7.1 began to be used in the 2.4 timeframe - although it was getting discussed back when 2.3 was getting released, based on an offer Microsoft had made to provide copies to core developers. The discussions are archived, but VC 6 was definitely long in the tooth at that point. As the development tools aren't free, they haven't been upgraded past that point to date. It's unfortunate that when MS changed the main runtime DLL with VC 7 (for the first time in a pretty long time), that they then did so immediately again (and incompatibly) with VC 8. At the time, there were also efforts with some success to use the free toolkit MS made available (although I think it was sans optimizer), but then I think that got pulled and/or it became more difficult to find/use, but my memory is fuzzy. You mention having VS 2005 - if so, do you also have an MSDN subscription? I believe you should still be able to get VS 2003 via that route if you first started with 2005 and thus never had 2003. If not, the mingw approach may be your best bet. -- David From cjw at sympatico.ca Mon Sep 17 20:57:20 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 17 Sep 2007 20:57:20 -0400 Subject: Why 'class spam(object)' instead of class spam(Object)' ? In-Reply-To: References: <46e10916$0$16518$4c368faf@roadrunner.com> Message-ID: <46EF2270.6080000@sympatico.ca> Steve Holden wrote: > Carl Banks wrote: >> On Fri, 07 Sep 2007 01:30:00 -0500, Sergio Correia wrote: >>> Hi, I'm kinda new to Python (that means, I'm a total noob here), but >>> have one doubt which is more about consistency that anything else. >>> >>> Why if PEP 8 says that "Almost without exception, class names use the >>> CapWords convention", does the most basic class, object, is lowercase? >> It said "almost". :) >> > Indeed it did, and never forget that most of PEP 8 was derived from an > essay by Guido whose original title was "A Foolish Consistency is the > Hobgoblin of Little Minds" ... >>> I found a thread about this: >>> http://mail.python.org/pipermail/python-list/2007-April/437365.html >>> where its stated that -object- is actually a type, not a class; but the >>> idea still doesn't convince me. > You don't have to be convinced. You just have to do what the PEP says > yourself and ignore the people who *haven't* done what it says > (particularly if they are core Python developers). > >> There's a false dichotomy there: it's not an either-or situation. Almost >> everyone would agree that new-style classes, defined by the Python class >> statement, are both classes and types. Some might squabble over whether >> object is class, but it has nothing to do with why object is spelled in >> lower-case. >> >> The reason why "object" is lower case is because built-in types are >> spelled in lower-case. Why are built-in types lower case? Because many >> built-in types were originially functions. For example, "int" and "str" >> were once functions. When these symbols became the names of their >> respective types, they kept the lower-case spelling, and it became >> convention for built-in types to be spelled lower-case. >> > In other words: "Get over it" ;-) > > regards > Steve Surely Python 3000 gives the opportunity to introduce some consistency. Does the user care whether an object is implemented in C? Colin W. From koutoo at hotmail.com Tue Sep 18 14:58:16 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Tue, 18 Sep 2007 11:58:16 -0700 Subject: Newbie question In-Reply-To: References: <1190139661.046103.45440@19g2000hsx.googlegroups.com> <1190140395.567419.16280@k79g2000hse.googlegroups.com> Message-ID: <1190141896.085799.295110@57g2000hsv.googlegroups.com> On Sep 18, 1:42 pm, "Shawn Milochik" wrote: > On 9/18/07, kou... at hotmail.com wrote: > > > > > > > On Sep 18, 1:31 pm, "Shawn Milochik" wrote: > > > On 9/18/07, kou... at hotmail.com wrote: > > > > > If I have a file name: AVC1030708.14. How do I strip out certain > > > > characters from the file name? I am so used to using MID, LEFT, and > > > > RIGHT functions, that I have no idea how to do this in python? I have > > > > had trouble as well with most newbies on finding the help. But I have > > > > used the command line built in help, but with no luck. Thanks. > > > > > Kou > > > > Do you want to strip out specific characters, characters in specific > > > positions, or characters matching certain patterns? > > > Yes, I want specific characters in specific positions. > > Try this: > > newString = oldString[0:3] + oldString[5:10] > > Some other quick examples: > > >>> test = "this is a test" > >>> test > 'this is a test' > >>> fred = test[:3] + test[9:] > >>> fred > 'thi test' > >>> test[0:5] > 'this ' > >>> test[:5] > 'this ' > >>> test[4:] > > ' is a test'- Hide quoted text - > > - Show quoted text - I see. It's so hard to imagine the world of python than from VB. It's like looking at VB is in 2 dimensions, where with Python, it's more 3D. The code is so simple, yet it's hard for me to envision how to do something so simple. I guess it's because the rules or the way of looking at things in Python, things can be stripped down to the bare bones and in so many ways. Thanks. Kou From carsten at uniqsys.com Fri Sep 7 09:11:30 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 07 Sep 2007 09:11:30 -0400 Subject: MySQLdb: ValueError Something Stupid In-Reply-To: <1189169527.020589.185120@w3g2000hsg.googlegroups.com> References: <1189163332.990248.134080@d55g2000hsg.googlegroups.com> <1189169527.020589.185120@w3g2000hsg.googlegroups.com> Message-ID: <1189170690.3367.30.camel@dot.uniqsys.com> On Fri, 2007-09-07 at 05:52 -0700, mcl wrote: > > ValueError: invalid literal for int(): 0- > > args = ('invalid literal for int(): 0-',) > > > > ========================================= > > Thanks Richard > > Sort of solved it. > > On that particular table it did not like * for all fields. > > Any reason why that would be the case ? None that we can divine without more information. What's the schema for the table in question, which column(s) are you excluding to make the query work, and what kind of data is in the column(s) you're excluding? -- Carsten Haese http://informixdb.sourceforge.net From yosuke at ccwf.cc.utexas.edu Mon Sep 3 22:51:10 2007 From: yosuke at ccwf.cc.utexas.edu (yosuke at ccwf.cc.utexas.edu) Date: Tue, 4 Sep 2007 02:51:10 +0000 (UTC) Subject: trap setting attribute when the attribute is dict References: <1188845236.417709.307160@50g2000hsm.googlegroups.com> <1188864653.854065.80100@g4g2000hsf.googlegroups.com> Message-ID: John Machin wrote: > On Sep 4, 5:47 am, wrote: >> Arnaud Delobelle wrote: >> > On Sep 3, 7:00 pm, wrote: >> >> >> I want to do something like this. My class/instance has a dict as a >> >> property. I want the instance to catch the change in the dict (change >> >> in some values, addition/deletion of key/value etc) to be recognized by >> >> the class instance. >> >> >> How can I do this? Any suggestions are very well appreciated. >> [snip] >> >> Thank you for suggestion, Arnaud. >> >> Since you are discouraging this idea of trigger, may I ask an advice of >> if my intention was legitimate one or not? >> >> My intention was to have a propery 'sum' in my object, and which has sum >> of all the values() of the dict (i have code to make sure that the value >> of dict are all numeric). I could just the propery being calculated >> everytime the property got __getattr__. But I thought that it was >> inefficient to calculate the same number over and over when the value is >> already known. So I was thiking of calculating the number only when the >> dict got modified. >> >> I also experimented with the idea of subclassing dict itself to >> calculate the sum. Is this what would be better solution? >> > And what's wrong with calculating the value when you need it ... > def thedictsum(self): > return sum(self.thedict.itervalues()) > How big will the dict be, how often will it be updated, how often will > the sum be required? > Have you done timings of any of the options? Thank you for the post. I want the code to have fewer lines of code. That was my biggest motivation for this. I have many of this dict with sum, each have <1000 elements. all of them share the same keys. I do many addition/subtraction/divisions by each elements (yes, division makes the elements not being able to summed). so in my code i have repeated lines that works on each elements and then on the sum. i made a dict to take care of adding elements by elements. but i still had two lines of code, one for dict elements, and one for the sum. my code was originally in fortran and it has like thousands of lines, obscuring the mathematics that i want to do. i need to modify math often while i use the code (i dont know exactly what math i will need at this point), so i want to the code to be able to show the math clearly. ideally i want to this to be somthing like c = a + b d = 1 / c and each of a, b, c, d knows how to operates on each elements, and also keep track of the sum. I think i will settle for extending dict to have sum property and keep track of it . > You say you have code to check that the values are numeric; why not > put this together with maintenance of the sum into a method which > clients must use to update the dict? > BTW, my motto: > "__" == "Danger, Will Robinson!" == "Wrong way, go back" :-) not quite getting this.... :( > HTH, > John -- yosuke kimura Center for Energy and Environmental Resources The Univ. of Texas at Austin, USA From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 21 05:04:07 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 21 Sep 2007 11:04:07 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1190013827.107324.111820@w3g2000hsg.googlegroups.com> <1190053757.091035.221570@22g2000hsm.googlegroups.com> Message-ID: <46f38907$0$27686$426a74cc@news.free.fr> Ron Adam a ?crit : > > > TheFlyingDutchman wrote: > >> I am not talking about the way it does it, but rather, the way it >> could do it or... could have done it. That requires no knowledge of >> how the interpreter currently does it unless I am proposing something >> that no interpreter in the world could ever do. > (snip) > So if you can find a way to do things like removing self in python in > such a way that it doesn't require adding more to the Core interpreter, > then it might be considered. By who ? As far as I'm concerned, I don't want 'self' to be removed, and I'm probably not the only one here. > > What I've found is as my skills improve, I take more advantage of being > able to modify and/or introspect how things work. This allows more > choices on how I might solve a particular problem. The changes required by removing self would make most of this either painfull or near impossible AFAICT. > I also think there a lots of improvements that could be made to other > parts of python such as the libraries that would be of much more > practical benefit. indeed. From fredrik at pythonware.com Thu Sep 27 11:44:53 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Sep 2007 17:44:53 +0200 Subject: setuptools without unexpected downloads In-Reply-To: <1190840682.716950.131830@r29g2000hsg.googlegroups.com> References: <87ejgmklep.fsf@benfinney.id.au><5lumarFae888U1@mid.uni-berlin.de> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> <1190805012.275901.227570@57g2000hsv.googlegroups.com> <5luv0iFaai82U1@mid.uni-berlin.de> <1190808836.056298.232640@57g2000hsv.googlegroups.com> <1190840682.716950.131830@r29g2000hsg.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > What would it entail to do this? Using py2exe + some installer (like > Inno Setup) to create an installer that basically copies/installs the > files into the site-packages folder or wherever the user chooses? if the setup.py file is properly built, "python setup.py bdist_wininst" builds an installer that does exactly that. ideally, someone doing this would: 1) build EXE installers and EGG:s for a reasonable number of Python versions (e.g. 2.3 and newer) for selected releases. if possible, using the same compilers as used for the python.org core distribution. 2) test the installers in some way (at least some kind of "sanity checking" is necessary; i.e. installing the kit and checking that the core modules can at least be imported). 3) if necessary, work with upstream providers to fix/improve setup.py and test code. From sbassi at clubdelarazon.org Wed Sep 12 00:33:18 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Wed, 12 Sep 2007 01:33:18 -0300 Subject: Generating HTML Message-ID: <9e2f512b0709112133l41ce5ef1g815962a81becf6b9@mail.gmail.com> Hello, What are people using these days to generate HTML? I still use HTMLgen, but I want to know if there are new options. I don't want/need a web-framework a la Zope, just want to produce valid HTML from Python. Best, SB. -- Sebasti?n Bassi (???????). Diplomado en Ciencia y Tecnolog?a. Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From pavlovevidence at gmail.com Sat Sep 15 00:58:26 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Sep 2007 00:58:26 -0400 Subject: An ordered dictionary for the Python library? References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <1189733785.813953.77370@k79g2000hse.googlegroups.com> Message-ID: <46eb6ad1$1$7493$4c368faf@roadrunner.com> On Thu, 13 Sep 2007 19:21:08 -0700, James Stroud wrote: > Carl Banks wrote: >> On Sep 13, 4:20 pm, James Stroud wrote: >>> Mark Summerfield wrote: >>>> - If an item is inserted it is put in the right place (because the >>>> underlying data structure, b*tree, skiplist or whatever is >>>> intrinsically ordered by < on the key) >>> +1 for all your suggestions below, but -1 for the above. You suggest >>> that >>> >>> myOrderedDict['key'] = value >>> >>> would place it in the dictionary in sorted order depending on 'key'. >>> More natural to some of us (or maybe its just me) would be to append >>> the key/value pair to the end of items. >> >> Or, maybe, like, you know, you could have two different types that >> maintain two different orders? >> >> > Do you mean, like, a SortedDict and an OrderedDict like I mentioned in > the post you are replying to? Like, you know, maybe I should read the whole article I reply to. *sigh* Carl Banks From fakeaddress at nowhere.org Sun Sep 9 02:42:27 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 08 Sep 2007 23:42:27 -0700 Subject: Does shuffle() produce uniform result ? In-Reply-To: <7xhcm4pl5m.fsf@ruckus.brouhaha.com> References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> <7xhcm4pl5m.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Lawrence D'Oliveiro writes: >> Except that the NSA's reputation has taken a dent since they failed to >> anticipate the attacks on MD5 and SHA-1. > > NSA had nothing to do with MD5, and it's to NSA's credit that SHA-1 > held up for as long as it did. I haven't kept up. Has anyone exhibited a SHA-1 collision? -- --Bryan From bignose+hates-spam at benfinney.id.au Tue Sep 25 20:16:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 26 Sep 2007 10:16:13 +1000 Subject: Test-driven development and code size (was: What is a good way of having several versions of a python module installed in parallell?) References: <5ls95aF9pq3gU1@mid.uni-berlin.de> Message-ID: <87ejgmmgc2.fsf_-_@benfinney.id.au> Joel Hedlund writes: > Do you also do [test-driven development] for all the little stuff, > the small hacks you just whip together to get a particular task > done? My impression is that doing proper unittests adds a lot of > time to development, and I'm thinking that this may be a low return > investment for the small programs. My impression is that failing to have reliable code adds a lot of time to debugging and maintenance, and it is far cheaper to have tested and flushed out the obvious bugs early in the development process. > I try to aim for reusability and generalizability also in my smaller > hacks mainly as a safeguard. In which case, you will be maintaining that code beyond the initial use for which you thought it up. Maintaining code without unit tests is far more costly than maintaining code with tests, because you have no regression test suite: you are prone to chasing down bugs that you though you'd fixed in an earlier version of the code, but can't figure out when you broke it again. This time is entirely wasted. Instead, in code that has unit tests, a bug found means another unit test to be added (to find and demonstrate that bug). This is work you must do anyway, to be sure that you can actually reproduce the bug; test-driven development merely means that you take that test case and *keep it* in your unit test. Then, once you're assured that you will find the bug again any time it reappears, go ahead and fix it. > My reasoning here is that if I mess up somehow, sooner or later I'll > notice With test-driven development I get much closer to the "sooner" end of that, and much more reliably. > Maybe I should be rethinking this? That's my opinion, yes. -- \ "My mother was like a sister to me, only we didn't have sex | `\ quite so often." -- Emo Philips | _o__) | Ben Finney From paul at boddie.org.uk Wed Sep 26 07:10:12 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 26 Sep 2007 04:10:12 -0700 Subject: setuptools without unexpected downloads In-Reply-To: <5lurorFa92euU1@mid.uni-berlin.de> References: <87ejgmklep.fsf@benfinney.id.au><5luhb0Faal8aU1@mid.uni-berlin.de> <874phhlupi.fsf@benfinney.id.au> <5lumarFae888U1@mid.uni-berlin.de> <1190802526.695391.326220@n39g2000hsh.googlegroups.com> <5lurorFa92euU1@mid.uni-berlin.de> Message-ID: <1190805012.275901.227570@57g2000hsv.googlegroups.com> On 26 Sep, 12:48, "Diez B. Roggisch" wrote: > [Quoting me...] > > However, the argument that a dependency manager cannot deal with > > different system packages is a weak one: apt and Smart have shown that > > dependency management can be decoupled from package management. > > Do you care to elaborate on how apt has shown that? I use it every day (or > at least often), but I have to admit I never delved to deeply into them - > to me it appears that apt is a retrieval-solution, not so much a dependency > management system. The dependencies are declared in the debs themselves, > used by dpkg-* - aren't they? Sure, apt does solve them, but how so > decoupled from the underlying .deps? Perhaps I was thinking more about the whole apt vs. apt-rpm situation, since apt-rpm supposedly works with RPMs, albeit in a different distribution of the software. > Regarding smart: what I read here > > """ > Smart is not meant as an universal wrapper around different package formats. > It does support RPM, DEB and Slackware packages on a single system, but > won't permit relationships among different package managers. While > cross-packaging system dependencies could be enabled easily, the packaging > policies simply do not exist today. > This is not at all different from what you can already do. In fact, Debian > has been shipping the RPM package manager for a few years now. "Possible" > does not equal "good idea", and everybody should stick to their native > package format. > """ > > in the FAQ doesn't make me think that it's just a matter of unwillingness > from the setuptools-people but instead an intrinsic property of > dependency-handling that makes cross-package-management-management (or > meta-management) hard. I think the argument is that you use your own system's package format, but smart is supposed to resolve the dependencies expressed in the packages itself. There are also universal package formats, but I think these usually leave some people disappointed, partly because you then have to consider all the different dependency representations and the inevitable integration with genuine system packages. I guess this is why dependency issues were left underspecified in the PEP. > Apart from the technical intricacies of .deb/.rpm and their respective > tools, on thing sure makes this an argument: THEY evolve as they like, and > it sure puts a lot of additional burden to the setuptools-guys to keep > track with that. I think most of the evolution has been in the surrounding tools, although stuff like the new Debian Python policy could be complicating factors. But I don't think the dependency stuff has changed that much over the years. [...] > >> For example - what if there is no debian package that provides module XY > >> in the required version? Do you rather install it into the global > >> site-packages, or do you rather keep it private to the program requiring > >> it? I'd say the latter is better in mostly all circumstances, as it will > >> not disrupt the workings of other programs/modules. [http://www.boddie.org.uk/paul/userinstall.html] > Certainly a nice solution to a real problem that might be handy for me at > some time. Yet I fail to see how that relates to the above question: if the > OS package repository fails to meet a certain version requirement, how do > you deal with that - installation local to the product you're actually > interested in installing, or in a more public way that possibly interferes > with other software? My response here was mostly addressing the "global site-packages" issue since that's usually a big reason for people abandoning the system package/dependency management. If you can't find a new-enough system package, you have to either choose a local "from source" installation (which I would regard as a temporary measure for reasons given elsewhere with respect to maintenance), or to choose to repackage the upstream code and then install it through the system package manager, which I claim can be achieved in a non-global fashion. Paul From martin at v.loewis.de Sat Sep 1 11:41:20 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 Sep 2007 17:41:20 +0200 Subject: How to find out if the interpreter is a debug build? In-Reply-To: <1188654173.615402.190960@19g2000hsx.googlegroups.com> References: <1188609417.273513.74450@i13g2000prf.googlegroups.com> <46d905d5$0$26151$9b622d9e@news.freenet.de> <1188643450.431001.219220@o80g2000hse.googlegroups.com> <46d95d5a$0$9015$9b622d9e@news.freenet.de> <1188654173.615402.190960@19g2000hsx.googlegroups.com> Message-ID: <46d98820$0$23700$9b622d9e@news.freenet.de> > Would such a patch require a full blown PEP? No. > If i have to write a PEP i can better add it to the documentation of > my application and be sure that the problem is solved. I don't understand. Are you saying you would rather not write a PEP, and add something to the documentation of your application instead? If that solves your problem, go for it! > A patch might > be rejected by anybody in a bad mood or who don't understand why it is > usefull. That's true. Martin From joshua at eeinternet.com Thu Sep 20 15:45:13 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 20 Sep 2007 11:45:13 -0800 Subject: A struct for 2.4 that supports float's inf and nan? References: <1190315989.268629.37520@22g2000hsm.googlegroups.com> Message-ID: On Thursday 20 September 2007 11:19, Paul Hankin wrote: >> I suppose I could get the relevant source from the 2.5 source and compile >> it as a custom package, but that wouldn't be very transparent for my >> users, and would probably be getting in way over my head. :) >> >> Ideas? Suggestions? > > Here's a wrapped pack: > > import struct > > pack_double_workaround = { > 'inf': struct.pack('Q', 0x7ff0000000000000L), > '-inf': struct.pack('Q', 0xfff0000000000000L), > 'nan': struct.pack('Q', 0x7ff8000000000000L) > } > > def pack_one_safe(f, a): > if f == 'd' and str(f) in pack_double_workaround: > return pack_double_workaround[str(f)] > return struct.pack(f, a) > > def pack(fmt, *args): > return ''.join(pack_one_safe(f, a) for f, a in zip(fmt, args)) > > Unpacking is similar: unpack doubles with 'Q' and test the > long for equality with +-inf, and find nan's by checking bits > 52 to 62. If the number's ok, unpack again using 'd'. > > You can get python values for nan, -inf and inf by using > float('nan'), float('-inf'), float('inf'). > > I've not been able to properly test this, as struct seems > to work fine in Python 2.3 and 2.4 on MacOS X. Thanks for the ideas, Paul! I came up with something that works for me, but this has a few ideas that I'm going to implement in my wrapper to make for cleaner code. As to testing it on MacOS X: yeah, it can be a somewhat system-dependent problem, so may not show up on all architectures. Thanks for the tips! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From tjreedy at udel.edu Fri Sep 7 20:45:15 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 7 Sep 2007 20:45:15 -0400 Subject: Speed of Python References: <1189185542.798286.168880@50g2000hsm.googlegroups.com> Message-ID: "wang frank" wrote in message news:BAY122-F37CD62BB3682998CD2C45AB4C50 at phx.gbl... | z=log(j); This matlab code is faster in part than your Python equivalent: | > > z=math.log(m) because of the repeated lookup of log in the math module. So, replace | > > import math with from math import log Also make that the top line of the function so 'log' is a local variable. Then delete 'math.' everywhere. That said, such artificial benchmarks do not strike me as terribly useful. More useful, for instance, for appropriate applications, might be doing a fourier transform on a 2**20 length vector with both matlab and numpy/scipy tjr From bignose+hates-spam at benfinney.id.au Tue Sep 18 19:15:47 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Sep 2007 09:15:47 +1000 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <740c3aec0709130730k2226e9abmbf5defb579b77660@mail.gmail.com> Message-ID: <87wsuny38c.fsf@benfinney.id.au> "Colin J. Williams" writes: > .rect.width = .foo(.rect.x + .rect.y) * .boo() > > Does this preceding "." create parsing problems? Perhaps not for the computer, but certainly for the human. A leading "." is far too easy to miss when visually scanning the code, and fails the "explicit" principle. -- \ "I have the simplest tastes. I am always satisfied with the | `\ best." -- Oscar Wilde | _o__) | Ben Finney From tim.couper at scivisum.co.uk Tue Sep 4 08:36:05 2007 From: tim.couper at scivisum.co.uk (Tim Couper) Date: Tue, 04 Sep 2007 13:36:05 +0100 Subject: Setting Current Dir in Python In-Reply-To: <000001c7eeec$d9341470$8b9c3d50$@net> References: <000001c7eeec$d9341470$8b9c3d50$@net> Message-ID: <46DD5135.7060501@scivisum.co.uk> "Non-ASCII character '\xef' in file" SandhirFileMonitor.py on line 356, This is reason for the failure .. you have a (probably accidentally placed) non-ascii (ie whose value is > 128) character on line 356, whose hex value is ef (decimal 259) . Solution: find that line and remove the character - or line. Tim Dr Tim Couper CTO, SciVisum Ltd www.scivisum.com Sandipan Gangopadhyay wrote: > Hi all! > > I have utility programs in Python that do clean up, image processing tasks > on files in a folder. I just drop the program into the folder and run it. > > I have been double clicking on a Python program in my Windows XP Home to > make it run . it sets the program's directory as the current directory when > it runs. > > I have recently installed Python 2.5.1 and Pythonwin (without any errors) on > Windows Vista Ultimate. > > Now, the programs run fine within Pythonwin IDE when current directory is > set to the program's directory. > > But, when I double click them from Windows Explorer, the program is not run. > > If I run the following program: > > ============================================================================ > =============== > # MODULE IMPORT > try: > import time, os, Image, urllib, string, math, os.path, filecmp, shutil, > sys > except: > strInput = raw_input("Failed import. Hit enter key to continue.") > pass > > # FIGURE OUT CURR DIR > try: > print "CURENT = %s" % os.listdir(".") > print "PARENT = %s" % os.listdir("..") > print "ABS PATH = %s" % os.path.abspath(".") > print "CURENT = %s" % os.listdir(os.curdir) > print "PARENT = %s" % os.listdir(os.pardir) > except: > strInput = raw_input("Failed os module calls. Hit enter key to end.") > pass > > print > strInput = raw_input("Hit enter key to end program") > > Through Pythonwin IDE without setting the directory (using Open, or Save > As), I get: > > ============================================================================ > =============== > CURENT = ['addins', 'AppPatch', 'assembly', 'atl80.dll', . - snip - . , > 'winsxs', 'WMSysPr9.prx', 'xpsp1hfm.log', '_default.pif'] > PARENT = ['$Recycle.Bin', 'autoexec.bat', 'Boot', 'bootmgr', 'BOOTSECT.BAK', > 'config.sys', 'Documents and Settings', . - snip - . , 'Program Files', > 'ProgramData', 'Python25', . - snip - . , 'System Volume Information', > 'temp', 'Users', 'Windows'] > ABS PATH = C:\Windows > CURENT = ['addins', 'AppPatch', 'assembly', 'atl80.dll', . - snip - ., , > 'winsxs', 'WMSysPr9.prx', 'xpsp1hfm.log', '_default.pif'] > PARENT = ['$Recycle.Bin', 'autoexec.bat', 'Boot', 'bootmgr', 'BOOTSECT.BAK', > 'config.sys', 'Documents and Settings', . - snip - . , 'Program Files', > 'ProgramData', 'Python25', . - snip - . , 'System Volume Information', > 'temp', 'Users', 'Windows'] > > If I run it using double click on the program through Windows Explorer, I > get: > > ============================================================================ > =============== > Nothing . the window closes immediately. Despite the except catches. > > If I run it from a Command Prompt, by first navigating to the program's > directory and then specifying [ python.exe SandhirFileMonitor.py ], I get: > > ============================================================================ > =============== > sys:1: DeprecationWarning: Non-ASCII character '\xef' in file > SandhirFileMonitor.py on line 356, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details > Failed import. Hit enter key to continue. > CURENT = ['Diff.txt', 'Folder2', 'report-templates', 'reports - Copy > (2).html','reports - Copy (3).html', 'reports - Copy (4).html', 'reports - > Copy (5).html', 'reports - Copy.html', 'reports.html', > 'SandhirFileBackupUtility - Copy.py', 'SandhirFileBackupUtility.py', > SandhirFileBackupUtility.py - Shortcut.lnk', 'SandhirFileMonitor.py'] > PARENT = ['BackupV10', 'BackupV11', 'DayReadiness', 'reporterV70'] > ABS PATH = > E:\Data\ActiveData\SandipanPersonalData\FromNODE06\SoftwareBackups\BackupV11 > CURENT = ['Diff.txt', 'Folder2', 'report-templates', 'reports - Copy > (2).html', 'reports - Copy (3).html', 'reports - Copy (4).html', 'reports - > Copy (5).html', 'reports - Copy.html', 'reports.html', > 'SandhirFileBackupUtility - Copy.py', 'SandhirFileBackupUtility.py', > 'SandhirFileBackupUtility.py - Shortcut.lnk', 'SandhirFileMonitor.py'] > PARENT = ['BackupV10', 'BackupV11', 'DayReadiness', 'reporterV70'] > > I am obviously missing something very simple, but I can't figure this out . > it's been a few days now. > > Can someone help? Thanks. > > Sandipan > > > From andre.roberge at gmail.com Fri Sep 7 15:13:41 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Fri, 07 Sep 2007 19:13:41 -0000 Subject: Is a Borg rebellion possible? (a metaclass question) In-Reply-To: References: <1189168282.665210.260840@19g2000hsx.googlegroups.com> <1189180478.257790.60160@g4g2000hsf.googlegroups.com> Message-ID: <1189192421.638450.266050@22g2000hsm.googlegroups.com> On Sep 7, 3:53 pm, Steve Holden wrote: > Andr? wrote: > > On Sep 7, 10:27 am, Carsten Haese wrote: > >> On Fri, 2007-09-07 at 12:31 +0000, Andr? wrote: > >>> In my application, I make use of the Borg idiom, invented by Alex > >>> Martelli. > >>> class Borg(object): > >>> '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273 > >>> Derive a class form this; all instances of that class will share > >>> the > >>> same state, provided that they don't override __new__; otherwise, > >>> remember to use Borg.__new__ within the overriden class. > >>> ''' > >>> _shared_state = {} > >>> def __new__(cls, *a, **k): > >>> obj = object.__new__(cls, *a, **k) > >>> obj.__dict__ = cls._shared_state > >>> return obj > >>> ---- > >>> This has worked very well so far, but is starting to impose some > >>> unwanted constraints on my program design. > >>> What I would like to do is, to put it figuratively, create a Borg > >>> rebellion with various splinter groups. In concrete Python terms, I > >>> would like to have > >>> class MyClass(Borg, ...): > >>> ... > >>> seven_of_nine = MyClass(...) # part of group "BORG" > >>> two_of_nine = MyClass(...) > >>> splinter1 = MyClass(..., group='splinter') > >>> splinter2 = MyClass(..., group='splinter') > >>> and have splinter 1 and splinter2 share the same state, but a > >>> different state than the one shared by members of the BORG collective. > >>> Any suggestions from the metaclass experts? > >> You don't need a metaclass. Just turn _shared_state into a dictionary of > >> shared states, keyed by the group name: > > >> class SplinterBorg(object): > >> _shared_states = {} > >> def __new__(cls, *a, **k): > >> group = k.pop("group","BORG") > >> obj = object.__new__(cls, *a, **k) > >> obj.__dict__ = cls._shared_states.setdefault(group,{}) > >> return obj > > >> HTH, > > >> -- > >> Carsten Haesehttp://informixdb.sourceforge.net > > > Unfortunately, it fails. Here's what I tried, followed by the > > traceback > > class SplinterBorg(object): > > _shared_states = {} > > def __new__(cls, *a, **k): > > group = k.pop("group","BORG") > > obj = object.__new__(cls, *a, **k) > > obj.__dict__ = cls._shared_states.setdefault(group,{}) > > return obj > > > class MyClass(SplinterBorg): > > def __init__(self, name): > > self.name = name > > > a1 = MyClass('a') > > a2 = MyClass('aa') > > b1 = MyClass('b', group="B") > > > Traceback (most recent call last): > > File "test.py", line 15, in > > b1 = MyClass('b', group="B") > > TypeError: __init__() got an unexpected keyword argument 'group' > > Because your subclass signature is completely wrong. Why did you feel > you had to add an __init__() method to your subclass? This has two bvad > effects: Because this is what I need to do currently with using the standard Borg class, and is something I would like to be able to do. Here's a simplified version of the current usage I have ===== class Borg(object): _shared_state = {} def __new__(cls, *a, **k): obj = object.__new__(cls, *a, **k) obj.__dict__ = cls._shared_state return obj class BorgConsole(Borg, SingleConsole): '''Every BorgConsole share a common state''' def __init__(self, locals={}, filename="Crunchy console"): SingleConsole.__init__(self, locals, filename=filename) ===== and it is called via something like a_console = BorgConsole(locals) where locals is a previously defined dict. Note that a number of such instances are created dynamically as the program is used. What I would like to do is to be able to add a "page_id" (the Borg group referred to my previous message), so that I could call a_console = BorgConsole(locals, page_id) where page_id would be an optional argument, defaulting to the BORG group, as mentioned in my original post. I must admit I did not try with keywords arguments ... and will not be for a couple of hours while I am at work. > > 1. It stops the super-class's __init__() method from being called, and > I don't understand why this is so here, and not with the usual Borg case as I used it... > 2. It breaks the calling syntax specified in the superclass. > > All you really need is to create your SplinterBorgs with appropriate > group names, you don't neef subclasses at all: > > a1 = SplinterBorg(group="one") > a2 = SplinterBorg(group="two") > > and so on. > > If you want to create subclasses then they should work like this: > > class MyBorg1(SplinterBorg): > def __init__(self): > SplinterBorg.__init__(self, group='borg1') > > and so on, with a different group for each. But this seems over complicated. > I do need subclasses (I think) as my classes inherit from more than the SplinterBorg class... I'll see what I can do following some of your suggestions. Thanks for the reply, Andr? > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 3 05:34:31 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 03 Sep 2007 11:34:31 +0200 Subject: Adding attributes stored in a list to a class dynamically. In-Reply-To: <1188794274.562413.70140@k79g2000hse.googlegroups.com> References: <1i3t9va.1jkz4om1sajk8pN%aleax@mac.com> <1188769303.724140.248630@d55g2000hsg.googlegroups.com> <13dmehro14cjp05@corp.supernews.com> <1188794274.562413.70140@k79g2000hse.googlegroups.com> Message-ID: <46dbd527$0$5441$426a74cc@news.free.fr> Brian Munroe a ?crit : > On Sep 2, 3:33 pm, Steven D'Aprano cybersource.com.au> wrote: > >> In a nutshell, like all double-underscore methods, __setattr__ are for >> overriding behaviour in your own classes. With very few exceptions, you >> shouldn't need to directly call double-underscore methods (although you >> often may _write_ double-underscore methods). >> > > I think I understand. You are saying that if I wanted to override the > normal behavior when doing something like > > p1.firstName = "Brian" > > then I'd override __setattr__()? That's one possible solution. Another one is to use a property object or a custom descriptor (you should find relevant documentation on python.org). > But if I am doing something like creating dynamic attributes, the more > 'correct' way is to use setattr? Even though they both appear to do > the same thing, the more Pythonic way is to never directly call magic > methods (if you can help it)? Mainly, yes. From mccredie at gmail.com Thu Sep 20 18:57:16 2007 From: mccredie at gmail.com (Matt McCredie) Date: Thu, 20 Sep 2007 15:57:16 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190325588.608625.259800@q3g2000prf.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> Message-ID: <9e95df10709201557q22e7daedmae48eabd42f2b1a4@mail.gmail.com> On 9/20/07, Python Maniac wrote: > I am new to Python however I would like some feedback from those who > know more about Python than I do at this time. Well, you could save some time by not applying the scramble one line at a time (that is if you don't mind losing the line endings in the scrambled version). For that to be effective though, you probably want to open in binary mode. Also, your scramble can be written using list comprehension. [code] def scramble(s, key=0x80): return ''.join([chr(ord(c) ^ key) for c in s]) output = scramble(f.read()) [/code] If you use xor (^) as above, you can use the same method for scramble as descramble (running it again with the same key will descramble) and you can use an arbitrary key. Though, with 255 combinations, it isn't very strong encryption. If you want stronger encryption you can use the following AESish algorithm: [code] import random def scramble(s, key): random.seed(key) return ''.join([chr(ord(c) ^ random.randint(0,255)) for c in s]) [/code] This allows you to use much larger keys, but with a similar effect. Still not strong enough to be unbreakable, but much better than the origional. It is strong enough that someone knowing how you scrambled it will have trouble unscrambling it even if they don't know the key. Matt From donn at u.washington.edu Fri Sep 21 19:18:15 2007 From: donn at u.washington.edu (Donn Cave) Date: Fri, 21 Sep 2007 16:18:15 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> Message-ID: In article <1190410638.211343.241690 at y42g2000hsy.googlegroups.com>, Cristian wrote: ... > To someone who's learning to program wouldn't a syntax like the > further give them all they need and also reinforces the idea that > functions are data just like everything else? > > my_function = function(foo, bar): pass > an_instance_method = function(self, foo): pass > a_method_declaration = method(self, foo): pass I think one followup has already alluded to the division between Python `statements' and `expressions'. The `def' statement may create and bind a value, but since it's a statement and not an expression, it doesn't have any value. Python is not a functional programming language. It probably could be reinvented to eliminate statements, but ... there are already plenty of languages to choose from. If we're going there, though, I think it's obvious that once you have defined an_instance_method = function(self, foo): ... it should be invoked an_instance_method(an_instance, foo) which would be much less messy in nested expressions where the current standard OOP notation flips from right to left too much ... string.join(x.split('-'), '').lower() --> lower(string.join('', split(x, '-'))) It might make for some interesting problems, but that's what it's about, changing things so it stays fun for everyone. At the same time, partial function parameter binding should be implemented, so you could say dotted = string.join('.') ... v = dotted(['comp', 'lang', 'python']) As you probably well know, that isn't my idea, it's a common functional programming language idiom. Donn Cave, donn at u.washington.edu From stefan.arentz at gmail.com Thu Sep 6 03:00:02 2007 From: stefan.arentz at gmail.com (Stefan Arentz) Date: 06 Sep 2007 09:00:02 +0200 Subject: We need PIGs :) References: <46d74472$0$402$426a34cc@news.free.fr> Message-ID: <87hcm81dot.fsf@kip.sateh.com> Bruno Desthuilliers writes: ... > The problem with Java is that it makes it very painfull to bridge two > APIs together, while Python usually makes it a breeze (easy > delegation, no dumb-ass psycho-rigid type system). So Java's solution > (hyper-formalization) isn't necessary here. Interesting. I find Java much more predictable with APIs than Python actually. Java has pretty strict rules for style and API design, which basically all modern code follows pretty well. I think this is mostly the result of a strict JSR regime. What I find really frustrating in Python (combined with usually bad documentation) is that many people have different styles. The most frustratinng being getFoo() vs .foo, vs get_foo(). S. From kyosohma at gmail.com Thu Sep 6 10:56:43 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 06 Sep 2007 07:56:43 -0700 Subject: Finding specific date ranges Message-ID: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> Hi, I am working on a timesheet application in which I need to to find the first pay period in a month that is entirely contained in that month to calculate vacation time. Below are some example date ranges: December 31, 2006 January 13, 2007 # doesn't earn January 14, 2007 January 27, 2007 # does earn January 28, 2007 February 10, 2007 # doesn't February 11, 2007 February 24, 2007 # does So far, the best approach I've come up with is to create a list of tuples that contain the pay period date ranges for the year and iterate through the tuples looking for the first occurrence of the month names matching. Then I'd add that date range to a separate list and somehow ignore any other matches in that month. This seems like a hack. Does anyone have a better idea? Thanks in advance! Mike From michael at jedimindworks.com Sat Sep 22 00:42:14 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 21 Sep 2007 21:42:14 -0700 Subject: Killing A Process By PID In-Reply-To: References: <5970333469768353093@unknownmsgid> Message-ID: On Sep 20, 2007, at 7:46 PM, Arvind Singh wrote: > file('/var/lock/Application.lock', 'w').write(str(os.getpid())) > > Which to be honest appears to run just fine, when I look in that > file it always contains the correct process ID, for instance, 3419 > or something like that. > > I honestly doubt that. The I/O is buffered and you need to flush()/ > close() the file. Otherwise data may not get written until python > interpreter exits. Isn't the file closed after the file().write()? Seems to me that the great garbage collector in the sky will happily flush(), close() and forget it ever happened... -Michael --- "Those who don't understand UNIX are condemned to reinvent it, poorly." --Henry Spencer -------------- next part -------------- An HTML attachment was scrubbed... URL: From tleeuwenburg at gmail.com Fri Sep 14 20:11:29 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Sat, 15 Sep 2007 00:11:29 -0000 Subject: Python Papers Reader Survey Message-ID: <1189815089.525155.299620@19g2000hsx.googlegroups.com> Greetings, readers. I have put together a survey designed to capture a little information about how I can better target "The Python Papers" towards the needs of its readers. This survey has been created as a part of my "Marketing Management" assignment for my Masters of Business Administration study. The results will be used to help create a marketing plan for The Python Papers and should also help a great deal in practical terms. It will help to guide our efforts when soliciting articles from potential authors and other content- generation activities. The questions relate to primarily to areas of interest and are non-personal. The survey can be found at http://freeonlinesurveys.com/rendersurvey.asp?sid=nhozmh9qv9hl2oe333133 . The survey is not a long one and I imagine could be completed in under five minutes. Thanks very much, -Tennessee Leeuwenburg (Editor-In-Chief, The Python Papers) From larry.bates at websafe.com Wed Sep 12 16:50:33 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 12 Sep 2007 15:50:33 -0500 Subject: xml question In-Reply-To: References: Message-ID: JYOUNG79 at kc.rr.com wrote: > Just curious if there's any python xml parsing tools built into the Mac (OS 10.4.10 Tiger)? If so, > could anyone > share some simple code (or maybe point me to a web-site) of how to parse xml data from a > file? For example, if I > had a file that contained this: > > > > Black > Light Blue > Green > > > I'd want to look in the 'colors' xml element, then look at each 'color' xml element inside and > pull any that have > values (which would be Black, Light Blue and Green). I'd like to know how to pull 'attributes' > too. > > Thanks very much for your help. > > Jay Python 2.5 has elementtree built into it. You should be able to parse the XML and extract anything you want. -Larry From grante at visi.com Sat Sep 1 00:28:26 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 01 Sep 2007 04:28:26 -0000 Subject: strings (dollar.cents) into floats References: <877incd20i.fsf@benfinney.id.au> <46d75cf3$0$7698$9b4e6d93@newsspool2.arcor-online.net> <1188575044.874256.42960@50g2000hsm.googlegroups.com> Message-ID: <13dhqjalm8hln79@corp.supernews.com> On 2007-09-01, Lawrence D'Oliveiro wrote: > In message <1188575044.874256.42960 at 50g2000hsm.googlegroups.com>, > sturlamolden wrote: > >> There are fractions that can be exactly represented by floats that >> cannot be exactly represented by decimals. > > There are no such. In that statement does "float" mean finite-length base-2 FP and "decimal" mean finite-length base-10 FP? -- Grant Edwards grante Yow! My LESLIE GORE record at is BROKEN... visi.com From gherron at islandtraining.com Tue Sep 4 03:55:16 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 04 Sep 2007 00:55:16 -0700 Subject: how to get a formatted string? In-Reply-To: <006301c7eec7$654a9e00$4de1a8c0@amd.com> References: <46DCD51B.7040508@v.loewis.de> <006301c7eec7$654a9e00$4de1a8c0@amd.com> Message-ID: <46DD0F64.807@islandtraining.com> Ginger wrote: > like format function in Visual Basic, > format("##.##%",0.3456) ==>> 34.56% > "%5.2f%%" % (0.3456*100) '34.56%' See this section of the manual: http://docs.python.org/lib/typesseq-strings.html Gary Herron From daniel.j.larsson at gmail.com Fri Sep 7 09:37:44 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Fri, 7 Sep 2007 15:37:44 +0200 Subject: Class design (information hiding) In-Reply-To: References: <46e1305e$0$18302$426a74cc@news.free.fr> Message-ID: <2bfa72fa0709070637q2ec34e0ft60ce6cdc106daeb0@mail.gmail.com> On 9/7/07, Alexander Eisenhuth wrote: > > Bruno Desthuilliers schrieb: > > > Nope. It's either 'interface' (no leading underscore), 'implementation' > > (single leading underscore), 'implementation with some protection > > against accidental overriding' (two leading underscores). > > What do you mean with 'implementation'? What does it express? "Don't touch my _members, they're my private parts! If you do, face the consequences!" Again, this isn't enforced by the language (other than the slight name mangling on __names), but a convention that python programmers should adhere to. -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Sat Sep 1 09:24:40 2007 From: roy at panix.com (Roy Smith) Date: Sat, 01 Sep 2007 09:24:40 -0400 Subject: Co-developers wanted: document markup language References: <87odgyyx9u.fsf@wilson.homeunix.com> <87tzqpew22.fsf@wilson.homeunix.com> <87tzqp77my.fsf@wilson.homeunix.com> <7xy7g1if24.fsf@ruckus.brouhaha.com> Message-ID: Lawrence D'Oliveiro wrote: > By the way, did you know there was life before TEX? Back in that era, the > main open-source markup system in use was ... troff. Still not quite dead > today, it lives on in the definition of Unix/Linux man pages. I would hardly call troff "open source", at least not "back in that era". When I first started using roff and nroff, you had to sign all sorts of non-disclosure paperwork to get a copy of Unix. It wasn't until much later that things like the BSD and GNU projects started coming out with open source versions. Of course, the whole roff family is based on the old runoff program (which in turn was probably based on something else). Anybody remember Scribe? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 12 10:14:41 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 12 Sep 2007 16:14:41 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189604018.520338.162520@57g2000hsv.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> Message-ID: <46e7f450$0$12305$426a74cc@news.free.fr> Dave Hansen a ?crit : (snip) > As others have mentioned, you can also provide local synonyms if the > dot syntax is too onerous. But make sure you use the member access > syntax if the result of an expression is an immutable type. For > example, I assume a_dot is a mutable type, such as a list. If so, > then you could simply use > > a_dot, k, a, u = self.a_dot, self.k, self.a, self.u > a_dot = -k(a-u) > > However, if it's an immutable type, such as a scalar, strung, or > tuple, you need > > self.a_dot = -k(a-u) Hmmm... Actually, whether self.a_dot is an instance of a mutable or immutable type won't change anything - in both case, it's only the *local* name a_dot that'll be rebound. So as soon as you want to rebind (iow:assign to) an attribute, you *need* to use self.the_attr_name on the LHS. Of course, *mutating* is a different situation... From jelleferinga at gmail.com Thu Sep 6 13:28:33 2007 From: jelleferinga at gmail.com (jelle) Date: Thu, 06 Sep 2007 17:28:33 -0000 Subject: initializing cooperative method In-Reply-To: <13e0bgg5lo0p2ec@corp.supernews.com> References: <1189095131.853954.233660@r34g2000hsd.googlegroups.com> <13e0bgg5lo0p2ec@corp.supernews.com> Message-ID: <1189099713.851340.288580@r29g2000hsg.googlegroups.com> Ai, calling super(Abstract) is just getting object, sure... However, I'm still curious to know if there's a good idiom for repeating the argument in __init__ for the super(Concrete, self).__init__ ? Thanks, -jelle From wizzardx at gmail.com Fri Sep 21 15:53:15 2007 From: wizzardx at gmail.com (David) Date: Fri, 21 Sep 2007 21:53:15 +0200 Subject: Python Regex Question In-Reply-To: <46f415ff$0$3060$e4fe514c@dreader31.news.xs4all.nl> References: <1190316811.760038.145850@50g2000hsm.googlegroups.com> <46f2c7e8$0$21956$88260bb3@free.teranews.com> <1190332336.357719.28060@19g2000hsx.googlegroups.com> <46f415ff$0$3060$e4fe514c@dreader31.news.xs4all.nl> Message-ID: <18c1e6480709211253h26702b5bk9962b1a2e9b3f276@mail.gmail.com> > re.search(expr, string) compiles and searches every time. This can > potentially be more expensive in calculating power. especially if you > have to use the expression a lot of times. The re module-level helper functions cache expressions and their compiled form in a dict. They are only compiled once. The main overhead would be for repeated dict lookups. See sre.py (included from re.py) for more details. /usr/lib/python2.4/sre.py From bignose+hates-spam at benfinney.id.au Wed Sep 26 02:20:57 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 26 Sep 2007 16:20:57 +1000 Subject: setuptools without unexpected downloads References: <87ejgmklep.fsf@benfinney.id.au> Message-ID: <878x6ukkvq.fsf@benfinney.id.au> Ben Finney writes: > How can I, as the distributor of a package using setuptools, gain > the benefits of dependency declaration and checking, without the > drawback of unexpected and potentially unwanted download and > installation? To clarify: I want to retain the "assert the specified dependencies are satisfied" behaviour, without the "... and, if not, download and install them the Setuptools Way" behaviour. Instead, I just want the default "dependencies not satisfied" behaviour for my 'setup.py' program to be: complain the dependencies aren't met, and refuse to install. If I can set that default, and allow individual users to specifically override that and get the "download and install un-met dependencies" behaviour if they want, all well and good; but that's not necessary. How can I get this happening with setuptools? -- \ "One time a cop pulled me over for running a stop sign. He | `\ said, 'Didn't you see the stop sign?' I said, 'Yeah, but I | _o__) don't believe everything I read.'" -- Steven Wright | Ben Finney From ldo at geek-central.gen.new_zealand Sun Sep 2 05:50:18 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 02 Sep 2007 21:50:18 +1200 Subject: So what exactly is a complex number? References: <451mq4-les.ln1@ozzie.tundraware.com> <46d89ba9$0$30380$9b4e6d93@newsspool4.arcor-online.net> <46d92f54$0$4533$9b4e6d93@newsspool3.arcor-online.net> Message-ID: In message , Tim Daneliuk wrote: > No, but go to my other example of an aircraft in flight and winds > aloft. It is exactly the case that complex numbers provide a convenient > way to add these two "vectors" (don't wince, please) to provide the > effective speed and direction of the aircraft. Numerous such examples > abound in physics, circuit analysis, the analysis of rotating machinery, > etc. Not really. The thing with complex numbers is that they're numbers--mathematically, they comprise a "number system" with operations called "addition", "subtraction", "multiplication" and "division" having certain well-defined properties (e.g. associativity of multiplication, all numbers except possibly one not having a multiplicative inverse). An aircraft in flight amidst winds needs only vector addition (and possibly scalar multiplication) among the basic operations to compute its path--you don't need to work with complex numbers as such for that purpose. For my AC circuit theory example, however, you do. From stephane at harobed.org Mon Sep 24 16:47:18 2007 From: stephane at harobed.org (KLEIN Stephane) Date: Mon, 24 Sep 2007 20:47:18 +0000 (UTC) Subject: I don't undestand why sometime python (or other) add "tmpWvk7zy" (tmp + random string) after "buildout-eggs" in path of python script Message-ID: Hi, first, I think that my question is generalist and don't impact only zopeproject and/or Paste package. Instance, when I trace (debug) some scripts, its name is "/home/harobed/ buildout-eggs/tmpWvk7zy/PasteScript-1.3.6-py2.5.egg/paste/script/ serve.py" instead of "/home/harobed/buildout-eggs/PasteScript-1.3.6- py2.5.egg/paste/script/serve.py". I don't understand why and who append "tmpWvk7zy" after "buildout-eggs". I don't know if it's related with python thread support. This trouble is very not useful to debug because pdb can't load source code for its path is not found. Thanks for your help. Stephane From wizzardx at gmail.com Mon Sep 10 02:27:11 2007 From: wizzardx at gmail.com (David) Date: Mon, 10 Sep 2007 08:27:11 +0200 Subject: Spell-checking Python source code In-Reply-To: <18c1e6480709090802t654abc98r3c2639c752a9568d@mail.gmail.com> References: <1189285495.185657.88010@o80g2000hse.googlegroups.com> <46E314FD.7030200@bigfoot.com> <18c1e6480709081444x69c4d23cx65f7c9b62eda8271@mail.gmail.com> <46E32273.2050304@bigfoot.com> <18c1e6480709090802t654abc98r3c2639c752a9568d@mail.gmail.com> Message-ID: <18c1e6480709092327r2e235d23mc4ebcc2c79640d0b@mail.gmail.com> On 9/9/07, David wrote: > > tokenize.tokenize( > > file.readline, > > processStrings > > ) > > > > How would you go about writing the output to a file? I mean, I would > > like to open the file at main level and pass a handle to the file to > > processStrings to write to it, finally close output file at main level. > > Probably a class with a processString method? > You can also use closures for this. http://ivan.truemesh.com/archives/000411.html See the example in the "Assignment considered awkward" section. Since you're not assigning to your file variable in processStrings you don't have to use the list work-around mentioned later in the doc. From not_here at no_where.com Tue Sep 11 21:02:42 2007 From: not_here at no_where.com (Brian) Date: Tue, 11 Sep 2007 18:02:42 -0700 Subject: python 2.5 problems In-Reply-To: <1189410656.649807.63640@r29g2000hsg.googlegroups.com> References: <3nVEi.98555$Vk6.66626@newsfe07.phx> <1189410656.649807.63640@r29g2000hsg.googlegroups.com> Message-ID: Was not specific about my process. Yes, I did use the 'formal' windoze uninstall using Add/Remove Programs. I ran the same code and idle at work (XP Pro/SP2/Python 2.4) with no problems. My next step is to install python 2.5 at work. My Linux partition has Python 2.4, and I do not use idle on Linux, so the test would probably not be legit. any ideas/suggestions ??? Ant wrote: > On Sep 9, 6:57 pm, "O.R.Senthil Kumaran" wrote: >>> Finally deleted 2.2 and loaded 2.5 (see below), using >> Dont delete. Uninstall python 2.2 and additional modules if you have installed them. > > But since you've already deleted 2.2, download and reinstall 2.2, > uninstall 2.2 and 2.5 via Add/Remove Programs and then reinstall 2.5 > again. > > -- > Ant... > From nfrancken at gmail.com Thu Sep 6 19:01:16 2007 From: nfrancken at gmail.com (windandwaves) Date: Thu, 06 Sep 2007 16:01:16 -0700 Subject: why should I learn python In-Reply-To: <87zlzzs9by.fsf@wilson.homeunix.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <87zlzzs9by.fsf@wilson.homeunix.com> Message-ID: <1189119676.239459.325280@w3g2000hsg.googlegroups.com> On Sep 7, 10:44 am, Torsten Bronger wrote: > Hall?chen! > > Tom Brown writes: > > [...] Python has been by far the easiest to develop in. Some > > people might say it is not "real programming" because it is so > > easy. > > I can't believe this. Have you really heard such a statement? > > Tsch?, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > Jabber ID: bron... at jabber.org > (Seehttp://ime.webhop.orgfor ICQ, MSN, etc.) Hmmm, thank you all for your replies. I will do some research on the net (i did some already, but because I am really not much of a programmer, it is often too detailed for me). I have limited time, but it does sound like something to learn, just for fun and for practical use. How would you use it in a web development environment? I mean, in real practical terms. Could it assist with php? Is it easy to write GUI programs in Python? From kyosohma at gmail.com Fri Sep 28 15:46:09 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 28 Sep 2007 19:46:09 -0000 Subject: OCBC connection In-Reply-To: References: <1191000128.112881.111790@r29g2000hsg.googlegroups.com> Message-ID: <1191008769.878419.307310@k79g2000hse.googlegroups.com> On Sep 28, 1:07 pm, Steve Holden wrote: > kyoso... at gmail.com wrote: > > On Sep 28, 9:57 am, "Sugrue, Sean" wrote: > >> I'm trying to make an odbc connection to postgresql which is on a server > >> using python. > >> Does anyone have a code snippet to make a basic connection with a select > >> query? > > >> Sean > > > Sean, > > > This appears to be what you're looking for: > > >http://www.devx.com/opensource/Article/29071 > > > See also Python Database spec and module page: > > >http://www.python.org/topics/database/ > > Mike: > > This doesn't address the ODBC part of the inquiry. I was actually going > to respond saying I wasn't aware of an ODBC driver for PostgreSQL > (though I'd be surprised if there wasn't one). > > Using the psycopg2 module, which is my preferred PostgreSQL interface > module, it's easy to answer: > > >>> curs = conn.cursor() > >>> import psycopg2 as db > >>> conn = db.connect(database="pycon", user="username", > password="password", host="localhost", port=5432) > >>> curs = conn.cursor() > >>> curs.execute("SELECT orgid, orgname FROM organization") > >>> from pprint import pprint # just for neatness > >>> pprint(curs.fetchall()) > [(1, 'AB Strakt'), > (79, 'DevIS'), > ... > (113, 'Test Organization'), > (19, 'Holden Web LLC')] > >>> > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline Whoops! I almost posted some code using the adodb or the odbc module, which is what I would have probably used, but I figured I'd take a look and see if there was a postgres module available. I'm not seeing any basic differences between your code and the code I linked to though...except that if I ran your first line of code, I would get an exception as "conn" hasn't been defined yet. Whatever. I apologize for being misleading(?) Mike From Michael.O.Rivera at gmail.com Sun Sep 16 15:57:27 2007 From: Michael.O.Rivera at gmail.com (PFGCIO) Date: Sun, 16 Sep 2007 19:57:27 -0000 Subject: The path '/' was not found. Message-ID: <1189972647.697108.315460@g4g2000hsf.googlegroups.com> I've checked for space/tab problems twice. Any ideas? Thanks ahead of time. 404 Not Found The path '/' was not found. Page handler: "The path '/' was not found." Traceback (most recent call last): File "c:\python25\lib\site-packages\cherrypy-2.2.1-py2.5.egg\cherrypy \_cphttptools.py", line 105, in _run self.main() File "c:\python25\lib\site-packages\cherrypy-2.2.1-py2.5.egg\cherrypy \_cphttptools.py", line 246, in main page_handler, object_path, virtual_path = self.mapPathToObject(path) File "c:\python25\lib\site-packages\cherrypy-2.2.1-py2.5.egg\cherrypy \_cphttptools.py", line 312, in mapPathToObject raise cherrypy.NotFound(objectpath) NotFound: 404 controllers.py import logging import cherrypy from docutils.core import publish_parts import turbogears from turbogears import controllers, expose, validate, redirect from brokerconduit import json from brokerconduit.model import Service class Root(controllers.RootController): @expose(template="brokerconduit.templates.home") def home(self , servicename="BrokerConduit"): service = Service.byServicename(servicename) return dict(service=service) From daniel.j.larsson at gmail.com Wed Sep 5 10:14:57 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Wed, 5 Sep 2007 16:14:57 +0200 Subject: handling modules in packages In-Reply-To: <384C9792-3923-42C6-8F9C-E3EB19B8811A@mac.com> References: <619B716A-C1EB-42DF-9702-E288AD04F613@mac.com> <384C9792-3923-42C6-8F9C-E3EB19B8811A@mac.com> Message-ID: <2bfa72fa0709050714u7c752ab3pc2f698a291d9f8c8@mail.gmail.com> On 9/5/07, Tommy Grav wrote: > > >> > > The simplest thing to do would be to have PyAstro.__init__.py > > import all > > the sub-modules, and define __all__ as the set of names that the > > package > > should inject into importing modules. > > > > Then you could write (for example) > > > > from PyAstro import numpy, constants, conversion, obsrvations > > > > However if you are simply worried about run-time efficiency then don't > > be: once a module is imported further imports essentially reduce to > > checking that the module is already present in the sys.modules > > dict, and > > so take almost no time at all. > > So am I understanding it right that a second import numpy statement > in a different module (and thus a different namespace) just results in > a binding to the already existing numpy "object"? Yes, correct -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Sep 25 04:40:37 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Sep 2007 10:40:37 +0200 Subject: strange behavious of the logging module? References: <1190643051.084144.230220@o80g2000hse.googlegroups.com> <1190672978.233964.232900@g4g2000hsf.googlegroups.com> Message-ID: Christian Meesters wrote: > Peter Otten wrote: > >> Vinay Sajip wrote: >> >>> This is a known bug, and not specifically related to logging, though >>> it sometimes manifests itself via logging: >>> >>> http://bugs.python.org/issue1180193 >> >> Yup, thanks for looking into it. >> >> Peter > Thanks Vinay, but I am curious how issue 1180193 is related to the "bug" > Peter and me described: I do not have any *.pyc file around. As I kept > changing the file during development I used to call the program directly > using a link in my PATH. Hence no *.pyc file got created at all. The problem is not caused by the pyc-file for your script, but by the logging/__init__.pyc file in your python installation. You can check if you are affected by the bug by typing >>> logging.info.func_code.co_filename 'logging/__init__.py' >>> logging._srcfile '/usr/lib/python2.5/logging/__init__.py' in the interpreter. If you get different paths like in "logging" and "/usr/lib/python2.5/logging" in the above example you are affected. > However, does anybody know a suggestion for a work-around? You could try setting logging._srcfile = logging.info.func_code.co_filename manually, but that might break other things. Or you recreate the pyc-files of your distribution. Again, I don't know what might break... Peter From per9000 at gmail.com Sun Sep 23 09:40:21 2007 From: per9000 at gmail.com (per9000) Date: Sun, 23 Sep 2007 06:40:21 -0700 Subject: annoying stdin/stdout + pipes problem Message-ID: <1190554821.677666.93530@w3g2000hsg.googlegroups.com> Hi, I want to create a program that reads input from stdio that can prompt a user for input while doing so without getting into problems. A simplified version of what I want: I have an input file ***>cat input.txt foo bar baz fubar barooba xyxxyt raboof txet black knight And a file that replaces certain words ***>cat replace2.py from sys import stdin, stdout def censor(foo, bar, input): return input.replace(foo, bar) # i = raw_input('Remove what? ').strip() # o = raw_input('Replace "%s" with what? ' %i).strip() for line in stdin.xreadlines(): line = censor('foo', 'candy', line) line = censor('bar', 'donkey', line) line = censor('baz', 'hare rama', line) # line = censor(i, o, line) stdout.write(line) ***>cat input.txt | python replace2.py candy donkey hare rama fudonkey donkeyooba xyxxyt raboof txet black knight As you can see I have commented out what I'd like to do but do not know how to. Can I somehow halt the previous print to stdout (cat input.txt) - if so can I then start it again, and how? I want to use this to use it in a small encryption program called txet in order to do something like this: tar -blabla ~ | gzip -blabla | txet -e -stdin -stdout > /tmp/ home.tar.gz.txet Of course I want to use it to get the password from the user. Thanks, Per PS: a prototype can be downloaded from www.txet.org From mensanator at aol.com Sat Sep 22 12:50:40 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 22 Sep 2007 09:50:40 -0700 Subject: Getting rid of bitwise operators in Python 3? In-Reply-To: <46f49740$0$32514$4c368faf@roadrunner.com> References: <46f49740$0$32514$4c368faf@roadrunner.com> Message-ID: <1190479840.694294.301720@o80g2000hse.googlegroups.com> On Sep 21, 10:44?pm, Carl Banks wrote: > Anyone with me here? (I know the deadline for P3 PEPs has passed; this > is just talk.) Are you a loony? Python doesn't have enough bit operations. I'm always using the gmpy module's bit functions: digits(...) digits(x[,base]): returns Python string representing x in the given base (2 to 36, default 10 if omitted or 0); leading '-' present if x<0, but no leading '+' if x>=0. x must be an mpz, or else gets coerced into one. getbit(...) getbit(x,n): returns 0 or 1, the bit-value of bit n of x; n must be an ordinary Python int, >=0; x is an mpz, or else gets coerced to one. hamdist(...) hamdist(x,y): returns the Hamming distance (number of bit-positions where the bits differ) between x and y. x and y must be mpz, or else get coerced to mpz. lowbits(...) lowbits(x,n): returns the n lowest bits of x; n must be an ordinary Python int, >0; x must be an mpz, or else gets coerced to one. numdigits(...) numdigits(x[,base]): returns length of string representing x in the given base (2 to 36, default 10 if omitted or 0); the value returned may sometimes be 1 more than necessary; no provision for any 'sign' characte, nor leading '0' or '0x' decoration, is made in the returned length. x must be an mpz, or else gets coerced into one. popcount(...) popcount(x): returns the number of 1-bits set in x; note that this is 'infinite' if x<0, and in that case, -1 is returned. x must be an mpz, or else gets coerced to one. scan0(...) scan0(x, n=0): returns the bit-index of the first 0-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 0-bits are in x at or above bit-index n (which can only happen for x<0, notionally extended with infinite 1-bits), None is returned. x must be an mpz, or else gets coerced to one. scan1(...) scan1(x, n=0): returns the bit-index of the first 1-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 1-bits are in x at or above bit-index n (which can only happen for x>=0, notionally extended with infinite 0-bits), None is returned. x must be an mpz, or else gets coerced to one. setbit(...) setbit(x,n,v=1): returns a copy of the value of x, with bit n set to value v; n must be an ordinary Python int, >=0; v, 0 or !=0; x must be an mpz, or else gets coerced to one. And I don't do hardware, I do math research where things like Hamming distance, popcount and scan1 are used extensively along with Python's bit operators like >>. Hey, I never use classes, maybe we should get rid of them also, eh? From aahz at pythoncraft.com Sun Sep 2 12:40:41 2007 From: aahz at pythoncraft.com (Aahz) Date: 2 Sep 2007 09:40:41 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <1188709535.459572.22130@r34g2000hsd.googlegroups.com> Message-ID: In article <1188709535.459572.22130 at r34g2000hsd.googlegroups.com>, Russ wrote: > >Excellent points. As for "no strong case for adding new features to >Python specifically for design-by-contract," if you mean adding >something to language itself, I agree, but I see nothing wrong with >adding it to the standard libraries, if that is possible without >changing the language itself. Someone please correct me if I am wrong, >but I think PEP adds only to the libraries. You're wrong, but even aside from that, libraries need to prove themselves useful before they get added. -- 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 http://www.lysator.liu.se/c/ten-commandments.html From python at cx.hu Tue Sep 4 18:09:46 2007 From: python at cx.hu (Ferenczi Viktor) Date: Wed, 5 Sep 2007 00:09:46 +0200 Subject: doctest and decorators In-Reply-To: <2bfa72fa0709041452o72d9a98fp939852d061a2cda3@mail.gmail.com> References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> <200709042316.08263.python@cx.hu> <2bfa72fa0709041452o72d9a98fp939852d061a2cda3@mail.gmail.com> Message-ID: <200709050009.46380.python@cx.hu> > > @functools.wraps(f) > > Pass the function to be wrapped by the decorator to the wraps function. > Ooops, right. That doesn't change the fact that decorated functions get > hidden from doctest though. Run my test script (one file) with the -v (verbose) option. Without the -v option it does not show output. This fact is documented in the Python manual at the doctest module. --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- import functools def simplelog(f): @functools.wraps(f) def new_f(*args, **kwds): print "Wrapper calling func" return f(*args, **kwds) return new_f @simplelog def test(): """ >>> test() Wrapper calling func 'works!' """ return 'works!' def fn(): """ >>> fn() 'ok' """ return 'ok' if __name__ == '__main__': import doctest doctest.testmod() --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- Regard, Viktor From surekap at gmail.com Thu Sep 13 00:26:16 2007 From: surekap at gmail.com (Prateek) Date: Wed, 12 Sep 2007 21:26:16 -0700 Subject: Possible suggestion for removing the GIL Message-ID: <1189657576.772108.136550@d55g2000hsg.googlegroups.com> Hi, Recently there was some talk on removing the GIL and even the BDFL has written a blog post on it. I was trying to come up with a scalable and backwards compatible approach for how to do it. I've put my thoughts up in a blog post - and I'd really like to hear what the community thinks of it. Mainly it revolves around dedicating one core for executing synchronized code and doing context switches instead of acquiring/ releasing locks. http://www.brainwavelive.com/blog/index.php?/archives/12-Suggestion-for-removing-the-Python-Global-Interpreter-Lock.html Thanks, Prateek Sureka From deets at nospam.web.de Wed Sep 5 08:59:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Sep 2007 14:59:55 +0200 Subject: threads References: <1188995538.507987.142250@k79g2000hse.googlegroups.com> Message-ID: <5k7nicF2ho9gU1@mid.uni-berlin.de> vijayca wrote: > i have written a script that spawns some threads.... > all run in parallel.... > now i need to stop all the threads once i press a key(example: "\n") > how to do it... That's a FAQ. Search this NG/ML for exhaustive discussions. The quick answer is: - you can't stop externally - so you must rely on frequently checking some flag inside your worker threads. Like this (untested): class MyThread(Thread): def __init__(self): Thread.__init__(self) self.running = True def run(self): while self.running: work() Set MyThread.running to False when the key is pressed. Diez From subscriber100 at rjs.org Fri Sep 28 10:48:52 2007 From: subscriber100 at rjs.org (Ray Schumacher) Date: Fri, 28 Sep 2007 07:48:52 -0700 Subject: is there a posh Win32 binary? or, compiling with MS 2005 Express... Message-ID: <6.2.3.4.2.20070928073722.03435950@pop-server.san.rr.com> Is there a posh Win32 binary? Or better, has anyone successfully compiled modules for Python 2.4 with the newest "free" tools? Do I need to move to 2.5? I could not get it to compile with my (apparently incomplete) MS C++ 7.1 install (which did, however, work for weave/blitz, before). The 7.1 compiler with the 1.1SDK is no longer available, so I can't repair the install. I went through the motions of compiling yesterday with the new MS Express Toolkit on another machine and failed. Distutils keeps saying that the SDK for 7.1 is not installed. Ray From timaranz at gmail.com Thu Sep 27 20:31:06 2007 From: timaranz at gmail.com (timaranz at gmail.com) Date: Thu, 27 Sep 2007 17:31:06 -0700 Subject: developing an application In-Reply-To: <1190930761.625756.309830@50g2000hsm.googlegroups.com> References: <1190930761.625756.309830@50g2000hsm.googlegroups.com> Message-ID: <1190939466.475390.58460@g4g2000hsf.googlegroups.com> On Sep 28, 10:06 am, yadin wrote: > hi! > i was buiding an application using python...a program > this was my first one...now that i got it working perfectly > how can i put the bunch of files into one package? > the user of the appliation will not know where to start? that is which > file to click on in oder to start the program? > thanks a lot Check out py2exe and distutils From pavlovevidence at gmail.com Sat Sep 22 03:03:30 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Sep 2007 03:03:30 -0400 Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> <13f99fediasg3ae@corp.supernews.com> Message-ID: <46f4c171$0$26367$4c368faf@roadrunner.com> On Sat, 22 Sep 2007 05:19:42 +0000, Grant Edwards wrote: > On 2007-09-22, Carl Banks wrote: > >> Anyone with me here? (I know the deadline for P3 PEPs has passed; this >> is just talk.) > > Not me. > >> Not many people are bit-fiddling these days. > > I do. Your anecdotal evidence is noted and given all the consideration it's due. >> One of the main uses of bit fields is flags, but that's not often done >> in Python because of keyword arguments and dicts, which are lot more >> versatile. Another major use, talking to hardware, is not something >> oft done in Python either. > > I do it all the time. Anecdotes again. Do you have any stats on the usage of hardware interfacing in Python? That would be a lot more useful. > Bit fiddling is also required for implementing communications > prototocols. Fair enough. That is a big issue, and defintely common on Python. >> Is it worth it to make such a change? It would remove a lot of >> operators (11 by my count), vastly simplifying syntax, Which, IMHO, is >> no small thing. > > If you don't want to use the bitwise operations, then ignore them. > Presto! Simpler syntax. Until people no longer need to read code written by others, this argument is utter bull. It's completely besides the point, anyways. The point is to make the language core smaller. It would shift code implementing bitwise logic out the core parts of Python, and localize it in modulespace. It's not about trying to make the mental footprint of the language smaller; in fact, wouldn't do that at all. >> Obviously, how widespread their usage is would matter. But keep in >> mind it would also be easy to convert the code automatically, because >> the Python parser could reliably find all bitwise operations reliably. > > The resulting code wold be fugly. Of course it would be. The reason I mention it is that automatic convertibility is a key factor in whether a change can make it into Python 3. Carl Banks From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Sep 30 19:23:29 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 01 Oct 2007 01:23:29 +0200 Subject: Can you please give me some advice? References: <13fuv0gh7342r27@corp.supernews.com> <1191173228.756531.225860@o80g2000hse.googlegroups.com> Message-ID: <5mapfhFccc9cU1@mid.individual.net> cmpython at gmail.com wrote: > And, as someone who has been learning Python from almost no > knowledge of programming, I've found it is not too bad in trying > to keep as reasonably close to a natural language like English > as possible. Sure, your next project should be learning COBOL -- it must be *very* intuitive. > On the other hand, perhaps because Ruby is newer it has been able > to freshly start with advantages learned from the difficulties of > other languages. What are those advantages in respect to Python? Regards, Bj?rn -- BOFH excuse #4: static from nylon underwear From steve at REMOVE-THIS-cybersource.com.au Sat Sep 15 20:48:39 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Sep 2007 00:48:39 -0000 Subject: Python statements not forcing whitespace is messy? References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> <46EC3C6E.6050002@sdf.lonestar.org> Message-ID: <13eovb712m4j62f@corp.supernews.com> On Sun, 16 Sep 2007 09:14:57 +0900, Ryan Ginstrom wrote: >> On Behalf Of J. Cliff Dyer >> On the other hand, this is just as bad: >> >> [ ( y ) for ( x , y ) in [ ( "foo" , 2 ) , ( "bar" , 4 ) ] if "foo" in >> ( x ) ] > > I think that's allowed in order to recruit C/C++ programmers. Heh :) In all seriousness, sometimes, in an extremely crowded and busy expression, adding a little extra whitespace to emphasize the boundaries between sub-expressions is a good thing. And let's not forget that we can do this: >>> complex_expression = ( ... 2*x + # double the whatzit ... 1.78**(c*3-1) + # see chapter 2 of Martelli, 2008 ... sin(radians(80)) # angle between the foo and the bar ... ) -- Steven. From jscrerar at compuserve.com Sun Sep 30 20:29:38 2007 From: jscrerar at compuserve.com (Jim) Date: Sun, 30 Sep 2007 17:29:38 -0700 Subject: Command-line does work when scheduled In-Reply-To: <13g0f31ak031jc4@corp.supernews.com> References: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> <1191104269.578536.56470@g4g2000hsf.googlegroups.com> <1191114246.668635.327080@o80g2000hse.googlegroups.com> <1191163376.067339.34740@d55g2000hsg.googlegroups.com> <13g0f31ak031jc4@corp.supernews.com> Message-ID: <1191198578.984891.233620@19g2000hsx.googlegroups.com> On Sep 30, 6:16 pm, Dennis Lee Bieber wrote: > On Sun, 30 Sep 2007 07:42:56 -0700, Jim > declaimed the following in comp.lang.python: > > > What else could be wrong? > > Thanks, > > Possibly those associations are only defined for your login account, > and not active for the "account" that the task scheduler is running > under? > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ As far as know, since I'm the major user of my PC it runs under my account (computer administrator). It even asked for the password for my account when I added this scheduled task. Any further ideas? Thanks, Jim From steve at holdenweb.com Sat Sep 15 17:49:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 15 Sep 2007 17:49:54 -0400 Subject: Python statements not forcing whitespace is messy? In-Reply-To: <1189890755.870694.29790@r29g2000hsg.googlegroups.com> References: <1189884110.006272.240840@50g2000hsm.googlegroups.com> <1189890755.870694.29790@r29g2000hsg.googlegroups.com> Message-ID: buffi wrote: > On Sep 15, 10:11 pm, "J. Cliff Dyer" wrote: >> buffi wrote: >>> Am I the only one that thinks that python statements should force >>> whitespace before and after them? >>> Right now this is not enforced and for an example these statements are >>> valid >>> print"hello" >>> "foo"if"bar"else"foobar" >>> for(x,y)in[(1,2),(3,4)]:print(x,y) >>> [(y)for(x,y)in[("foo",2),("bar",4)]if"foo"in(x)] >>> ...and so on. >> On the other hand, this is just as bad: >> >> [ ( y ) for ( x , y ) in [ ( "foo" , 2 ) , ( "bar" , 4 ) ] if "foo" in ( >> x ) ] >> >> And I'd hate to have to remember all of the rules for what can go >> together and what can't, especially when it comes time to debug. No. >> I don't think it should be forced, but maybe put it in PEP8 or PEP3008. >> >> Also, the only thing I find thoroughly disagreeable in all of that >> mess, is the run-ins involving " characters. The rest are at least >> clear at a glance what belongs where. >> >> Also, would you require the following? >> >> my_function (swallow='European') >> >> Because that is just an awful use of whitespace. >> >> Cheers, >> Cliff > > I believe that having whitespace around the builtin statements, and > having whitespace around everything is pretty different. > > There would be no downside whatsoever to enforcing this, except for > backwards incompatibility (which is a rather huge downside but well... > py3k is gonna break everything anyways). There obviously shouldnt be > any limit to the maximum amount of whitespace used around statements > (due to formatting and so on), but allowing stuff like print"hello" is > just horrible. > If you don't like it then don't write it. I've been reading this group on and off for about ten years and I believe your email is the first to point out that this is possible. Clearly it isn't something that happens a lot, and I don't know why you have a bug up your ass about it, as the Americans say. The Python philosophy is to be permissive, and to expect individual users to write readable Python. Since they obviously do (one message in ten years providing a counter-example) I think you are wasting your time and energy on this. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From http Wed Sep 12 19:03:40 2007 From: http (Paul Rubin) Date: 12 Sep 2007 16:03:40 -0700 Subject: An ordered dictionary for the Python library? References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> Message-ID: <7xzlzrtrjn.fsf@ruckus.brouhaha.com> Mark Summerfield writes: > I feel that Python lacks one useful data structure: an ordered > dictionary. > Do other Python programmers feel this lack? Is this worth a PEP? Yes. It should use a functional data structure. From robin at NOSPAMreportlab.com Sun Sep 30 11:54:12 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sun, 30 Sep 2007 16:54:12 +0100 Subject: Create a string array of all comments in a html file... In-Reply-To: <1191166775.660477.97840@o80g2000hse.googlegroups.com> References: <1191166775.660477.97840@o80g2000hse.googlegroups.com> Message-ID: <46FFC6A4.6040200@jessikat.plus.net> sophie_newbie wrote: > Hi, I'm wondering how i'd go about extracting a string array of all > comments in a HTML file, HTML comments obviously taking the format > "". > > I'm fairly stumped on how to do this? Maybe using regular expressions? > > Thanks. > You should probably eat beautiful soup at http://www.crummy.com/software/BeautifulSoup/documentation.html which helps with this sort of task. -- Robin Becker From ptmcg at austin.rr.com Sun Sep 16 11:36:42 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 16 Sep 2007 08:36:42 -0700 Subject: Cannot formulate regex In-Reply-To: References: Message-ID: <1189957002.841152.178850@o80g2000hse.googlegroups.com> On Sep 16, 10:18 am, "Dotan Cohen" wrote: > I'd like to filter spam from a certain company. Here are examples of > strings found in their spam: > Mega Dik > Mega D1k > MegaDik > Mega. Dik > M eg ad ik > M E _G_A_D_ IK > M_E_G. ADI. K > > I figured that this regex would match all but the second example, yet > it matches none: > |[^a-z]m[^a-z]e[^a-z]g[^a-z]a[^a-z]d[^a-z]i[^a-z]k[^a-z]|i > > What would be the regex that matches "megadik" regardless of whatever > characters are sprinkled throughout? > > Thanks in advance. > > Dotan In your regex, every occurrence of "[^a-z]" requires a single character not in the a-z range. So what you have *should* match "M*E*G*A*D*I*K" (an unfortunate pr0n sequel to "M*A*S*H"?), but not any of your examples. You will need to add an '*' character to your [^a-z]'s, as in: [^a-z]*m[^a-z]*e[^a-z]*g[^a-z]*a[^a-z]*d[^a-z]*i[^a-z]*k[^a-z]* to indicate "0 or more" repetitions of [^a-z]. Also, I would omit the leading and trailing "[^a-z]*"s - I think they will significantly slow down your regex. -- Paul From aisaac at american.edu Wed Sep 5 23:31:43 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 06 Sep 2007 03:31:43 GMT Subject: Any syntactic cleanup likely for Py3? And what about doc standards? In-Reply-To: <87ejhc8z23.fsf@wilson.homeunix.com> References: <46DEFD2E.5050205@sbcglobal.net> <87tzq898e2.fsf@wilson.homeunix.com> <87ejhc8z23.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: > I like to use properties. However, Python already > has properties. Their syntax is quite nice in my opinion, and > rather explicit, too. Yes. > Their only flaw is that they are not > "virtual" (in C++ speak). In other words, you can't pass a "self" > parameter to them. http://www.kylev.com/2004/10/13/fun-with-python-properties/ fwiw, Alan Isaac From __peter__ at web.de Wed Sep 19 09:45:45 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Sep 2007 15:45:45 +0200 Subject: Keeping a database connection with a Singleton? References: <1190208406.041953.115580@g4g2000hsf.googlegroups.com> Message-ID: exhuma.twn wrote: > I remember reading about the Singleton pattern in python and how it's > an unpythonic pattern and all. At the time I did not need the > Singleton anyways, so I just glanced over the document. > > But, setting this aside: I have an application where I have a > connection to a database. At some point in the application I open up a > new window. The new windows resides in a different module. So I have a > directory structure like this: > > - mainapp.py > - newwindow.py > > So I import "newwindow" in "mainapp" so I can instantiate and display > it. Meanwhile, the main-app has an open connection to the database. > What's the cleanest way to hand this connection to the new window? I > can see several possibilities: > > 1) Simply pass the connection as paramtere to the constructor of new- > window. > 2) Use the "Singleton" deisign pattern to keep a reference to the > connection > 3) Open up a completely new connection to the database in the new > window. > > Now, option 1) is clearly the easiest to implement, however, I somehow > tend to use option 2 (the singleton) as it's more flexible. Option 3 > looks ugly to me. > > This is a stuation I run into many times. And I am always faced with > the same choice. And I never know which one to chose. And now that I > am getting more and more comfortable with the basics of python, I > would like to know if I am missing something more "pythonic". > > So, what would you recommend? Passing the connection as a parameter is the best approach because it keeps the dependencies explicit. Also, it allows you to switch between singleton and one connection per window without ever touching the newwindow module. By the way, there is a pythonic (near) singleton: the module. So if you go with option 2, just move the connection setup into a separate module that you can import into client code. Peter From jstroud at mbi.ucla.edu Fri Sep 14 21:19:45 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 14 Sep 2007 18:19:45 -0700 Subject: How to avoid overflow errors In-Reply-To: <13em8vnr527rq20@corp.supernews.com> References: <13em8vnr527rq20@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > I thought that overflow errors would be a thing of the past now that > Python automatically converts ints to longs as needed. Unfortunately, > that is not the case. > >>>> class MyInt(int): > ... pass > ... >>>> MyInt(sys.maxint) > 2147483647 >>>> MyInt(sys.maxint+1) > Traceback (most recent call last): > File "", line 1, in > OverflowError: long int too large to convert to int > > > How do I subclass int and/or long so that my class also auto-converts > only when needed? > > > Use __new__. py> import sys py> py> class MyLong(long): ... pass ... py> class MyInt(int): ... def __new__(cls, *args, **kwargs): ... try: ... return int.__new__(cls, *args, **kwargs) ... except OverflowError: ... return MyLong(*args, **kwargs) ... py> MyInt(sys.maxint**2) 4611686014132420609L py> type(_) James From michele.simionato at gmail.com Thu Sep 13 01:08:56 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 12 Sep 2007 22:08:56 -0700 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1i4bnbp.1l8sr3mjdojghN%aleax@mac.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> <1i4bnbp.1l8sr3mjdojghN%aleax@mac.com> Message-ID: <1189660136.689766.295350@d55g2000hsg.googlegroups.com> On Sep 12, 1:05 pm, al... at mac.com (Alex Martelli) wrote: > Making, say, 'a' hiddenly mean 'x.a', within a function, requires a > decorator that suitably rewrites the function's bytecode... (after > which, it WOULD still be terrible and horrible and not to be used, just > as you say, but it might at least _work_;-). Main problem is, the > decorator needs to know the set of names to be "faked out" in this > terrible and horrible way at the time the 'def' statement executes: it > can't wait until runtime (to dynamically determine what's in var(self)) > before it rewrites the bytecode All right Alex, and since I had 20 minutes of spare time I implemented the decorator you are talking about by using the wonderful byteplay module ;) Here it is: import dis from byteplay import Code, LOAD_GLOBAL, LOAD_ATTR, LOAD_FAST, STORE_FAST def instance2local(varname): yield LOAD_FAST, 'self' yield LOAD_ATTR, varname yield STORE_FAST, varname def declare_instance_vars(*varnames): def dec(f): c = Code.from_code(f.func_code) # change LOAD_GLOBAL -> LOAD_FAST for i, (opcode, value) in enumerate(c.code): if opcode == LOAD_GLOBAL and value in varnames: c.code[i] = (LOAD_FAST, value) # insert instance2local assigments at the beginning assignments = [] for varname in varnames: for pair in instance2local(varname): assignments.append(pair) c.code[0:0] = assignments # redefine the code object f.func_code = c.to_code() return f return dec class Test(object): def __init__(self): self.a = 1 self.b = 2 def test1(self): a = self.a b = self.b return a * b @declare_instance_vars('a', 'b') def test2(self): return a * b co1 = Test.__dict__['test1'].func_code co2 = Test.__dict__['test2'].func_code print 'bytecode for test1' dis.dis(co1) print 'bytecode for test2' dis.dis(co2) t = Test() assert t.test1() == t.test2() It is still a hack, since one is not supposed to mess around with bytecodes, but at least it seems to work ;) [warning: I have not tested it more than you see] Michele Simionato From neilscad at hotmail.com Sat Sep 29 05:25:02 2007 From: neilscad at hotmail.com (neil) Date: Sat, 29 Sep 2007 21:25:02 +1200 Subject: python 2.5 and 3gb switch References: <46FDF800.5030504@v.loewis.de> Message-ID: no sir nothing spectacular like that, I'll explain further - The .blend file I have is 550mb It originates from 13,000+ meshes imported from Solidworks ( 3d CAD program) of a piece of machinery. A python script was used for this purpose -it also performed some other tasks on the meshes like matching materials from a library and identifying sharp edges for normals in the renderer. This part was not a problem - the commit space reached 2,4 gb The next step is to export it in parts of about 2 million faces each in a file format Indigo uses. I need to save and reopen to unload commit space to do that... this means I have about 1.4gb commit. If I start the export script it will run fine until just about the end - this consumes another 700mb - ( I have the max MS recommends -2.9gb- set in the 3gb switch to play with and I actually know this is the limit cos I've hit that too..) Right at this point I still have 800mb available but here's the kicker - It needs about the same 550mb to complete the save.I know this from previous work on lesser files. This is where python gives 'memerror'. Although the space is there it wont use it. I believe I should be using Python that is 3gb enabled as well This is the same error I ran across doing smaller tasks without the switch btw Blender does not crash. HTH Neil From bignose+hates-spam at benfinney.id.au Wed Sep 12 20:44:28 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 13 Sep 2007 10:44:28 +1000 Subject: Coming from Perl References: Message-ID: <87wsuv5r83.fsf@benfinney.id.au> Amer Neely writes: > A question I have, if someone here is familiar with Perl, does Python > have something like Perl's 'here document'? I'm not sure exactly what behaviour you want, but Python accepts literal strings to be triple-quoted (i.e. delimited by """ pairs or ''' pairs), which allows you to freely use literal line feed and quote characters inside that string. -- \ "Are you pondering what I'm pondering?" "I think so, Brain, but | `\ pants with horizontal stripes make me look chubby." -- _Pinky | _o__) and The Brain_ | Ben Finney From alain.barthe.65 at free.fr Sat Sep 22 17:32:27 2007 From: alain.barthe.65 at free.fr (Alain) Date: Sat, 22 Sep 2007 23:32:27 +0200 Subject: too many values with string.split In-Reply-To: References: Message-ID: <46f589d8$0$9504$426a34cc@news.free.fr> Shawn Minisall a ?crit : > I'm trying to unpack a list of 5 floats from a list read from a file and > python is telling me 5 variables are too many for the string.split > statement. Anyone have any other idea's? NOTE: the only reason I > convert it to a float instead of just leaving it as a string in the loop > is because I have to have it printed out as a float besides the names > and then the average displayed underneath > > thx > > #read in data line by line > for line in infile: > mylist = string.split(line) > firstName[counter] = mylist[0] > lastName[counter] = mylist[1] > grades[counter] = float(mylist[2]) > print firstName[counter], > lastName[counter],":","\t\t",grades[counter] > #increment counter > counter = counter + 1 > > #calculates and prints average score > grades = str(grades) > num1, num2, num3, num4, num5 = string.split(grades,",") > average = float(num1 + num2 + num3 + num4 + num5) / 5 > print > print "Average:" As I can see, grades is a string that looks like '[12.0,12.0, ...]' So you can't split it just with string.split () Rather than doing grades = str(grades) and split it, you have just to do : avarage = sum (grades) / len (grades) From koutoo at hotmail.com Mon Sep 24 15:28:07 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Mon, 24 Sep 2007 12:28:07 -0700 Subject: Nested For and While Statements Message-ID: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> I start my code with some constants then a while statement. But I have some For statements towards the end within the While statement where I start getting some errors. I'm hoping I won't have to post my code, but it looks something like this: Import os, string while this: All Code indented like it should Last line in While. For i in range(1) class = [] class2 = [] For i in range(2) Do this And this And that. Next Line hits snag here? Where should this line be? From paddy3118 at googlemail.com Sat Sep 1 03:30:26 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 01 Sep 2007 07:30:26 -0000 Subject: list index() (OT) and definitely trolling :-) In-Reply-To: References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188497498.3468.60.camel@dot.uniqsys.com> <0v2dnaYWyv4HWkrbnZ2dnUVZ_oTinZ2d@speakeasy.net> <1188551958.728836.137370@x35g2000prf.googlegroups.com> <6ftgd35rd1g4mddqg2f44d7svd4r85ev17@4ax.com> <13dhvs3p5drsd99@corp.supernews.com> Message-ID: <1188631826.355736.206920@k79g2000hse.googlegroups.com> On Sep 1, 7:32 am, Steve Holden wrote: > Dennis Lee Bieber wrote: > > On Fri, 31 Aug 2007 21:15:10 +0100, DaveM > > declaimed the following in comp.lang.python: > > >> No - but I would pronounce "lever" and "fever" the same way, if that helps. > > > To me, those are different... I suppose you also add an > > extra "i" to aluminum > > No, he just spells it with two i's like sensible people do. Who would > ever want *three* I's in "aluminium" (which, by the way, you misspelled ;-)? > > Such things are matters of practical significance to me, since I have > adopted a policy of using English spelling when in the UK and US > spelling when elsewhere. Since I am now pretty much full-time in the US, > I am finally having to come to terms with its crazy spelling. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > --------------- Asciimercial ------------------ > Get on the web: Blog, lens and tag the Internet > Many services currently offer free registration > ----------- Thank You for Reading ------------- Since the language that inspired the programming language is most definitely English as spoken in the UK, could it be that the highest levels of Pythonistic Nirvana are to be reached only by .... Nah - can't do it! (just spell colour right and I'll be OK). - Paddy. From lasses_weil at klapptsowieso.net Sat Sep 8 07:16:13 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sat, 08 Sep 2007 13:16:13 +0200 Subject: unexpected behavior: did i create a pointer? In-Reply-To: <13e4db4lp4tce86@corp.supernews.com> References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <13e2jdobu2kqkf1@corp.supernews.com> <13e4db4lp4tce86@corp.supernews.com> Message-ID: <46e2847d$0$30384$9b4e6d93@newsspool4.arcor-online.net> Dennis Lee Bieber wrote: > On Fri, 07 Sep 2007 12:19:12 -0700, Steve Holden > declaimed the following in comp.lang.python: > >> Since it's only a matter of time before someone brings up the "post-It" >> analogy, let me cavil in advance about it. The thing I don't like about >> that particular pedagogic mechanism is that it always "attaches" the >> names to the objects. >> > Fine... then visual the namespace as a box... Inside the box are the > "post-it notes" -- attached to the ends of strings that then run to the > "physical object" at the other end. This is getting clearer by the minute. ;) /W From pydecker at gmail.com Tue Sep 25 12:19:11 2007 From: pydecker at gmail.com (Peter Decker) Date: Tue, 25 Sep 2007 12:19:11 -0400 Subject: An Editor that Skips to the End of a Def In-Reply-To: <46F8FC3D.6050700@holdenweb.com> References: <87hclpjm3a.fsf@rudin.co.uk> <5lhs4pF8bkunU1@mid.individual.net> <5ls313F9ndm1U1@mid.individual.net> <46F8FC3D.6050700@holdenweb.com> Message-ID: On 9/25/07, Steve Holden wrote: > >> Why does it "choose" to modify your position when you exit insert > >> mode? Does the phrase "broken as designed" mean anything to you? > > > > Does the phrase "everything I don't like is stupid" mean anything to > > you? Honestly, if you don't like it, either propose improvement or > > stop using it (and complaining about it). Your preference with user > > interfaces is obviously different. (Personally, I prefer single > > strokes to breaking my fingers with Esc-Meta-Alt-Control-Shift. > > :) ) > > > Does "this non-Python related twaddle is boring the shit out of me" mean > anything to you both? +1 QOTW!! -- # p.d. From carsten at uniqsys.com Wed Sep 26 11:54:15 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 26 Sep 2007 11:54:15 -0400 Subject: regex with specific list of string In-Reply-To: <1190821357.753909.178210@50g2000hsm.googlegroups.com> References: <1190821357.753909.178210@50g2000hsm.googlegroups.com> Message-ID: <1190822055.3397.52.camel@dot.uniqsys.com> On Wed, 2007-09-26 at 15:42 +0000, james_027 wrote: > hi, > > how do I regex that could check on any of the value that match any one > of these ... 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', > 'sep', 'oct', 'nov', 'dec' Why regex? You can simply check if the given value is contained in the set of allowed values: >>> s = set(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']) >>> 'jan' in s True >>> 'spam' in s False HTH, -- Carsten Haese http://informixdb.sourceforge.net From zzbbaadd at aol.com Tue Sep 4 05:46:16 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 04 Sep 2007 02:46:16 -0700 Subject: parameter list notation In-Reply-To: References: <1188882028.165803.316540@r34g2000hsd.googlegroups.com> Message-ID: <1188899176.091592.247360@50g2000hsm.googlegroups.com> Steve, Ben, Duncan, Thanks for the replies. TFD From arvind1.singh at gmail.com Thu Sep 20 22:46:27 2007 From: arvind1.singh at gmail.com (Arvind Singh) Date: Fri, 21 Sep 2007 08:16:27 +0530 Subject: Killing A Process By PID In-Reply-To: <5970333469768353093@unknownmsgid> References: <5970333469768353093@unknownmsgid> Message-ID: file('/var/lock/Application.lock', 'w').write(str(os.getpid())) > > Which to be honest appears to run just fine, when I look in that file it > always contains the correct process ID, for instance, 3419 or something like > that. > I honestly doubt that. The I/O is buffered and you need to flush()/close() the file. Otherwise data may not get written until python interpreter exits. if file('/proc/%s/cmdline' % pid).read().endswith('python'): > > os.system('kill %s' % pid) > Are you sure about endswith('python')? Maybe you need find('python') != -1. -- Regards, Arvind -------------- next part -------------- An HTML attachment was scrubbed... URL: From xiaoyisheng at gmail.com Thu Sep 13 21:00:01 2007 From: xiaoyisheng at gmail.com (Pacino) Date: Fri, 14 Sep 2007 01:00:01 -0000 Subject: read part of jpeg file by pure python In-Reply-To: <1189683855.168075.325770@o80g2000hse.googlegroups.com> References: <1189671634.712690.154580@o80g2000hse.googlegroups.com> <1189673325.083163.210630@d55g2000hsg.googlegroups.com> <1189683855.168075.325770@o80g2000hse.googlegroups.com> Message-ID: <1189731601.307114.231020@19g2000hsx.googlegroups.com> On 9 13 , 7 44 , michal.zaborow... at gmail.com wrote: > On 13 Wrz, 10:48, Pacino wrote: > > > > > On 9 13 , 4 43 , Laurent Pointal wrote: > > > > Pacino a ?crit : > > > > > Hi, everyone, > > > > > I am wondering whether it's possible to read part (e.g. 1000*1000) of > > > > a huge jpeg file (e.g. 30000*30000) and save it to another jpeg file > > > > by pure python. I failed to read the whole file and split it, because > > > > it would cost 2GB memory. > > > > > Can anyone help me? Any comments would be appreciated. > > > > Just reading parts of the *file* is easy (see tell() seek() and read() > > > methods on files). > > > But to extract a part of the *picture*, you must uncompress the picture > > > in memory, grab the sub-picture, and save it back - generally with > > > compression. I can't see how you can bypass the uncompress/compress > > > phases and the corresponding memory use. > > > The most difficult part is the uncompress part. I don't want the whole > > picture to be uncompressed in the memory, because it will consume a > > lot of memory (2GB, as I mentioned). My goal is to uncompress part of > > the picture into the memory. > > > I just read some article on this subject (http://mail.python.org/ > > pipermail/image-sig/1999-April/000713.html) , but haven't test it out > > yet. > > I have no idea what it does. Anyway - jpeg: > 1. RGB -> HLV > 2. divide data into 8x8 - blocks of data. > 3. blocks are treated with discrete cosine transform. > 4. Result is filtered to remove "fast changes". > 5. Then result is compressed with Huffman alg. > > So to get part of image - you can take smaller image before step 4. > As far as I understand code presented at:http://mail.python.org/pipermail/image-sig/1999-April/000713.html > - full image will be loaded, and cutted. > > -- > Regards, > Micha? Zaborowski (TeXXaS)- - > > - - Thanks. Seems no ways to achieve the requirements. From fredrik at pythonware.com Wed Sep 26 04:09:46 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 10:09:46 +0200 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: <496954360709251516teda6f2dwe8190236029e3688@mail.gmail.com> References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> <496954360709251421l578b9dfdwcc0e67d293ede1f3@mail.gmail.com> <496954360709251516teda6f2dwe8190236029e3688@mail.gmail.com> Message-ID: Robert Dailey wrote: > Hmm, ElementTree.tostring() also adds a space between the last character > of the element name and the />. Not sure why it is doing this. ET is commonly used to generate (X)HTML fragments, and that space provides partial HTML compatibility. since the default serializer never generates CDATA sections, it should be safe to simply do a text.replace(" />", "/>") on the resulting string. From michele.simionato at gmail.com Wed Sep 5 01:35:37 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 04 Sep 2007 22:35:37 -0700 Subject: doctest and decorators In-Reply-To: References: <2bfa72fa0709041329i14b5b547i2eb85250f7547da@mail.gmail.com> <200709042316.08263.python@cx.hu> <2bfa72fa0709041452o72d9a98fp939852d061a2cda3@mail.gmail.com> <200709050009.46380.python@cx.hu> <2bfa72fa0709041529g9d5ac22hce3a55d5357b1a1c@mail.gmail.com> Message-ID: <1188970537.297655.256600@r34g2000hsd.googlegroups.com> > En Tue, 04 Sep 2007 19:29:11 -0300, Daniel Larsson > escribi?: > > > > > On 9/5/07, Ferenczi Viktor wrote: > > >> > > @functools.wraps(f) > >> > > Pass the function to be wrapped by the decorator to the wraps > >> function. > >> > Ooops, right. That doesn't change the fact that decorated functions > >> get > >> > hidden from doctest though. > > > I have no issue when the decorator is defined in the same module as the > > decorated function, my problem is running doctests on functions using an > > imported decorator. Having to implement the decorator in every source > > module > > isn't very practical. I cannot reproduce your problem. Using functools.wraps the __module__ attribute is set correctly and everything works, even for decorators defined in separated modules. Care to post a complete example of what you are doing? Michele Simionato P.S. for some reason your messages are not appearing on Google groups, I see only the replies. From daniel.j.larsson at gmail.com Wed Sep 5 07:47:50 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Wed, 5 Sep 2007 13:47:50 +0200 Subject: Accessing Module variables from another Module In-Reply-To: <1188981521.735630.133060@r29g2000hsg.googlegroups.com> References: <1188981521.735630.133060@r29g2000hsg.googlegroups.com> Message-ID: <2bfa72fa0709050447p1432a39dna3c2362aed542d32@mail.gmail.com> On 9/5/07, cjt22 at bath.ac.uk wrote: > > Hi > > I am new to Python (I have come from a large background of Java) and > wondered if someone could explain to me how I can access variables > stored in my main module to other functions within other modules > called > from this module No, don't introduce circular dependencies, and make it explicit what your functions operate on by passing things as parameters, instead of using global references. for example > file: main.py > > from Storage import store > from Initialise import init > from ProcessSteps import process > > storeList = store() #Creates a object to store Step objects > init() > process() It is *much* more preferable to pass 'storeList' as a parameter to your functions. Don't change things behind the scenes. file: Initialise.py > def init() > ...... > storeList.addStep([a,b,c]) > > > file: ProcessSteps.py > def process() > for step in storeList.stepList: > etc > > I am currently just passing the variable in as a parameter > but I thought with Python there would be a way to gain direct access > to > storeList within the modules called from the top main module? Keep it the way it is. It's wrong on too many levels to do it the other way. Cheers > Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joe at goldthwaites.com Thu Sep 27 17:56:03 2007 From: joe at goldthwaites.com (Joe Goldthwaite) Date: Thu, 27 Sep 2007 14:56:03 -0700 Subject: A question on python performance. In-Reply-To: <1190832113.527114.94230@d55g2000hsg.googlegroups.com> Message-ID: <002f01c80151$33c73090$6c01a8c0@applexp> chris.monsanto at gmail.com wrote: >Makes perfect sense to me! Think about it: > >method 1: looks up the method directly from the object (fastest) >method 2: looks up __class__, then looks up __dict__, then gets the >element from __dict__ >method 3: looks up caller, looks up __class__, looks up __dict__, gets >element from __dict__ > >To get the element directly from the object (method 1), Python has to >internally check __class__.__dict__[element], which shows why method 1 >and method 2 are nearly the same speed. The last version has to look >up caller in addition to the process described by method 2. > >The best way to do what you are doing: > >getattr(self, param)(self, *args) I didn't know about the getattr function. I tried to search for that type of function but not knowing how to word the search request, I couldn't find it. That's a lot cleaner way of doing what I was trying to do. I benchmarked it and it's so close in speed to the hard-coded method as to be identical. Paul Hankin wrote: >You're calling a function (getValue) that just calls a method of trend >(caller), that just calls another method of trend (Ptd or Qtd or ...). >You can skip all these steps, and just call the method yourself: the >code that calls getValue(trend, param, per) replace with >trend.(per) if you're calling getValue with a static value >for param, or getattr(trend, param)(per) if param is dynamic. You're right, it makes sense. Thanks for also pointing out the getattr function. Eric Jones wrote: >What you're describing is a case of mulitple dispatch. See http:// www.artima.com/weblogs/viewpost.jsp?thread=101605 for a short >description and (as short) example by Guido. You can probably fill >that out and adapt it to your needs. Alternatively, you could look >into the multimethods module in the Gnosis Utilities package: http:// >pypi.python.org/pypi/Gnosis_Utils/1.2.1-a Thanks Eric. I read that article on multi-methods but I can't say I really understand it. I guess I still think of decorators as the people who got the gym ready for the prom. I've tried getting up to speed on decorators but I haven't had much success. Like I mentioned previously, with Python, I still feel like a newbie. Bruno Desthuilliers wrote: >IOW, direct access to obj.__class__.__dict__ bypasses both inheritence >and per-instance overriding. Thanks for your response also Bruno. I don't understand the code you posted well enough yet to even ask a useful question. There are a number of things I haven't seen before. Now I really feel like a newbie! I'm working on it though so I may have some questions later. Thanks again for everyone's input. I really appreciate it. From gagsl-py2 at yahoo.com.ar Sun Sep 23 18:01:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 23 Sep 2007 19:01:04 -0300 Subject: Properties and Objects... References: Message-ID: En Sat, 22 Sep 2007 15:06:38 -0300, George V. Neville-Neil escribi?: > I have been trying to switch this over to using properties, which seem > at first glance to be cleaner, but which I am having a lot of problems > with. In particular I want to add a property to an object, not a > class. The field list in a class is actually relatively static but I > wind up with ugly code like: > > class ethernet(pcs.Packet): > """Ethernet""" > __layout__ = pcs.Layout() > _map = ethernet_map.map > src = pcs.StringField("src", 48) > dst = pcs.StringField("dst", 48) > type = pcs.Field("type", 16) > > def __init__(self, bytes = None, timestamp = None): > """initialize an ethernet packet""" > > src = pcs.StringField("src", 48) > dst = pcs.StringField("dst", 48) > type = pcs.Field("type", 16) > > pcs.Packet.__init__(self, [dst, src, type], bytes = bytes) > self.description = inspect.getdoc(self) You don't have to repeat the fields: pcs.Packet.__init__(self, [self.dst, self.src, self.type], bytes = bytes) does the same thing. And you can remove self.description=... and use (at the class level): description = __doc__ or: description = property(lambda self: self.__doc__) to automatically enable subclases to share the definition One could say that the field order is important so I'd finally write it as: class ethernet(pcs.Packet): """Ethernet""" __layout__ = pcs.Layout() _map = ethernet_map.map src = pcs.StringField("src", 48) dst = pcs.StringField("dst", 48) type = pcs.Field("type", 16) _fields = [dst, src, type] description = property(lambda self: self.__doc__) def __init__(self, bytes = None, timestamp = None): """initialize an ethernet packet""" pcs.Packet.__init__(self, self._fields, bytes = bytes) > and assigning the properties at class time means that it's hard to > have variations, packets with the same name but with slightly varying > field lists. This is the part I don't understand. Can't you define a new class, in case you want a different field list? Using the above class: class ethernet_modified(ethernet): """Modified ethernet class""" added_field = pcs.StringField("whatever", 16) _fields = [dst, src, type, added_field] And it doesn't even requiere an __init__ method > So, is there a way to assign a property to an object, like this: > > def __init__(.... > self.src = property() > > or something like that? I'd use different classes for different kind of objects. > And, failing that, is there a clean way to modify the class in it's > __init__() method so I don't have to call the Field objects twice, > once for the property effect and once to put into the list in the base > Packet class? I think my example above does what you want. -- Gabriel Genellina From zzbbaadd at aol.com Fri Sep 14 01:44:44 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Thu, 13 Sep 2007 22:44:44 -0700 Subject: Python 3K or Python 2.9? In-Reply-To: <13eje8gi4nt0j1e@corp.supernews.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <5ksoaoF5am8cU1@mid.individual.net> <1189701793.466307.93210@g4g2000hsf.googlegroups.com> <5ktfjqF5ctrvU2@mid.individual.net> <13eje8gi4nt0j1e@corp.supernews.com> Message-ID: <1189748684.351475.3860@o80g2000hse.googlegroups.com> > If you look at the thread "parameter list notation" from ten days or so > ago, TheFlyingDutchman has forked Python and is working on a very special > new language, PIEthun 3.01B. > I for one am looking forward to seeing all > the very special features of PIEthun. It will be named PIEthun 3000 as it comes out of Beta. But you're not alone. From the emails I have been receiving there is anticipation and excitement from Mumbai to Dusseldorf to Caracas. From luojiang2 at tom.com Thu Sep 6 05:57:31 2007 From: luojiang2 at tom.com (Ginger) Date: Thu, 6 Sep 2007 17:57:31 +0800 Subject: how to install python2.5.1 in a amd64 redhat linux? Message-ID: <002b01c7f06c$578b2720$4de1a8c0@amd.com> [gluo at oshcs12]$ make install gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -o Modules/python.o ./Modules/python.c In file included from Include/Python.h:57, from Modules/python.c:3: Include/pyport.h:734:2: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." make: *** [Modules/python.o] Error 1 Thanks and Regards, Ginger -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.rappard at gmail.com Tue Sep 11 11:49:57 2007 From: s.rappard at gmail.com (Sjoerd) Date: Tue, 11 Sep 2007 15:49:57 -0000 Subject: mod_python and pysvn Message-ID: <1189525797.361829.69380@g4g2000hsf.googlegroups.com> Hello all, I have a script that uses pySVN. It gets the latest build information. I want to create a call to that function in a PSP file but everytime I try I get an error message: ClientError: Unable to open an ra_local session to URL Unable to open repository 'file:///P:/tools/builds/repository' does anyone know how I can fix this? thanks in advance! Sjoerd From robert.kern at gmail.com Thu Sep 20 03:22:50 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 20 Sep 2007 02:22:50 -0500 Subject: distutils, extensions, and missing headers In-Reply-To: <1190268535.052437.226240@v23g2000prn.googlegroups.com> References: <1190268535.052437.226240@v23g2000prn.googlegroups.com> Message-ID: Gary Jefferson wrote: > My setup.py (with extension) seems to work great for build and > install, but for bdist_rpm, compilation of the extension fails because > some of the headers needed to build the extension aren't in the bdist > tarball. > > I've tried adding a 'depends=[]' to the Extension definition with > these header files present, but they still don't get put in the > tarball. > > What's the key to getting headers or other [non-python] files included > in a bdist? Use the "headers" keyword to setup() to list the header files you want installed. For other files, it depends on where you need them to go. If you want the data files to be inside the package, you should use the "package_data" keyword. It was introduced in Python 2.4, so if you need to support pre-2.4 Pythons, there are recipes floating around to do so more nicely. http://docs.python.org/dist/node12.html For other things (and hopefully, you can live with package data), use "data_files": http://docs.python.org/dist/node13.html -- 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 __peter__ at web.de Fri Sep 21 02:23:53 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Sep 2007 08:23:53 +0200 Subject: UTF-8 characters in doctest References: <1190202459.229197.297350@n39g2000hsh.googlegroups.com> <878x71jfwo.fsf@pobox.com> Message-ID: John J. Lee wrote: > Peter Otten <__peter__ at web.de> writes: > [...] >> # -*- coding: utf8 -*- >> r""" >>>>> f("???".decode("utf8")) >> (u'\xe4\xf6\xfc',) >> """ >> def f(s): >> return (s,) > > Forgive me if this is a stupid question, but: What purpose does > function f serve? Like the OP's get_inventary_number() it takes a unicode string and returns a tuple of unicode strings. I'ts pointless otherwise. I hoped I had stripped down his code to a point where the analogy was still recognizable. Peter From dotancohen at gmail.com Tue Sep 11 20:45:12 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 12 Sep 2007 03:45:12 +0300 Subject: wx module? Message-ID: <880dece00709111745p2f816833j8f2cdaf2113633ee@mail.gmail.com> Where can I find a wx module for Python? I'm trying to run taskcoach, but I cannot find this package. Thanks. ubuntu at ubuntu-laptop:~/Desktop/todo-manager-0.75.1/todo-manager-0.75.1$ taskcoach.py Traceback (most recent call last): File "/usr/bin/taskcoach.py", line 24, in import wx ImportError: No module named wx ubuntu at ubuntu-laptop:~/Desktop/todo-manager-0.75.1/todo-manager-0.75.1$ Dotan Cohen http://what-is-what.com http://gibberish.co.il From tokland at gmail.com Thu Sep 20 10:22:11 2007 From: tokland at gmail.com (tokland at gmail.com) Date: Thu, 20 Sep 2007 14:22:11 -0000 Subject: os.popen and lengthy operations In-Reply-To: References: Message-ID: <1190298131.265147.292350@g4g2000hsf.googlegroups.com> On 20 sep, 08:31, "Dmitry Teslenko" wrote: > I'm using os.popen to perform lengthy operation such as building some > project from source. > def execute_and_save_output( command, out_file, err_file): > (i,o,e) = os.popen3( command ) You should consider using the higher-level "subprocess" module: import subprocess def run(command, output, error, bufsize=None): popen = subprocess.Popen(command.split(), bufsize=bufsize, stdout=output, stderr=error) popen.communicate() return popen.returncode example: create = lambda path: open(path, "w") run("ls /etc/services abc", create("/tmp/output"), create("/tmp/ error")) Check how to use the "bufsize" parameter in the docs: http://docs.python.org/lib/node529.html arnau From fakeaddress at nowhere.org Sat Sep 22 15:12:31 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Sep 2007 19:12:31 GMT Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> Message-ID: Cristian wrote: > [...] Specifically, he's having trouble > thinking of functions as first order data (don't worry, I haven't > confused him with such terminology yet). [...] > And, after we finally > get a hold of first order functions, we appreciate its incorporation > into languages. It would be a shame if my friend just learns the > motions and never incorporates first order functions into his > programs. The terminology I've heard for this is that functions are "first-class values". There's a minor name-collision on "class", but people have heard "first-class" in other contexts, and it means the same thing here: no second-class status for such values. "First order" has other usages, some contradicting what you mean. First-order functions are exactly those that cannot take functions as arguments. It would be a shame if your friend never incorporates *higher order* functions. [http://en.wikipedia.org/wiki/Higher-order_function] [...] > my_function = function(foo, bar): pass > an_instance_method = function(self, foo): pass > a_method_declaration = method(self, foo): pass I just argued for adopting mainstream terminology, but here I like yours better. The keyword "lambda" sucks. All the other keywords, having been so carefully chosen to relate to their conversational usage, have mis-trained to look at this spelling-out of the name of an arbitrary symbol. Alonzo Church's calculus used the *symbol*. He just needed it to be distinct. Could as well have been the '$-calculus'. Function-as-value is not a trivial concept. I remember wrestling with it, and I've seen many others do the same. The 'lambda' keyword is so awful as to pass for deep mystery long after students have grasped first-class functions. "function" would be a much better keyword. Or follow ML and abbreviate to "fn", or choose another term that clues one in to the meaning. I'd have caught on much quicker given a a hint to read: lambda x, y: x + y as: "the function of two variables, call them x and y, that returns x + y." --Bryan From duncan.booth at invalid.invalid Tue Sep 4 03:27:54 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Sep 2007 07:27:54 GMT Subject: The reverse of encode('...', 'backslashreplace') References: Message-ID: "Tor Erik S?nvisen" wrote: > How can I transform b so that the assertion holds? I.e., how can I > reverse the backslash-replaced encoding, while retaining the str-type? > >>>> a = u'?' >>>> b = a.encode('ascii', 'backslashreplace') >>>> b > '\\xe6' >>>> assert isinstance(b, str) and b == '?' > > Traceback (most recent call last): > File "", line 1, in > assert isinstance(b, str) and b == '?' > AssertionError > The simple answer is that you cannot: the backslashreplace isn't a reversible operation. e.g. Try: >>> a = u'\\xe6?' >>> print a \xe6? >>> b = a.encode('ascii', 'backslashreplace') >>> b '\\xe6\\xe6' >>> There is no way after the encoding that you can tell which of the \xe6 sequences needs reversing and which doesn't. Perhaps the following is what you want: >>> b = a.encode('unicode_escape') >>> print b \\xe6\xe6 >>> print b.decode('unicode_escape') \xe6? >>> From gagsl-py2 at yahoo.com.ar Sat Sep 29 20:56:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Sep 2007 21:56:17 -0300 Subject: Command-line does work when scheduled References: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> <1191104269.578536.56470@g4g2000hsf.googlegroups.com> Message-ID: En Sat, 29 Sep 2007 19:17:49 -0300, Jim escribi?: > On Sep 29, 3:19 pm, "Gabriel Genellina" > wrote: >> En Sat, 29 Sep 2007 17:34:34 -0300, Jim >> escribi?: >> >> > I want to schedule a Python program that reads the command line for >> > input. However, when adding an argument to the command line Python >> > will not pick it up when using Windows scheduled tasks. >> >> > How do I get it to work? >> >> Do you write the command line when defining the task? Using double >> quotes >> around arguments with spaces? >> It works fine for me. >> > I ran the following on the Scheduled Tasks: > "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py" n > "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py n" > "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py" "n" > None of them work. > However, no problem with running from *.bat file or directly from > shortcut on my Desktop. Try prepending the Python executable: C:\Python25\Python.exe "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py" n If it works this way, maybe the .py file extension is not correctly registered. -- Gabriel Genellina From cjt22 at bath.ac.uk Wed Sep 5 04:07:45 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Wed, 05 Sep 2007 01:07:45 -0700 Subject: Printing lists in columns In-Reply-To: <46ddbb26$0$18672$426a74cc@news.free.fr> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> <1188913394.763871.218660@d55g2000hsg.googlegroups.com> <46dd69b1$0$24998$426a74cc@news.free.fr> <1188917550.261894.84010@k79g2000hse.googlegroups.com> <46ddbb26$0$18672$426a74cc@news.free.fr> Message-ID: <1188979665.052672.211110@r34g2000hsd.googlegroups.com> Thanks guys, I really appreciate it. I have never used google groups before and am so impressed with how helpful you all are. It is also lovely that none of you mock my little knowledge of Python but just want to improve it. I have another question in relation to the izip_longest function (I persume this should be within the same topic). Using this funciton, is there a way to manipulate it so that the columns can be formated tabular i.e. perhaps using something such as str(list).rjust(15) because currently the columns overlap depending on the strings lengths within each column/list of lists. i.e. my output is currently like: bo, daf, da pres, ppar, xppc magnjklep, *, dsa *, *, nbi But I want it justified, i.e: bo , daf, da pres , ppar, xppc magnjklep, *, dsa * , *, nbi I am struggling to understand how the izip_longest function works and thus don't really know how it could be manipulated to do the above. It would be much apprecited if somoene could also explain how izip_function works as I don't like adding code into my programs which I struggle to understand. Or perhaps I have to pad out the lists when storing the Strings? Any help would be much appreciated. From jgardner.jonathangardner.net at gmail.com Thu Sep 13 16:21:07 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Thu, 13 Sep 2007 20:21:07 -0000 Subject: plotting pixels in python In-Reply-To: <1189708663.253748.323460@y42g2000hsy.googlegroups.com> References: <1189706620.564963.29690@d55g2000hsg.googlegroups.com> <1189707751.846412.51420@r29g2000hsg.googlegroups.com> <1189708663.253748.323460@y42g2000hsy.googlegroups.com> Message-ID: <1189714867.580851.13230@k79g2000hse.googlegroups.com> On Sep 13, 11:37 am, jo5867... at gmail.com wrote: > No currently I am using a canvas from the Tkinter module > What I actually want is to show how a line is plotted pixel by pixel > using a delay loop. I want functions something like putpixel not > draw_line Try drawing 1px wide rectangles. From deets at nospam.web.de Wed Sep 12 05:34:21 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Sep 2007 11:34:21 +0200 Subject: Generating HTML References: Message-ID: <5kpq4tF4ugonU1@mid.uni-berlin.de> Sebastian Bassi wrote: > Hello, > > What are people using these days to generate HTML? I still use > HTMLgen, but I want to know if there are new options. I don't > want/need a web-framework a la Zope, just want to produce valid HTML > from Python. KID, Genshi, Mako. And a bazillion others. I prefer the first two ones because the force you to use valid XML and produce HTML/XHMTL out of that. Diez From neilscad at hotmail.com Sat Sep 29 02:10:22 2007 From: neilscad at hotmail.com (neil) Date: Sat, 29 Sep 2007 18:10:22 +1200 Subject: python 2.5 and 3gb switch References: Message-ID: why? I am asking if any one knows of a 3gb python build. The code runs successfully in lesser missions it just wont run in the extra memory available when I try to run it along with my other programs in a 3gb space. thanks for your reply though From carsten at uniqsys.com Fri Sep 28 16:15:03 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 28 Sep 2007 16:15:03 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191009608.985644.271160@50g2000hsm.googlegroups.com> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191005906.556751.261940@22g2000hsm.googlegroups.com> <5m51l4Fbao07U2@mid.uni-berlin.de> <1191007754.740566.137510@n39g2000hsh.googlegroups.com> <1191008702.579795.141180@r29g2000hsg.googlegroups.com> <1191009608.985644.271160@50g2000hsm.googlegroups.com> Message-ID: <1191010503.3393.52.camel@dot.uniqsys.com> On Fri, 2007-09-28 at 13:00 -0700, TheFlyingDutchman wrote: > Being in a land where every nit can be picked, I am surprised that you > offered up a mailing list when I was asking for a newsgroup. nntp://news.gmane.org/gmane.comp.python.tutor -- Carsten Haese http://informixdb.sourceforge.net From vito.detullio at gmail.com Sun Sep 16 07:16:59 2007 From: vito.detullio at gmail.com (ZeD) Date: Sun, 16 Sep 2007 11:16:59 GMT Subject: generate list of partially accumulated values References: <1189936564.932553.148800@50g2000hsm.googlegroups.com> <1189936979.276166.103080@w3g2000hsg.googlegroups.com> <1189937183.100462.175070@o80g2000hse.googlegroups.com> <1189938119.469599.171960@w3g2000hsg.googlegroups.com> Message-ID: cesco wrote: > The list is composed of objects: > l = [obj1, obj2, obj3, obj4] > and I need to call a method (say method1) on each object as follow: > l1 = [obj1.method1(obj2), obj2.method1(obj3), obj3.method1(obj4), > obj4] to me it sounds a bit different from the original request, but... > Is there a clean way of doing this? l = [obj1, obj2, obj3, obj4] l1 = [a.method1(b) for a,b in zip(l, l[1:)] + l[-1:] -- Under construction From stefan.behnel-n05pAM at web.de Wed Sep 19 04:17:11 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 19 Sep 2007 10:17:11 +0200 Subject: lxml codespeak pages empty ? In-Reply-To: References: Message-ID: <46F0DB07.5080902@web.de> Laurent Pointal wrote: > I can no longer get codespeak's lxml page at http://codespeak.net/lxml/ > (get an empty HTML document Transitional//EN">)... > > > Am-I alone in this case ? > Any codespeaker reading ? Hmm, it's working for me... Stefan From s.mientki at id.umcn.nl Wed Sep 12 03:51:02 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 12 Sep 2007 09:51:02 +0200 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> Message-ID: Mark Summerfield wrote: > I feel that Python lacks one useful data structure: an ordered > dictionary. > > I find such data structures v. useful in C++. I know that in Python > the sort function is v. fast, but often I prefer never to sort but > simply to use an ordered data structure in the first place. > (I'm aware that for ordered lists I can use the bisect module, but I > want an ordered key-value data structure.) > > I think other people must find such things useful. There are three > implementations on the Python Cookbook site, and one on PyPI, all in > pure Python (plus I have my own implementation, also pure Python). > > I would suppose that it would be better if it was implemented in C--- > for example, my own pure Python ordered dict loads data about eight > times slower than the built-in dict. Nonetheless, I still find it > worth using for the convenience it offers. > > Do other Python programmers feel this lack? Is this worth a PEP? > > Yes I think it's really useful, (or at least I'm used to it in other languages ;-) If you're going to extend the dictionary, there's one other flag I'm continuously missing: "case-insensitive" key. cheers, Stef Mientki > [I originally asked about this on the P3K mailing list, but then > realised that it isn't version-specific really.] > > From Shawn at Milochik.com Wed Sep 5 12:20:08 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Wed, 5 Sep 2007 12:20:08 -0400 Subject: REGULAR EXPRESSION In-Reply-To: <1188968632.077355.199740@y42g2000hsy.googlegroups.com> References: <1188912767.360967.306050@y42g2000hsy.googlegroups.com> <1188968632.077355.199740@y42g2000hsy.googlegroups.com> Message-ID: <2dc0c81b0709050920w59324fd6t8a77cf854d38777c@mail.gmail.com> > Hi.. Thanks alot for finding time to help a beginner like me. What I > am trying to do is validate the input i get. I just want to take > numbers and numbers only. So if the input is 23+1 or 2/3 or 9-0 or > 7/0 , I want to find it using reg exp. I know there are other ways to > do this... but i thought i will try this as i need to learn reg exp. I > tried \D+ , \W+, and \D+|\W+ .. Thanks once again... > > > -- Send a couple of strings and the output you would like from each. From van.lindberg at gmail.com Tue Sep 11 07:28:00 2007 From: van.lindberg at gmail.com (VanL) Date: Tue, 11 Sep 2007 06:28:00 -0500 Subject: [PyCON-Organizers] Next PyCon Organizers' Meeting Tuesday, 11 September In-Reply-To: <200709110557.l8B5vQbm011421@theraft.openend.se> References: <46E5CFAB.8090802@python.org> <18149.64774.138831.976974@montanaro.dyndns.org> <200709110557.l8B5vQbm011421@theraft.openend.se> Message-ID: <46E67BC0.7040104@gmail.com> Laura Creighton wrote: > Does this mean that if you do not have a google account, and do not > want one, there is no way to join the meeting? No. Any jabber/xmpp account will do fine. Google is just the highest-profile provider of jabber accounts. There is a list of other account providers on jabber.org. Alternatively, there is jabber server software (including Free Software) that you can run on a server that you control. After setting that up, you can use your own account on your own server to join the meeting. Thanks, Van From fakeaddress at nowhere.org Sat Sep 15 01:32:31 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Sep 2007 22:32:31 -0700 Subject: Coming from Perl In-Reply-To: References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <87y7fa52ru.fsf@benfinney.id.au> Message-ID: Amer Neely wrote: > This seems to indicate that maybe my host needs to configure Apache to > run python scripts? But I didn't need to do anything with mine. Another possibility: If it works on Windows but not Unix, check the end-of-line characters. Windows ends each line with the two character sequence carriage-return + newline, which in Python is "\r\n". Unix uses newline alone, "\n". Most Unixies will choke on a #! line with a carriage return. The Python interpreter will accept source files with either end-of-line on either system, but of course you'll not get that far unless the operating system respects the shebang line. Maybe you already checked that. Hmmm...other possiblities... Do you have shell access? Can you executing it directly from the shell? Do you get a Python error, or some other? Did you: chmod ugo+rx Is Python in /usr/bin? What does "which python" say? Generally, most experts seem to prefer: #!/usr/bin/env python You might try changing the the extension of your script from .py to .cgi. Windows uses the .py to choose the executable, but Unix does not care; it used the shebang line. -- --Bryan From sjmachin at lexicon.net Mon Sep 10 06:37:59 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Sep 2007 03:37:59 -0700 Subject: Modul (%) in python not like in C? In-Reply-To: References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> <46E4466C.2030303@sdf.lonestar.org> <1189377800.482587.143060@22g2000hsm.googlegroups.com> Message-ID: <1189420679.118421.18420@r34g2000hsd.googlegroups.com> On Sep 10, 9:16 am, Ricardo Ar?oz wrote: > John Machin wrote: > > On Sep 10, 8:05 am, Lee Harr wrote: > >>>> Python will always yield a number x = m%n such that 0 <= x < n, but > >>>> Turbo C will always yield a number such that if x = m%n -x = -m%n. That > >>>> is, since 111 % 10 = 1, -111 % 10 = -1. The two values will always > >>>> differ by n (as used above). > >> Maybe it is an order-of-operations thing.... > > >> -111 % 10 = -1 > >> (-111) % 10 = 9 > >> ? > > > and on the other hand, maybe it's not. Try to think of any language > > where unary minus binds so loosely. > > Why the theoretical argument when you can TEST your assumptions? > > >>> -111 % 10 > 9 > >>> (-111) % 10 > > 9 I was *assuming* nothing; I *know* what is the relative precedence of % and unary minus in both C and Python. I was not arguing; I was inviting Lee (as I now invite you) to think before writing. From mcl.office at googlemail.com Fri Sep 7 04:21:40 2007 From: mcl.office at googlemail.com (mcl) Date: Fri, 07 Sep 2007 01:21:40 -0700 Subject: MySQL: Global Connection Message-ID: <1189153300.967875.204820@y42g2000hsy.googlegroups.com> It is tough when the grey matter is getting past it. I am starting to use MySQL and I would like to make my connection to my database a variable in my Global Variable Class, but I just can not see how to do it. Class GlobalVars : From mail at microcorp.co.za Sat Sep 1 04:34:08 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 1 Sep 2007 10:34:08 +0200 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com><-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com><1188364909.397692.209170@q4g2000prc.googlegroups.com><1188367108.393207.241970@g4g2000hsf.googlegroups.com><1188369928.755777.142690@i38g2000prf.googlegroups.com><46d75191$0$401$426a74cc@news.free.fr><1188518054.298017.90610@x35g2000prf.googlegroups.com><46d76595$0$4013$426a74cc@news.free.fr><1188523589.736146.263510@l22g2000prc.googlegroups.com><1i3o9kr.2gmni61g62moaN%aleax@mac.com><7xwsvcc9yz.fsf@ruckus.brouhaha.com><1i3p8lm.19738kn1q0gkouN%aleax@mac.com><1188587846.687895.69240@q5g2000prf.googlegroups.com><38rmq4-cq.ln1@strongwill.g2ctech> <46d903db$0$19580$4c368faf@roadrunner.com> Message-ID: <026201c7ec75$07d6e0c0$03000080@hendrik> "Carl Banks" wrote: > This is starting to sound silly, people. Critical is a relative term, > and one project's critical may be anothers mundane. Sure a flaw in your > flagship product is a critical problem *for your company*, but are you > really trying to say that the criticalness of a bad web search is even > comparable to the most important systems on airplanes, nuclear reactors, > dams, and so on? Come on. This really intrigues me - how do you program a dam? - and why is it critical? Most dams just hold water back. Dam design software - well yes that I would agree is critical. Is that what you mean? - Hendrik From arnodel at googlemail.com Sat Sep 1 10:08:37 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 01 Sep 2007 07:08:37 -0700 Subject: Is there a simple way to exit a while loop on keystroke? In-Reply-To: <1188595723.878736.186900@w3g2000hsg.googlegroups.com> References: <1188578827.809840.90100@r29g2000hsg.googlegroups.com> <1188581623.588967.78050@z24g2000prh.googlegroups.com> <1188583918.747640.300850@22g2000hsm.googlegroups.com> <1188593722.696576.12390@y42g2000hsy.googlegroups.com> <1188595723.878736.186900@w3g2000hsg.googlegroups.com> Message-ID: <1188655717.047492.57860@50g2000hsm.googlegroups.com> On Aug 31, 10:28 pm, kyoso... at gmail.com wrote: > On Aug 31, 3:55 pm, Arnaud Delobelle wrote: > > > On Aug 31, 7:11 pm, gsxg wrote: > > > > Thanks, > > > The curses library doesn't look to helpful to me. > > > And yet it is. > > > -- > > Arnaud > > Maybe the OP is on Windows. The docs seem to indicate that the curses > module isn't for Windows (see excerpt below): Ah yes, Windows! I didn't think about it. Yes, I reckon it's unlikely that curses is implemented for MS Windows. [...] -- Arnaud From gagsl-py2 at yahoo.com.ar Tue Sep 25 00:23:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Sep 2007 01:23:30 -0300 Subject: Regular Expressions: Can't quite figure this problem out References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> <496954360709241917m3801e4aavee29cfef7deaf41b@mail.gmail.com> <496954360709241951h6901d60etf2c4b3b5ec759f2a@mail.gmail.com> Message-ID: En Mon, 24 Sep 2007 23:51:57 -0300, Robert Dailey escribi?: > What I meant was that it's not an option because I'm trying to learn > regular > expressions. RE is just as built in as anything else. Ok, let's analyze what you want. You have for instance this text: "" which should become "" You have to match: (opening angle bracket)(any word)(closing angle bracket)(opening angle bracket)(slash)(same word as before)(closing angle bracket) This translates rather directly into this regular expression: r"<(\w+)>" where \w+ means "one or more alphanumeric characters or _", and being surrounded in () creates a group (group number one), which is back-referenced as \1 to express "same word as before" The matched text should be replaced by (opening <)(the word found)(slash)(closing >), that is: r"<\1/>" Using the sub function in module re: py> import re py> source = """ ... ... ... ... ... """ py> print re.sub(r"<(\w+)>", r"<\1/>", source) Now, a more complex example, involving tags with attributes: --> You have to match: (opening angle bracket)(any word)(any sequence of words,spaces,other symbols,but NOT a closing angle bracket)(closing angle bracket)(opening angle bracket)(slash)(same word as before)(closing angle bracket) r"<(\w+)([^>]*)>" [^>] means "anything but a >", the * means "may occur many times, maybe zero", and it's enclosed in () to create group 2. py> source = """ ... ... ... """ py> print re.sub(r"<(\w+)([^>]*)>", r"<\1\2 />", source) Next step would be to allow whitespace wherever it is legal to appear - left as an exercise to the reader. Hint: use \s* -- Gabriel Genellina From istvan.albert at gmail.com Wed Sep 26 10:28:09 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Wed, 26 Sep 2007 14:28:09 -0000 Subject: Tracking memory usage and object life time. In-Reply-To: <1190808386.571152.103710@22g2000hsm.googlegroups.com> References: <1190808386.571152.103710@22g2000hsm.googlegroups.com> Message-ID: <1190816889.237615.252450@19g2000hsx.googlegroups.com> On Sep 26, 8:06 am, Berteun Damman wrote: > that have been created after I don't need them anymore. I furthermore > don't really see why there would be references to these larger objects > left. (I can be mistaken of course). This could be tricky because you have a graph that (probably) allows you to walk its nodes, thus even having a single other reference to any of the nodes could keep the entire graph "alive" > The best I now can do is run the whole script several times (from a > shell script) -- but this also forces Python to reparse the graph > input again, and do some other stuff it only has to do once. A you could pickle and save the graph once the initial processing is done. That way subsequent runs will load substantially faster. i. From korovev76 at gmail.com Thu Sep 20 08:39:07 2007 From: korovev76 at gmail.com (korovev76 at gmail.com) Date: Thu, 20 Sep 2007 05:39:07 -0700 Subject: I MEANT ONIX.... [it was Re: ONYX] In-Reply-To: <5lf7dsF7vn3qU1@mid.uni-berlin.de> References: <1190211769.268351.79500@d55g2000hsg.googlegroups.com> <46f1726f$0$15276$426a74cc@news.free.fr> <1190282489.824709.29050@r29g2000hsg.googlegroups.com> <1190283378.175422.73290@r29g2000hsg.googlegroups.com> <5lf7dsF7vn3qU1@mid.uni-berlin.de> Message-ID: <1190291947.945038.54040@57g2000hsv.googlegroups.com> On 20 Set, 14:29, "Diez B. Roggisch" wrote: > > lxml is a validating parser for python. > > Diez thank u, i'll take a look From joel.schaerer at gmail.com Wed Sep 26 06:21:55 2007 From: joel.schaerer at gmail.com (Joel) Date: Wed, 26 Sep 2007 03:21:55 -0700 Subject: Cross-platform time out decorator Message-ID: <1190802115.585306.250400@o80g2000hse.googlegroups.com> I've been using this nice timing out decorator : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871 . The problem is that since it relies on sigalarm, it doesn't work under windows. Would anyone know how to do a cross-platform version? Thanks a lot! joel From rave247 at seznam.cz Thu Sep 6 14:47:02 2007 From: rave247 at seznam.cz (=?us-ascii?Q?rave247=20rave247?=) Date: Thu, 06 Sep 2007 20:47:02 +0200 (CEST) Subject: =?us-ascii?Q?Re=3A=20Getting=20original=20working=20directory?= In-Reply-To: Message-ID: <1658.1882-17889-1055570935-1189104422@seznam.cz> If I could use os.getcwd() or save the value to some variable before calling os.chdir() I would do it, believe me. However I can't because it is the part of code where I can't do any changes. Also I do not agree that such thing is not possible because after python script finishes its work, it naturally gets back into the original location from where you started the script (in shell you are in the original location after script finishes). So this information has to be stored somewhere (probably in shell which runs the interpreter) and there *must* be a way how to get it. Simply after calling os.chdir() the original value doen't disappear, I think it just needs some nice hack if python doesn't provide a way how to get it. > ------------ P?vodn? zpr?va ------------ > Od: Ian Clark > P?edm?t: Re: Getting original working directory > Datum: 06.9.2007 20:31:33 > ---------------------------------------- > rave247 rave247 wrote: > > "......the *original* directory location *after* os.chdir() is > performed......" os.getcwd() is not helping much as it returns the location that > was set up in os.chdir() call > > > > Thanks > > Your question is akin to having a name X that is bound to some value, > setting it to 2 and then wanting to know what the original value is. It > just ain't gonna happen. > > Simply follow the advice given by Gary and use os.getcwd() *before* the > call to os.chdir(). > > Ian > > -- > http://mail.python.org/mailman/listinfo/python-list > > > From jeremy+complangpython at jeremysanders.net Wed Sep 26 11:21:19 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Wed, 26 Sep 2007 16:21:19 +0100 Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> <1190799759.367001.106400@r29g2000hsg.googlegroups.com> <87fy11lo22.fsf@mulj.homelinux.net> <1190804538.469582.96950@22g2000hsm.googlegroups.com> <1190814263.104358.158090@n39g2000hsh.googlegroups.com> Message-ID: Mark Summerfield wrote: > The sorteddict API that has emerged so far is (1) apart from the > constructor, everything is identical to dict, (2) the constructor > takes the same args as sorted(), so if you want to seed with a dict or > with keywords you write sorteddict(dict(a=1,b=2), ...), (or you could > create a sorteddict and use update() since that takes the same args as > dict's constructor). first() and last() would also be nice on a sorted dict. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From george.sakkis at gmail.com Sat Sep 29 18:53:07 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 29 Sep 2007 22:53:07 -0000 Subject: Program inefficiency? In-Reply-To: <1191090727.614819.292550@50g2000hsm.googlegroups.com> References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> <1191087234.915654.182370@k79g2000hse.googlegroups.com> <1191090293.017485.225470@y42g2000hsy.googlegroups.com> <1191090727.614819.292550@50g2000hsm.googlegroups.com> Message-ID: <1191106387.602341.295460@d55g2000hsg.googlegroups.com> On Sep 29, 2:32 pm, hall.j... at gmail.com wrote: > It think he's saying it should look like this: > > (line noise snipped) Or you can let BeautifulSoup do the dirty job for you and forget all this ugliness: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(text) for a in soup.findAll('a'): for attr in 'href','name': val = a.get(attr) if val: a[attr] = val.replace(' ','_') print soup George From matt at tplus1.com Wed Sep 26 22:01:17 2007 From: matt at tplus1.com (Matthew Wilson) Date: Thu, 27 Sep 2007 02:01:17 GMT Subject: Using closures and partial functions to eliminate redundant code Message-ID: I wrote some code to create a user and update a user on a remote box by sending emails to that remote box. When I was done, I realized that my create_user function and my update_user function were effectively identical except for different docstrings and a single different value inside: ### VERSION ONE def create_user(username, userpassword, useremail): "Send an email that will create a user in the remote system." # Build email email_body = """ USERNAME = %s USERPASSWORD = %s USEREMAIL = %s """ % (username, userpassword, useremail) # send it. send_email(subject="CREATE", body=email_body) def update_user(username, userpassword, useremail): "Send an email that will update a user's password in the remote system." # Build email email_body = """ USERNAME = %s USERPASSWORD = %s USEREMAIL = %s """ % (username, userpassword, useremail) # send it. send_email(subject="UPDATE", body=email_body) ### END Then I came up with this approach to avoid all that redundant text: ### VERSION TWO def _f(mode): if mode not in ("create", "update"): raise ValueError("mode must be create or update!") def _g(username, userpassword, useremail): # Build email email_body = """ USERNAME = %s USERPASSWORD = %s USEREMAIL = %s """ % (username, userpassword, useremail) # send it. send_email(subject=mode.upper(), body=email_body) # Seems goofy, but other ways are there? docstrings = {'create': "Send an email that will create a user in the remote system.", 'update': "Send an email that will update a user's password in the remote system."} _g.__doc__ = docstrings[mode] return _g # Then I created my functions like this: v2_create_user = _f("create") v2_update_user = _f("update") ### END Finally, I came up with this approach: ### VERSION THREE from functools import partial def _h(mode, username, userpassword, useremail): if mode not in ("create", "update"): raise ValueError("mode must be create or update!") # Build email email_body = """ USERNAME = %s USERPASSWORD = %s USEREMAIL = %s """ % (username, userpassword, useremail) # send it. send_email(subject=mode.upper(), body=email_body) # I can't figure out how to set up the docstring on these. v3_create_user = partial(_h, mode="create") v3_update_user = partial(_h, mode="update") ### END I'm interested to hear how other people deal with really similar code. The similarity just bugs me. However, I wonder if using stuff like closures or partial function application is needlessly showy. Also, I hope anyone here can help me figure out how to attach a meaningful docstring for my version three code. Thanks in advance! Matt From wizzardx at gmail.com Thu Sep 20 17:34:52 2007 From: wizzardx at gmail.com (David) Date: Thu, 20 Sep 2007 23:34:52 +0200 Subject: validating parser In-Reply-To: References: Message-ID: <18c1e6480709201434q44ee08fkfd6ae04f8a1eca13@mail.gmail.com> On 9/20/07, Robert Schweikert wrote: > Is there a Python module which will do XSD validation? http://mail.python.org/pipermail/xml-sig/2006-June/011527.html From tim at timgolden.me.uk Thu Sep 6 15:39:26 2007 From: tim at timgolden.me.uk (Tim Golden) Date: Thu, 06 Sep 2007 20:39:26 +0100 Subject: Finding specific date ranges In-Reply-To: <1189101946.318748.99670@y42g2000hsy.googlegroups.com> References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> <1189099759.833051.253020@y42g2000hsy.googlegroups.com> <1189101946.318748.99670@y42g2000hsy.googlegroups.com> Message-ID: <46E0576E.7010105@timgolden.me.uk> kyosohma at gmail.com wrote: > On Sep 6, 12:41 pm, Tim Golden wrote: >>> Thanks! I'll try it both ways and see if there's any appreciable >>> difference in speed, although since it will be packaged into an >>> executable, that may not be an issue anyway. >>> Mike >> I honestly doubt there's any advantage to my approach, certainly >> not in terms of speed. It's really only if it happens to suit >> your mind better, or take advantage of structures you might >> already have in place, etc. >> >> TJG > > For completeness, here's my method for comparison's sake: > [... snipped ...] > Isn't it kind of late in the day over there, Tim? (It's about 8.30pm as I write this, so still awake :) > Anyway, your method is probably clearer to read whereas mine > doesn't require anything to be imported. I think I've been a SQL & Python programmer for so long that I tend to do anything -- and sometimes too much -- to avoid messy loop/exit-when structures. On reflection, my code would be simplified by ignoring all the datetime.date stuff which is irrelevant for the purpose, since tuples will compare perfectly well. Also, I had to put the conditional in the loop because I didn't have data for every month. If you *knew* you had at least one period for each month and weren't fussed about, say, date arithmetic later on, it would be even simpler, just a min () function around a generator expression. Frankly, though, with code as small scale as this, it's far more important what *you* the programmer and any future maintainers will find easy to understand and use, and far less important how clever the code is or how fast it runs. > I didn't even realize there was a calendar module...or > maybe I forgot about it. Even now, after some seven years of using Python, I'm *still* surprised when I read someone's blog article or mailing list posting referring to a module or application I never knew about, or had completely forgotten. TJG From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 24 07:16:24 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 24 Sep 2007 13:16:24 +0200 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> Message-ID: <46f79c75$0$30457$426a34cc@news.free.fr> Matthew Woodcraft a ?crit : > Cristian wrote: >> To me, the biggest setback for new programmers is the different >> syntax Python has for creating functions. Instead of the common (and >> easy to grasp) syntax of foo = bar Python has the def foo(): syntax. > > [...] > >> in a program like Python there doesn't seem to be any other reason to >> have it. > > One reason for the different syntax is that functions, unlike most > other objects, know their own names (which can be shown in tracebacks > and the like). Nope. They know *one* of their names - the one they've been given when first instanciated. Which may or not be the name used to get at them... From dickinsm at gmail.com Sun Sep 30 19:05:06 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 30 Sep 2007 23:05:06 -0000 Subject: Matrix convergence In-Reply-To: <1191179438.736054.322700@o80g2000hse.googlegroups.com> References: <1191179438.736054.322700@o80g2000hse.googlegroups.com> Message-ID: <1191193506.647796.255680@y42g2000hsy.googlegroups.com> On Sep 30, 3:10 pm, Zhengzheng Pan wrote: > I'm trying to check whether a (stochastic/transition) matrix > converges, i.e. a function/method that will return True if the input > matrix sequence shows convergence and False otherwise. The background > is a Markov progress, so the special thing about the transition matrix > is the values of elements in each row add up to be 1. Fail to find any > relevant build-in methods in Python... I'm not sure exactly what you want here. Do you have a single transition matrix, or a `matrix sequence'? Can I assume that you're working with a time-homogeneous Markov chain with a finite state space? And that the function should take the transition matrix, and should return True if and only if there's a unique limiting distribution for the Markov process, independent of starting state? Or have I misunderstood? What's the typical number of states? Thousands? Millions? Can you explain why you're unable to implement detection of periodicity and connectivity (is this the same as irreducibility)? Are there technical problems, or just conceptual problems? Detecting irreducibility ought to be straightforward: form the directed graph corresponding to the transition matrix (one vertex per state, an edge from i to j iff the corresponding entry in the transition matrix is nonzero) and apply Tarjan's algorithm (google it!), which detects strongly connected components: if there's a single strongly connected component consisting of the entire graph then the Markov process is irreducible. Figuring out the period shouldn't be too hard either---I have a feeling that it ought to be possible to adapt Tarjan's algorithm to detect the period: label the vertices of the graph by depth (Tarjan's algorithm is essentially a depth-first traversal of the graph), and every time Tarjan's algorithm detects a cycle, comparing depths will give you a multiple of the period; taking the gcd of all these multiples should give the period itself. An alternative, quick and dirty way (quick for the human, not the computer!) would be just to compute some large power of the transition matrix and eyeball it to see if all columns are identical. If so, the process converges. > Thx! Ur wlcm! Mark From nospam at nowhere.com Sun Sep 30 01:43:44 2007 From: nospam at nowhere.com (DavidM) Date: 30 Sep 2007 17:43:44 +1200 Subject: New to python References: <1191126010.260942.89230@y42g2000hsy.googlegroups.com> Message-ID: <46ff2980@news.orcon.net.nz> On Sat, 29 Sep 2007 21:20:10 -0700, Googy wrote: > I am new to python... > > The programming language i know well is C > Can any one recommend me the good ebook for beginners. I have loads of > ebooks but i am not able to decide which to start with which book. > Also i am learning XML so later on i can switch to books on Python and > XML but initially which book to read?? > > Please help... Some years ago I crossed over from C to Python myself. I found Python weird and incomprehensible at first, especially since I was effectively having to learn OO at the same time. I worked through the standard Python tutorial that comes with the Python manual, and kept an interactive Python interpreter session running in a terminal. It was tough for a while, but before long, something just seemed to 'click' and I 'got it'. There were still many things to learn - I'm still learning - but what has helped heaps has been the #python IRC channel on irc.freenode.net. Keep at it - it'll gel for you if you persist, and you're willing to do lots of experimenting. From gagsl-py2 at yahoo.com.ar Fri Sep 7 20:57:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Sep 2007 21:57:34 -0300 Subject: application version checking against database References: <1189165916.268515.10360@d55g2000hsg.googlegroups.com> <588D53831C701746A2DF46E365C018CE01D2CB32@LITEXETSP001.etrsouth.corp.entergy.com> Message-ID: En Fri, 07 Sep 2007 10:12:09 -0300, Hamilton, William escribi?: >> We are trying to implement a system that checks the version of the >> application against a version number stored in the database. We don't >> want the app and the db don't become out of sync. >> >> We have tried setting a __version__ variable in the top most module, >> however, it seems that this is not accessible for the modules that are >> subsequently imported. There are a several locations in the app where >> we want to do the version check, but we would like to have one place >> to set the version number, namely the top level module. > > You could add a Version module that contains the version number and any > functions related to the version checking, and import that into the > modules that do version checking. Also, there is a version module already available from the standard library: from distutils.version import StrictVersion __version__ = StrictVersion("1.3") __version__ = '$Revision: 1.19 $'[11:-2] The last line is for CVS. -- Gabriel Genellina From deets at nospam.web.de Thu Sep 13 03:39:14 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Sep 2007 09:39:14 +0200 Subject: Implementing a fixed size stack for an RPN Calculator In-Reply-To: <1189660374.063395.71360@50g2000hsm.googlegroups.com> References: <1189630522.152326.3040@d55g2000hsg.googlegroups.com> <5kr5hoF4s6gmU3@mid.uni-berlin.de> <1189660374.063395.71360@50g2000hsm.googlegroups.com> Message-ID: <5ks7pmF58ijvU1@mid.uni-berlin.de> rami.mawas at gmail.com schrieb: > On Sep 12, 2:55 pm, Marc 'BlackJack' Rintsch wrote: >> On Wed, 12 Sep 2007 20:55:22 +0000, rami.ma... at gmail.com wrote: >>> I have implemented an RPN calculator in python but now I would like to >>> make the stack size fixed. how can I transform the user's RPN >>> expression from a stack overflow to a computable expression. >>> For instance, if my stack size is 2 then the some expression can't be >>> computed but could be transformed as following: >>> Non computable expression: 1 2 3 + + --> stack size of 3 is needed >>> Computable expression: 1 2 + 3 + --> stack size of 2 is needed >>> How can I define a formal way of transforming the non computable >>> expression to computable one. >>> My RPN only implements: + - x % >> Why does this homework assignment limit the stack so severely!? ;-) >> >> Ciao, >> Marc 'BlackJack' Rintsch > > > The problem is not with the stack being severely small or not, it > could be 1000 but it should be fixed and that's the limitation. It can't be fixed. You can algebraic rewrite expressions of the form (a + (b + (c + d)) because of the commutativity of the +-operation to (a+b) + (c + d) and this can be done automatically. But for arbitrary expressions, you will _always_ need arbitrary stack-sizes. Diez From steve at REMOVE-THIS-cybersource.com.au Thu Sep 6 02:25:54 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Sep 2007 06:25:54 -0000 Subject: Any syntactic cleanup likely for Py3? And what about doc standards? References: <46DEFD2E.5050205@sbcglobal.net> <87tzq898e2.fsf@wilson.homeunix.com> <87ejhc8z23.fsf@wilson.homeunix.com> Message-ID: <13dv7biiu70252d@corp.supernews.com> On Thu, 06 Sep 2007 03:31:43 +0000, Alan Isaac wrote: >> Their only flaw is that they are not >> "virtual" (in C++ speak). In other words, you can't pass a "self" >> parameter to them. > > http://www.kylev.com/2004/10/13/fun-with-python-properties/ I'm not 100% sure I get what problem that piece of code is supposed to solve, but if I have understood it, the obvious solution is to use inheritance, not nasty tricks with lambdas. class Base(object): _foo = None def getFoo(self): return self._foo def setFoo(self, val): self._foo = val foo = property(getFoo, setFoo) class Derived(Base): # like Base, but the default for foo is 0 not None _foo = 0 (Naturally the above is a toy example -- for something as simple as that, there is no benefit in using properties.) The blogger who wrote it says "I was pretty impressed with myself for figuring this out. So I?m putting it on my site to pat myself on the back." Hmmm. Unless I've missed something, the solution on the web-page falls squarely in the too-clever-by-half bucket and nothing to be self- congratulatory about. -- Steven. From kw at codebykevin.com Thu Sep 20 13:54:59 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 20 Sep 2007 13:54:59 -0400 Subject: Internationalize a Tkinter application Message-ID: <67a81$46f2b3f7$4275d90a$11857@FUSE.NET> I'm investigating the possibility of internationalizing a Tkinter application that I develop. Tcl/Tk provides facilities for internationalizing applications via its msgcat package, documented in "how-to" fashion below: http://www.tcl.tk/doc/howto/i18n.html As far as I can tell, Tkinter does not wrap the msgcat library. Instead I've found the gettext module in the Python standard library. Is this the preferred package for implementing localized strings in a Tkinter application, or am I missing something? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From ilikecandy7 at gmail.com Tue Sep 4 10:43:52 2007 From: ilikecandy7 at gmail.com (frenchy64) Date: Tue, 04 Sep 2007 14:43:52 -0000 Subject: Parse or Pass? Message-ID: <1188917032.271543.236420@d55g2000hsg.googlegroups.com> I'm very confused...I want to describe passing variables to functions and I've seen these two words used in very similar contexts. Is there a difference between them? From rcdailey at gmail.com Mon Sep 24 21:53:57 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 24 Sep 2007 20:53:57 -0500 Subject: Regular Expressions: Can't quite figure this problem out In-Reply-To: References: <496954360709241737o6e42e7efk29886b5631f6ca2e@mail.gmail.com> Message-ID: <496954360709241853w6bb6e813ved0ec4fc80304d51@mail.gmail.com> Thanks. Any easier way to do a 'replace' then using start(), end(), and slicing operations? I'm currently doing it manually. On 9/24/07, Miles wrote: > > On 9/24/07, Robert Dailey wrote: > > Hi, > > > > I'm attempting to create a regular expression that removes redundancy in > > empty XML elements. For example: > > > > > > > > The regular expression would convert the XML above into: > > > > > > If you can guarantee that the XML is well-formed, then this should work: > > pattern = r'<([^/>][^>]*(?]+>' > replace = r'<\1/>' > > -Miles > -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Tue Sep 25 13:52:57 2007 From: http (Paul Rubin) Date: 25 Sep 2007 10:52:57 -0700 Subject: Clustering text-documents in bundles References: <1190733093.110073.101460@k79g2000hse.googlegroups.com> Message-ID: <7xir5y7hty.fsf@ruckus.brouhaha.com> "exhuma.twn" writes: > Is it possible to calculate a distance between two chunks of text? I > suppose one could simply do a simple word-count on the chunks > (removing common noise words of course). And then go from there. Maybe > even assigning different weighting to words. But maybe there is a well- > tested and useful algorithm already available? There's a huge field of text mining that attempts to do things like this. http://en.wikipedia.org/wiki/Latent_semantic_analysis for some info about one approach. Manning & Schutz's book "Foundations of Statistical Natural Language Processing" (http://nlp.stanford.edu/fsnlp/) is a standard reference about text processing. They also have a new one about information retrieval (downloadable as a pdf) that looks very good: . From hniksic at xemacs.org Thu Sep 27 17:38:49 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 27 Sep 2007 23:38:49 +0200 Subject: Cross-platform time out decorator References: <1190802115.585306.250400@o80g2000hse.googlegroups.com> <1190899882.702911.44670@w3g2000hsg.googlegroups.com> <87k5qc18gf.fsf@mulj.homelinux.net> <1190907553.425261.273400@w3g2000hsg.googlegroups.com> <87ejgjnarq.fsf@mulj.homelinux.net> Message-ID: <87abr7n5zq.fsf@mulj.homelinux.net> "Chris Mellon" writes: > You can use ctypes and the Python API to raise a Python exception in > the thread. How, by changing the thread's exception state? From furkankuru at gmail.com Mon Sep 17 13:39:34 2007 From: furkankuru at gmail.com (Furkan Kuru) Date: Mon, 17 Sep 2007 20:39:34 +0300 Subject: Using python to create windows apps that everyone can use? In-Reply-To: <000001c7f94c$8a280de0$0202fea9@upstairs> References: <000001c7f94c$8a280de0$0202fea9@upstairs> Message-ID: <3a4a8f930709171039u574fc0b9m65d68d825f9cbb87@mail.gmail.com> have a look at wxpython and py2exe. On 9/17/07, Tom Harding wrote: > > Hi guys, sorry to post another topic on this, as I am aware that it has > already been posted a few times, but not with specifically what I am looking > for. I want an app that makes a gui interface for python (similar to > Microsoft visual studio or qt designer, not a code based one) and/or an app > that can make this into a .exe that can be opened by any person on any > computer without python installed. > > > > I would just love to do this in python and not C++, its so simple and > logical. > > > > So basically, the easiest way to do that, please! > > > > Thanks, > > > > Tom Harding > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From croozeus at gmail.com Tue Sep 25 10:47:42 2007 From: croozeus at gmail.com (croozeus at gmail.com) Date: Tue, 25 Sep 2007 14:47:42 -0000 Subject: PyS60 Message-ID: <1190731662.584011.105500@o80g2000hse.googlegroups.com> Does anybody in the group develop applications for symbian OS using Python for Series 60? I am interested in developing such applications.. Also i have the following site for the newbies to PyS60. Regards, Pankaj Nathani Pys60 1.4.0 on Nokia 6680 4.04 2nd Edition FP2,Pys60 1.4.0 on Nokia 7610 2nd Edition View my P60 at http://croozeus.googlepages.com/py60 Py60 Resources http://sourceforge.net/projects/pys60 _____________________________ From steve at holdenweb.com Thu Sep 6 07:36:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Sep 2007 04:36:41 -0700 Subject: How to do python and RESTful In-Reply-To: <1189022079.403495.175800@g4g2000hsf.googlegroups.com> References: <1189022079.403495.175800@g4g2000hsf.googlegroups.com> Message-ID: MarkyMarc wrote: > Hi all, > > I want to make a web service application in python and keywords are > RESTful, python and nice urls(urls mapped to python objects). > > I don't want a big framework but a nice small one, that can just do > the things I want. > Translation: I am only interested in a solution that has anticipated my needs almost exactly. [?] > I have be looking at quixote, but is this uptodate? "plain" > mod_python, can this make url to http put,get,delete and post? > Would you care to explain why quixote needs to be "uptodate"? Surely it either does what you want or it doesn't? If it dies, then it hardly matters how "up to date" it is. Are you also concerned that some parts of Python remains unchanged since before 1.5.2, now almost tne years old? > Can some one here point me some where I can read about python and > RESTful or have some experiences with other? > > Any help is apricieted. > I hope you don't regard this as being unhelpful. I would encourage you to focus on finding a system that meets your (functionality) requirements. If you want "up to date" then C# is that way ---> ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From hniksic at xemacs.org Wed Sep 26 08:42:30 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 26 Sep 2007 14:42:30 +0200 Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> <1190805819.406334.24730@k79g2000hse.googlegroups.com> Message-ID: <87bqbplhs9.fsf@mulj.homelinux.net> Paul Hankin writes: >> An implementation of sorted dict using a balanced tree as the >> underlying data structure would give decent performance in all the >> mentioned use cases. For example, red-black trees search, insert, >> and delete in O(log n) time. > > But dicts do search, insert and delete in O(1) time, so using some > variety of balanced tree will give you much worse performance when > you're doing regular dict operations. I wouldn't call it "much worse"; while O(log(n)) is worse than O(1), it's still very fast, which is why popular programming language libraries have an ordered mapping type based on balanced trees. Also note that dict performance can degrade with hash collisions, while trees can maintain complexity guarantees on all operations. In the end, it's a tradeoff. Hash tables offer O(1) access, but lack ordering. Balanced trees offer ordering at the price of O(log n) access. Both have their uses, but neither is syntactic sugar for the other. From paddy3118 at googlemail.com Wed Sep 19 04:37:21 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 19 Sep 2007 08:37:21 -0000 Subject: Using pseudonyms In-Reply-To: <1i4nmjz.z9983sibdq42N%aleax@mac.com> References: <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> <46e97917$0$9014$426a74cc@news.free.fr> <1190013177.473529.167770@o80g2000hse.googlegroups.com> <46ee2d9d$0$26213$426a74cc@news.free.fr> <46ef893c$0$21882$426a34cc@news.free.fr> <1i4nmjz.z9983sibdq42N%aleax@mac.com> Message-ID: <1190191041.582109.113930@19g2000hsx.googlegroups.com> On Sep 19, 5:07 am, al... at mac.com (Alex Martelli) wrote: > Aahz wrote: > > For that matter, there are plenty of people who are better known by some > > nickname that is not their legal name. > > Yep. For example, some people whose legal name is "Alessandro" (which > no American is ever going to be able to spell right -- ONE L, TWO S's, > NOT an X or a J instead, "DRO" ending rather than "DER", etc), might > choose to avoid the hassle and go by "Alex" (just to make up a case...). > > Alex ... and someone whose nickname is Paddy which is very common, and who finds it hard to remember birthdates decides to add the days in the month that his first two children were born on to his used name and now only gets worried near his partners birthday :-) - Paddy. From cjt22 at bath.ac.uk Wed Sep 5 04:38:41 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Wed, 05 Sep 2007 01:38:41 -0700 Subject: Accessing Module variables from another Module Message-ID: <1188981521.735630.133060@r29g2000hsg.googlegroups.com> Hi I am new to Python (I have come from a large background of Java) and wondered if someone could explain to me how I can access variables stored in my main module to other functions within other modules called from this module for example file: main.py from Storage import store from Initialise import init from ProcessSteps import process storeList = store() #Creates a object to store Step objects init() process() file: Initialise.py def init() ...... storeList.addStep([a,b,c]) file: ProcessSteps.py def process() for step in storeList.stepList: etc I am currently just passing the variable in as a parameter but I thought with Python there would be a way to gain direct access to storeList within the modules called from the top main module? Cheers Chris From bdesth.quelquechose at free.quelquepart.fr Sun Sep 16 15:21:05 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 16 Sep 2007 21:21:05 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> Message-ID: <46ed8251$0$31567$426a74cc@news.free.fr> Erik Jones a ?crit : > On Sep 14, 2007, at 11:54 PM, David Trudgett wrote: > >> TheFlyingDutchman writes: >> (snip) >> >> Several languages use the "object.method(args)" form, which is syntactic >> sugar for "method(object, other_args)" which Ada, for instance, uses. >> Knowing this clears up half the confusion (the object /is/ passed as a >> parameter whichever syntax is used). >> >> The other half of the confusion is cleared up by considering that >> Python methods are ordinary functions that don't magically "know" in >> which "class" context they are executing: they must be told via the >> first parameter. > > > Yes, that is really the crux of the issue, though. While the former > may be syntactic sugar for the latter, once any syntactic sugar has > become prevalent enough, it becomes the expected norm Being "the expected norm" is not enough to qualify has "being the right thing to do". > and the latter > becomes clutter or, at best, awkward. Until you want to dynamically add some generic function taking an object as first arg as a method of a class or instance. Exposing most of the inner working of it's object model is one of the greatest strength of Python. And that's one of the reasons I (and probably other people here) like this language. > It's something that really just > takes a little use until you get to the point where you don't usually > think of it but, every so often, the thought creeps in. I'm not > complaining, just pointing out if you step out of this particular box, > you'll realize that it really is a pointless one. Saying, "because > that's how Python does it" may be the only valid reason, but that > argument is about on par with a six year old's "just because...". If you really think the only rationale for this is "just because", then you're missing something IMHO. From ldo at geek-central.gen.new_zealand Mon Sep 10 04:19:08 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 10 Sep 2007 20:19:08 +1200 Subject: Python syntax wart References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> <5ki2sdF3nr68U1@mid.individual.net> <5kk8p0F3vfqqU1@mid.uni-berlin.de> <5kkcmvF3vfqqU3@mid.uni-berlin.de> Message-ID: In message <5kkcmvF3vfqqU3 at mid.uni-berlin.de>, Marc 'BlackJack' Rintsch wrote: > I see a tree structure here ... Good, you're improving. > ... but still no table. Who said anything about a table? > And this is also easily written that way in Python if you don't insist on > the line break after the ``if`` or can live with backslashes. Which is precisely the point. From pitonero at gmail.com Fri Sep 7 03:33:02 2007 From: pitonero at gmail.com (El Pitonero) Date: Fri, 07 Sep 2007 00:33:02 -0700 Subject: So what exactly is a complex number? In-Reply-To: <1189002459.001229.116700@d55g2000hsg.googlegroups.com> References: <451mq4-les.ln1@ozzie.tundraware.com> <1189002459.001229.116700@d55g2000hsg.googlegroups.com> Message-ID: <1189150382.664389.166620@50g2000hsm.googlegroups.com> On Sep 5, 7:27 am, El Pitonero wrote: > > I am a bit surprised that today, September 2007, in a thread about > complex numbers, no one has mentioned about geometric algebra. Here is a good reference for whoever is interested. It's quite accessible to general audience. http://www.xtec.es/~rgonzal1/treatise.pdf If a person spends some time to look at the geometric algebra, it will become clear that complex numbers are not that special, after all. Hopefully the relationship between the 2-d vector plane and the complex plane will also become more clear, as complex numbers can be understood as rotation-dilation operators over vectors. One also learns that complex numbers are based on a metric assumption of square of vectors (norm) being positive (a.k.a Euclidean space). There is nothing sacred about positively-defined metric, and in fact if one uses mixed signature metric (pseudo-Euclidean space), one comes up with hyperbolic numbers instead of complex numbers. From claird at lairds.us Thu Sep 13 10:17:46 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 13 Sep 2007 14:17:46 +0000 Subject: My first Python CGI (was: Coming from Perl) References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> <2b6Gi.222$372.110@read2.cgocable.net> Message-ID: In article <2b6Gi.222$372.110 at read2.cgocable.net>, Amer Neely wrote: >Amer Neely wrote: >> TheFlyingDutchman wrote: >>> On Sep 12, 5:30 pm, Amer Neely wrote: >>>> I'm a complete newbie with Python, but have several years experience >>>> with Perl in a web environment. >>>> >>>> A question I have, if someone here is familiar with Perl, does Python >>>> have something like Perl's 'here document'? I've just searched and read >>>> some postings on generating HTML but they all seem to refer to various >>>> template utilities. Is this the only way, or am I missing something? I'm >>>> used to generating X/HTML by hand, which makes the here document in Perl >>>> ideal for me. Also, many times a client already existing HTML code that >>>> I can use in a script. >>>> >>>> -- >>>> Amer Neely >>>> w:www.webmechanic.softouch.on.ca/ >>>> Perl | MySQL programming for all data entry forms. >>>> "Others make web sites. We make web sites work!" >>> >>> I am not sure if this is what you are looking for, but Python has a >>> special string with 3 quotes that I believe duplicates part of the >>> functionality of a here document: >>> >>> myHmtlHeader = """ >>> >>> My Page >>> >>> """ >>> >>> print myHtmlHeader >>> >>> >>> outputs: >>> >>> >>> >>> My Page >>> >>> >> >> Well, I have checked everything I can but I'm getting '500 Internal >> Server Error'. The log files aren't helpful: >> [Thu Sep 13 03:43:00 2007] [error] [client 24.235.184.39] Premature end >> of script headers: /home/softouch/public_html/cgi-bin/scratch/hello.py >> >> I can't even get it to run on my home PC running Apache + Win2K. Same >> error. >> >> My script: >> #!/usr/bin/python >> import cgitb; cgitb.enable(display=0, logdir=".") >> import sys >> sys.stderr = sys.stdout >> print "Content-Type: text/html" >> print >> >> print """ >> >> >>
Hello >> from Python
>>
>> Goodbye. >> >> >> """ >> > >I should have added that it runs from the command line OK. . . . Yes, it should work fine. Do the things you'd do if it were Perl source: when you say "it runs from the command line OK", do you mean invocation of /home/softouch/public_html/cgi-bin/scratch/hello.py gives sensible results? Does your Web server recognize that .py is a CGI extension? What are the permissions on /home/softouch/public_html/cgi-bin/scratch/hello.py? Might your server have an issue with "Content-Type" vs. "Content-type"? From ivlenin at gmail.com Fri Sep 14 13:57:12 2007 From: ivlenin at gmail.com (I V) Date: Fri, 14 Sep 2007 17:57:12 GMT Subject: Coming from Perl - SOLVED References: Message-ID: On Thu, 13 Sep 2007 23:49:32 -0400, Amer Neely wrote: > In trying to track down why this script would not run on my host, it has > to come to light that Python is installed, however the Apache module is > not. So, short story is - I was flogging a dead horse. Which Apache module? You don't need any special modules (just the regular CGI one) to use python in a CGI script. From fw3 at hotmail.co.jp Fri Sep 7 19:53:48 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Fri, 07 Sep 2007 23:53:48 +0000 Subject: Speed of Python In-Reply-To: <5ke4h3F31i6hU9@mid.uni-berlin.de> Message-ID: I am just trying to compare the speed with matlab. The arrange is used for another test, that is why it shows up in the mail. Thanks Frank >From: "Marc 'BlackJack' Rintsch" >To: python-list at python.org >Subject: Re: Speed of Python >Date: 7 Sep 2007 23:17:55 GMT > >On Fri, 07 Sep 2007 22:59:26 +0000, wang frank wrote: > > > I also have tried to use numpy to speed it up. However, surprisingly, it is > > slower than the pure python code. > > > > Here is the code: > > import numpy > > arange=numpy.arange > > nlog=numpy.log > > def bench6(n): > > for i in xrange(n): > > for j in xrange(1000): > > m=j+1 > > z=nlog(m) > > z1=nlog(m+1) > > z2=nlog(m+2) > > z3=nlog(m+3) > > z4=nlog(m+4) > > z5=nlog(m+5) > > z6=nlog(m+6) > > z7=nlog(m+7) > > z8=nlog(m+8) > > z9=nlog(m+9) > > return z9 > > > > [??] > > > > Anyone know why? > >Because you don't really take advantage of `numpy`. The `numpy.log()` >function can be used with scalars but I guess it is slower because it has >to check if its argument is a scalar or array. Untested: > >from numpy import arange, log as nlog > >def bench6(n): > for dummy in xrange(n): > for j in xrange(1000): > z = nlog(arange(j + 1, j + 11)) > return z[-1] >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ 3?????????????????3?????????? ?????2.2??? ? http://clk.atdmt.com/GBL/go/msnjpqjl0060000010gbl/direct/01/ From arnodel at googlemail.com Mon Sep 17 14:28:27 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 17 Sep 2007 18:28:27 -0000 Subject: =?iso-8859-1?q?Re:_I=B4m_trying_to_desenvolve_a_site_in_python?= In-Reply-To: <5l7uglF6kto9U1@mid.individual.net> References: <1190051850.198096.258890@o80g2000hse.googlegroups.com> <5l7uglF6kto9U1@mid.individual.net> Message-ID: <1190053707.193010.159350@n39g2000hsh.googlegroups.com> On Sep 17, 7:14 pm, Bjoern Schliessmann wrote: > Andre P.S Duarte wrote: > > I?m trying to desenvolve a site in python. > > What does "desenvolve" mean? By "site", do you mean a web site? > "desenvolver" is a spanish verb meaning "to develop". -- Arnaud From deets at nospam.web.de Wed Sep 5 09:41:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Sep 2007 15:41:52 +0200 Subject: handling modules in packages References: Message-ID: <5k7q10F2e6haU1@mid.uni-berlin.de> Tommy Grav wrote: > Hi, > > I am working on a package that contains a number of > different modules: > > > ls pyAstro > __init__.py > constants.py > conversion.py > observation.py > orbit.py > transformation.py > > however, I find that several of the modules have the > same import statements: > > orbit.py: > > import numpy > import constants > import conversion > import observations > > observations.py: > > import numpy > import constants > import conversions > import transformations > > The modules themselves are not overly large, but it bugs > me to have to import numpy twice (or even more as the > number of modules grow). Is there a way to import numpy > once in the package (like in the __init__.py file) such that > it is accessible to all the modules? Or is the multiple imports > just something one has to live with? Essentially, yes. That's the way it is, and it's better for understanding how things work in the respective submodules. However, you can stuff things into the __builtins__-module using setattr, and thus make names known globally. But it's a hack, and it means that you possibly create conflicts if different modules have different ideas on what is supposed to live under one key. so - don't do it. And live with the imports. After all, that's only c'n'p, and not of the bad kind. Diez From carsten at uniqsys.com Thu Sep 6 10:24:43 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 06 Sep 2007 10:24:43 -0400 Subject: startswith( prefix[, start[, end]]) Query In-Reply-To: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> References: <1189087752.538726.101350@r29g2000hsg.googlegroups.com> Message-ID: <1189088683.3376.5.camel@dot.uniqsys.com> On Thu, 2007-09-06 at 07:09 -0700, cjt22 at bath.ac.uk wrote: > Hi > > startswith( prefix[, start[, end]]) States: > > Return True if string starts with the prefix, otherwise return False. > prefix can also be a tuple of suffixes to look for. However when I try > and add a tuple of suffixes I get the following error: > > Type Error: expected a character buffer object You are probably looking at the documentation for Python 2.5, but you're using Python 2.4 or older: ####################################################################### Python 2.5 (r25:51908, Oct 28 2006, 12:26:14) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "blah".startswith(("a","b")) True ####################################################################### Python 2.4.3 (#1, Oct 23 2006, 14:19:47) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "blah".startswith(("a","b")) Traceback (most recent call last): File "", line 1, in ? TypeError: expected a character buffer object ####################################################################### HTH, -- Carsten Haese http://informixdb.sourceforge.net From LISTSERV at LISTSERV.AOL.COM Sun Sep 9 23:14:46 2007 From: LISTSERV at LISTSERV.AOL.COM (LISTSERV at LISTSERV.AOL.COM) Date: Sun, 9 Sep 2007 23:14:46 -0400 Subject: Message ("Your message dated Sun, 9 Sep 2007 23:15:08 -0400...") Message-ID: Your message dated Sun, 9 Sep 2007 23:15:08 -0400 with subject "Returned mail: Data format error" has been submitted to the moderator of the CSICOP-ANNOUNCE list: Barry Karr . From naga86 at gmail.com Mon Sep 10 07:46:02 2007 From: naga86 at gmail.com (Nagarajan) Date: Mon, 10 Sep 2007 04:46:02 -0700 Subject: less obvious "super" In-Reply-To: References: <1189417830.645749.226120@d55g2000hsg.googlegroups.com> Message-ID: <1189424762.591411.99760@d55g2000hsg.googlegroups.com> On Sep 10, 4:20 pm, Duncan Booth wrote: > Nagarajan wrote: > > Here is what I need to achieve.. > > > class A : > > def __init__( self ): > > self.x = 0 > > Don't use old style classes. If you are planning to use 'super' then you > must use new-style classes, so use 'object' as a base class here. > > > > > class B ( A ): > > def __init__( self, something ): > > # Use "super" construct here so that I can "inherit" x of A > > self.y = something > > > How should I use "super" so that I could access the variable "x" of A > > in B? > > If you aren't worried about diamond shaped multiple inheritance > hierarchies then just use: > > class B ( A ): > def __init__( self, something ): > A.__init__(self) > self.y = something > > If you are then: > > class B ( A ): > def __init__( self, something ): > super(B, self).__init__() > self.y = something > > When you use super you usually just want the current class and current > instance as parameters. Putting that together: > > >>> class A(object): > > def __init__( self ): > self.x = 0 > > >>> class B ( A ): > > def __init__( self, something ): > super(B, self).__init__() > self.y = something > > > > >>> obj = B(3) > >>> obj.x > 0 > >>> obj.y > 3 What's the difference b/w: class A: and class A ( object ): Thanks. From arnodel at googlemail.com Sun Sep 2 05:27:43 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 02 Sep 2007 02:27:43 -0700 Subject: howto compile recursively all *.py files to *.pyc (from a directory my_dir)? In-Reply-To: <1188714081.476816.310350@50g2000hsm.googlegroups.com> References: <1188714081.476816.310350@50g2000hsm.googlegroups.com> Message-ID: <1188725263.502586.217560@o80g2000hse.googlegroups.com> On Sep 2, 7:21 am, dmitrey wrote: > howto compile recursively all *.py files to *.pyc (from a directory > my_dir)? > Thank you in advance, D. import compileall compileall.compile_dir('my/python/project/') -- Arnaud From python.list at tim.thechases.com Sun Sep 30 12:59:07 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 30 Sep 2007 11:59:07 -0500 Subject: s.split() on multiple separators In-Reply-To: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> Message-ID: <46FFD5DB.5080504@tim.thechases.com> > OK, so I want to split a string c into words using several different > separators from a list (dels). > > I can do this the following C-like way: > >>>> c=' abcde abc cba fdsa bcd '.split() >>>> dels='ce ' >>>> for j in dels: > cp=[] > for i in xrange(0,len(c)-1): > cp.extend(c[i].split(j)) > c=cp > > >>>> c > ['ab', 'd', '', 'ab', '', ''] Given your original string, I'm not sure how that would be the expected result of "split c on the characters in dels". While there's a certain faction of pythonistas that don't esteem regular expressions (or at least find them overused/misused, which I'd certainly agree to), they may be able to serve your purposes well: >>> c=' abcde abc cba fdsa bcd ' >>> import re >>> r = re.compile('[ce ]') >>> r.split(c) ['', 'ab', 'd', '', 'ab', '', '', 'ba', 'fdsa', 'b', 'd', ''] given that a regexp object has a split() method. -tkc From tedpottel at gmail.com Fri Sep 21 13:32:44 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Fri, 21 Sep 2007 10:32:44 -0700 Subject: TRying to import files from my folder not pythons lib folder Message-ID: <1190395964.541835.114350@50g2000hsm.googlegroups.com> Hi, I'm trying to create my own lib of functions, but it seems like I can only import them if they are in pythons lib folder. Example I have a folder called K:\mypython Now in the interactive python shell I type Import k:\mypython\listall And get a error on : If I store listall.py in pythons lib folder and type Limport listall It works fins. Can I create my own library of functions and store them in a separate dir???? Also I try to creat a folder in pythomns lib folder and that did not work Help -Ted From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Sep 13 08:05:39 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 13 Sep 2007 14:05:39 +0200 Subject: struct is saving 4 bytes instead of 2 References: <1189632217.661924.25520@r34g2000hsd.googlegroups.com> <5kr8fkF53m8gU1@mid.individual.net> <1189640178.267346.321040@r34g2000hsd.googlegroups.com> Message-ID: <5ksncjF5c2s1U1@mid.individual.net> TonyB wrote: > I tried > > f.write(struct.pack('=h',thevariable)) > > and it works. Great! :) Regards, Bj?rn -- BOFH excuse #45: virus attack, luser responsible From michael at stroeder.com Wed Sep 12 05:21:48 2007 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 12 Sep 2007 11:21:48 +0200 Subject: Get Only the Last Items in a Traceback In-Reply-To: <1189562968.529414.27910@w3g2000hsg.googlegroups.com> References: <1189562968.529414.27910@w3g2000hsg.googlegroups.com> Message-ID: gregpinero at gmail.com wrote: > I'm running code via the "exec in context" statement within a much > larger program. What I would like to do is capture any possible > errors and show a pretty traceback just like the Python interactive > interpreter does, but only show the part of the traceback relating to > the code sent to exec. > > For example here is the code I'm using: > > try: > exec code > except Exception,Err: > traceback.print_exc() Guess what's argument limit is for. Excerpt from the Python docs: -------------------------------- snip -------------------------------- print_exc( [limit[, file]]) This is a shorthand for print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file). (In fact, it uses sys.exc_info() to retrieve the same information in a thread-safe way instead of using the deprecated variables.) -------------------------------- snip -------------------------------- Ciao, Michael. From andre.roberge at gmail.com Sun Sep 2 23:56:43 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Mon, 03 Sep 2007 03:56:43 -0000 Subject: Crunchy release 0.9.8 Message-ID: <1188791803.621269.276170@19g2000hsx.googlegroups.com> Crunchy version 0.9.8 has been released. Crunchy is an application that transforms static html-based Python tutorials into interactive sessions within your browser (Firefox; other browsers *may* not fully support Crunchy). Crunchy is available from http://code.google.com/p/crunchy Since the last public release, the following changes have been introduced: * Important changes to security model. + 6 security levels. * New interpreter types * New interpreter options. * New option (used by default) to view tutorials that have no Crunchy- specific markup. * More documentation. * Friendlier tracebacks (for Python beginners) - translatable in languages other than English. * Automatic updating of sys.path so that tutorials can make use of Python's import statement. * More configuration options. * New math_graphics module. * New logo. * New look. * French translation of Crunchy/Python messages (not documentation) almost complete. + many more. Bug reports, comments and suggestions are always welcome. Andr? From sidnei at enfoldsystems.com Mon Sep 24 16:49:01 2007 From: sidnei at enfoldsystems.com (Sidnei da Silva) Date: Mon, 24 Sep 2007 17:49:01 -0300 Subject: [lxml-dev] Python script to optimize XML text In-Reply-To: <496954360709241336i43173947sda5245c2d7477ecb@mail.gmail.com> References: <496954360709241336i43173947sda5245c2d7477ecb@mail.gmail.com> Message-ID: If your XML is well-formed, a XSLT is probably your best choice. I believe even the most trivial 'pass through' example might produce the output you expect here. -- Sidnei da Silva Enfold Systems http://enfoldsystems.com Fax +1 832 201 8856 Office +1 713 942 2377 Ext 214 From bj_666 at gmx.net Wed Sep 12 17:55:04 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Sep 2007 21:55:04 GMT Subject: Implementing a fixed size stack for an RPN Calculator References: <1189630522.152326.3040@d55g2000hsg.googlegroups.com> Message-ID: <5kr5hoF4s6gmU3@mid.uni-berlin.de> On Wed, 12 Sep 2007 20:55:22 +0000, rami.mawas at gmail.com wrote: > I have implemented an RPN calculator in python but now I would like to > make the stack size fixed. how can I transform the user's RPN > expression from a stack overflow to a computable expression. > > For instance, if my stack size is 2 then the some expression can't be > computed but could be transformed as following: > > Non computable expression: 1 2 3 + + --> stack size of 3 is needed > Computable expression: 1 2 + 3 + --> stack size of 2 is needed > > How can I define a formal way of transforming the non computable > expression to computable one. > > My RPN only implements: + - x % Why does this homework assignment limit the stack so severely!? ;-) Ciao, Marc 'BlackJack' Rintsch From software at ginstrom.com Wed Sep 19 08:03:04 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Wed, 19 Sep 2007 21:03:04 +0900 Subject: lambda-funcs problem In-Reply-To: <1190201984.062329.182460@k79g2000hse.googlegroups.com> References: <1190201984.062329.182460@k79g2000hse.googlegroups.com> Message-ID: <06eb01c7fab5$0aa2bb50$0203a8c0@MOUSE> > On Behalf Of dmitrey.kroshko at scipy.org > F = [] > for i in xrange(N): > F.append(lambda x: x + i) > > however, the example don't work - since i in end is N-1 it yields x+ > (N-1) for any func. How about: >>> def make_adder(i): def adder(x): return x+i return adder >>> funcs = [make_adder(i) for i in xrange(10)] >>> print [func(10) for func in funcs] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> Regards, Ryan Ginstrom From grante at visi.com Thu Sep 20 12:27:29 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Sep 2007 16:27:29 -0000 Subject: Python and RTF References: <1190271676.160077.99270@w3g2000hsg.googlegroups.com> <13f51i4adkseae5@corp.supernews.com> <1190301666.417426.13320@r29g2000hsg.googlegroups.com> Message-ID: <13f57rhcoh575ea@corp.supernews.com> On 2007-09-20, Marco Bonifazi wrote: >> FWIW, I've added support for EMF graphics and enhanced the >> scaling options for graphics: >> >> http://groups.google.com/group/comp.lang.python.announce/browse_threa... > Oh, wonderful! Is licensed with the GPL and LGPL as like the > previous versions are? Yes. > Then, can I put in my closed software and at the end of my > development make a donation? I'm really sure how the LGPL applies to Python applications. AFAICT, it's been abandoned by the original developer, so I doubt he's going to sue you. ;) If you fix any bugs or add any features, it would be nice if you'd send me a patch. -- Grant Edwards grante Yow! There's enough money at here to buy 5000 cans of visi.com Noodle-Roni! From jergosh at wp.pl Thu Sep 6 17:00:56 2007 From: jergosh at wp.pl (=?UTF-8?B?R3J6ZWdvcnogU8WCb2Rrb3dpY3o=?=) Date: Thu, 06 Sep 2007 23:00:56 +0200 Subject: So what exactly is a complex number? In-Reply-To: References: <451mq4-les.ln1@ozzie.tundraware.com> <1188821241.516029.229020@o80g2000hse.googlegroups.com> <46DE7AB9.9000702@wp.pl> Message-ID: <46E06A88.60800@wp.pl> Gabriel Genellina wrote: > En Wed, 05 Sep 2007 06:45:29 -0300, Grzegorz S?odkowicz > escribi?: > > >> I believe vectors can only be added if they have the same point of >> application. The result is then applied to the same point. >> > > You are talking about "forces", not "vectors" in general. Using the "point > of application" is just a convenient way of condensing two things: the > resultant force -a vector- and the resultant momentum -a pseudovector- > into a single entity, and only makes sense for a rigid body. >From the Wikipedia (http://en.wikipedia.org/wiki/Vector_%28spatial%29): "Two vectors sharing the same initial point can also be added or subtracted." Regards, Greg From kay.schluehr at gmx.net Wed Sep 19 23:01:52 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 19 Sep 2007 20:01:52 -0700 Subject: limiting memory consumption of Python itself or a dict in a Python program In-Reply-To: <1190234913.608070.5410@19g2000hsx.googlegroups.com> References: <1190234913.608070.5410@19g2000hsx.googlegroups.com> Message-ID: <1190257312.419152.304580@g4g2000hsf.googlegroups.com> On 19 Sep., 22:48, Jonas Maurus wrote: > Hello everybody, > > I'm pondering the following problem: > > I want to write a Python program that receives messages via SMTP and > stores them in a dict or an array. For my purposes it would be > important that all received mail would be kept in RAM and not cached > out to disk. If a new message comes in that can't fit in the allocated > memory, a number of old messages would be discarded. > > As the server needs to have room for other tasks, I'd like to limit > the overall memory consumption to a certain amount. > > Is this possible? How would I go about implementing it? By imposing > "ulimit"s and catching MemoryError? > > Thanks for your help, > Jonas When your application pre-allocates a chunk of memory and use datatypes like array and struct you might write your own memory manager. You can't control the total memory consumption of Python though, since Python implements an own malloc and it might allocate memory in large chunks. But this is somewhat orthogonal to your problem and applies also when Python reads/writes buffers from/to disk. From hall.jeff at gmail.com Sat Sep 29 12:46:18 2007 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Sat, 29 Sep 2007 16:46:18 -0000 Subject: Program inefficiency? In-Reply-To: References: Message-ID: <1191084378.478623.321740@r29g2000hsg.googlegroups.com> XP is the OS... the files are split across a ton of subdirectories already... I'm actually starting to think there's a problem with certain files, however... We create help files for clients using RoboHelp... RoboHelp has Source HTML and then "webhelp" html which is what actually goes to the client... I'm trying to mass maintenance the "source" files... Right now, my program works but you've got to delete the webhelp files first... I figured that (based on the exponential growth in processing time) it was the additional number of files... However, after streamlining the codes I got the following results done 300 4.1904767226e-006 done 600 7.97062280262 done 900 22.3963802662 done 1200 29.9211888662 done 1375 35.3465962853 with the webhelp deleted and done 300 4.1904767226e-006 done 600 7.6259175398 done 900 13.3994678095 still processing 10 minutes later with the webhelp intact Since the system didn't hang sometime after 1375 (and in fact, still hasn't made it there), I can only assume that it hit one of the webhelp files and freaked out... The thing that's really weird is that the files it's hanging on appear to be some of the most basic files in the whole system (small, not alot going on... no hits on the RE search)... So I may just tell the users to delete the webhelp and have robohelp recreate it after they've run the program... From michael at jedimindworks.com Sun Sep 2 16:25:06 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 2 Sep 2007 13:25:06 -0700 Subject: how can I find out the process ids with a process name In-Reply-To: <1188761187.522146.192380@y42g2000hsy.googlegroups.com> References: <1188761187.522146.192380@y42g2000hsy.googlegroups.com> Message-ID: <12B3D8EF-C30A-4BCC-80A5-71ADFA8F6944@jedimindworks.com> On Sep 2, 2007, at 12:26 PM, herman wrote: > I would like to find out all the process id with the process name > 'emacs'. > > In the shell, i can do this: > > $ ps -ef |grep emacs > root 20731 8690 0 12:37 pts/2 00:00:09 emacs-snapshot-gtk > root 25649 25357 0 13:55 pts/9 00:00:05 emacs-snapshot-gtk rtp.c > root 26319 23926 0 14:06 pts/7 00:00:04 emacs-snapshot-gtk > stressTestVideo.py > root 26985 1 0 14:15 ? 00:00:01 /usr/bin/emacs-snapshot- > gtk > root 27472 21066 0 14:23 pts/5 00:00:00 grep emacs > > > and I can see the process id is 20731, 25649, etc, etc. > > But now I would like to do the programmically in my python script. > I know I can use ' os.system(cmd)' to execute the command 'ps -ef | > grep emacs', but how > can I pipe the output of my 'ps -ef | grep emacs' to my python script > and then run a regression expression with it to get the process Ids? Are you targeting Linux? If so, have a look at the /proc system. Each process has a directory, and the 'status' file in each process' directory tells many things, including process name (the line that ends with the process name, begins with 'Name'). Here's a quick bashy way to get pid + process names: cd /proc for i in ls [0-9]*/status do echo $i `grep '^Name' $i | cut -f2` | sed 's/\/status//g' done hth, Michael --- "If we had asked people what they wanted they would have said 'a faster horse'." --Henry Ford From daniel.j.larsson at gmail.com Mon Sep 17 08:25:46 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Mon, 17 Sep 2007 14:25:46 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <20070913191341.69dae855@cube.tz.axivion.com> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> <1i4dddf.piaojwz9lz40N%aleax@mac.com> <1189700775.661780.292150@50g2000hsm.googlegroups.com> <20070913191341.69dae855@cube.tz.axivion.com> Message-ID: <2bfa72fa0709170525w1fcb734fxedf6fac70ecbc8a1@mail.gmail.com> On 9/13/07, Stefan Bellon wrote: > > On Thu, 13 Sep, TheFlyingDutchman wrote: > > > Bruce said that no other mainstream OO language is explicitly passing > > the object as a parameter to class methods. > > Ada 95 does. And Ada 95 was the first standardized OO language. Now that's debatable :) "SIMULA 67 was formally standardized on the first meeting of the SIMULA Standards Group (SSG) in February 1968." http://en.wikipedia.org/wiki/Simula -------------- next part -------------- An HTML attachment was scrubbed... URL: From f.guerrieri at gmail.com Tue Sep 18 15:38:20 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Tue, 18 Sep 2007 21:38:20 +0200 Subject: Wait For Application Start In-Reply-To: <5AF03B37-0D8A-457E-8995-8C4E578C9550@jedimindworks.com> References: <120025966304300060@unknownmsgid> <79b79e730709180540q2045a086rc6a049f16bd7e7ad@mail.gmail.com> <5AF03B37-0D8A-457E-8995-8C4E578C9550@jedimindworks.com> Message-ID: <79b79e730709181238s4bf5d7f3y574bcecbe0823421@mail.gmail.com> On 9/18/07, Michael Bentley wrote: > > > > import os.path > > import time > > > > while True: > > if os.path.exists(YOUR_FILE): > > break > > time.sleep(30) > > or > > while not os.path.exists(YOUR_FILE): > time.sleep(1) I thought of that, but I found more readable the positive form :-) francesco From zzbbaadd at aol.com Tue Sep 11 23:33:05 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Tue, 11 Sep 2007 20:33:05 -0700 Subject: Get the complete command line as-is In-Reply-To: <1189566000.793354.308420@19g2000hsx.googlegroups.com> References: <1189566000.793354.308420@19g2000hsx.googlegroups.com> Message-ID: <1189567985.089215.108250@k79g2000hse.googlegroups.com> On Sep 11, 8:00 pm, wangzq wrote: > Hello, > > I'm passing command line parameters to my browser, I need to pass the > complete command line as-is, for example: > > test.py "abc def" xyz > > If I use ' '.join(sys.argv[1:]), then the double quotes around "abc > def" is gone, but I need to pass the complete command line ("abc def" > xyz) to the browser, how can I do this? > > I'm on Windows. > > Thanks. I'm on Solaris and this works for me: test.py '"abc def" xyz' print sys.arv[1] "abc def" xyz From hniksic at xemacs.org Wed Sep 19 03:22:36 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 19 Sep 2007 09:22:36 +0200 Subject: super() doesn't get superclass References: <8764281uea.fsf@benfinney.id.au> <87zlzkzgu2.fsf@benfinney.id.au> <46efdcaf$0$14241$426a74cc@news.free.fr> <87abrkhtfp.fsf@mulj.homelinux.net> <871wcvzhvc.fsf@benfinney.id.au> Message-ID: <87odfz5dc3.fsf@mulj.homelinux.net> Ben Finney writes: > Hrvoje Niksic writes: > >> class X(Y): >> def foo(self): >> super(X, self).foo() >> >> ...there is in fact no guarantee that super() calls a superclass of >> X. However, it is certainly guaranteed that it will call a superclass >> of type(self). > > Not even that. It could call *any class in the inheritance > hierarchy*, The inheritance hierarchiy is populated by the various (direct and indirect) superclasses of type(self). > depending on how the MRO has resolved "next class". Even one that is > neither an ancestor nor a descendant of X. My point exactly. superclass of X is not the same as superclass of type(self). Super iterates over the latter, where you expect the former. From jeremy+complangpython at jeremysanders.net Thu Sep 20 05:10:08 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Thu, 20 Sep 2007 10:10:08 +0100 Subject: limiting memory consumption of Python itself or a dict in a Python program References: <1190234913.608070.5410@19g2000hsx.googlegroups.com> Message-ID: Jonas Maurus wrote: > I want to write a Python program that receives messages via SMTP and > stores them in a dict or an array. For my purposes it would be > important that all received mail would be kept in RAM and not cached > out to disk. If a new message comes in that can't fit in the allocated > memory, a number of old messages would be discarded. > > As the server needs to have room for other tasks, I'd like to limit > the overall memory consumption to a certain amount. Since your data is all in one place, why not write a dict or list wrapper which keeps track of the total space of the items stored (using len on the strings)? It could automatically clean out old entries when the memory usage becomes too much. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From jfine at pytex.org Tue Sep 18 09:55:18 2007 From: jfine at pytex.org (Jonathan Fine) Date: Tue, 18 Sep 2007 14:55:18 +0100 Subject: [ANN] Metatest 0.1.0 Message-ID: Hello This announcement also appears on the Metatest web site http://metatest.sourceforge.net === *** Metatest - a Python test framework Metatest is a simple and elegant Python framework for writing tests. Metatest is mostly about writing tests and by design is not tied to any particular test runner. Hence the name. Here's how to write some tests using Metatest. We can think of the tests as an executable specification. from metatest.py.mymod import plus, Point # Function plus adds two numbers. plus(2, 2) == 4 plus(2, '', _ex=TypeError) # Class Point represent a point in the plane. p = Point(2, 5) p.x == 2 p.y == 5 p.area == 10 And here's one way to run them. if __name__ == '__main__': import metatest metatest.run() It's not hard to write an adapter that will run these tests in a different test runner framework. We gave a talk about Metatest at PyCon UK 2007 and here are the slides (HTML). http://www.pyconuk.org http://metatest.sourceforge.net/doc/pyconuk2007/metatest.html Please visit Sourceforge to download Metatest. http://sourceforge.net/project/showfiles.php?group_id=204046 -- Jonathan Fine From duncan.booth at invalid.invalid Wed Sep 26 06:02:31 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Sep 2007 10:02:31 GMT Subject: Confused about 'positive lookbehind assertion' References: <496954360709241938k6baf1009gc7cab215ad16b12f@mail.gmail.com> <1190753752.126335.205410@o80g2000hse.googlegroups.com> Message-ID: "Andrew Durdin" wrote: > On 9/25/07, Karthik Gurusamy wrote: >> >> Any idea what this positive lookbehind achieves which can't be done >> without it. >> I remember cases where positive look-ahead is useful. >> >> In the above example, r.search('abcdef') does the job of ensuring >> 'def' is preceded by 'abc'. > > AFAICT the only benefit I can see is that the lookbehind isn't > captured, so (a) it's not included in match.group(n), and (b) > match.start(), match.end(), and match.span() return the offsets of the > bit you actually wanted to capture. It also makes a difference if you are searching for multiple patterns and the lookbehind overlaps the previous result: >>> re.findall('(?<=abc)(abc|def)', 'abcabcdef') ['abc', 'def'] I think though that its real use is not at the beginning of a pattern but in the middle: you might have a greedy pattern which matches too easily (possibly to create a group), and then a guard which looks behind. e.g. >>> re.findall('(\d*)((?<=1)a|(?<=2)b)', '111a 111b 222b') [('111', 'a'), ('222', 'b')] This pattern finds all numbers ending in 1 followed by 'a', or ending in 2 followed by 'b' and it returns groups containing the number and the trailing letter. You could write '\d*(1a|2b)' but that doesn't get you the correct groups. From wizzardx at gmail.com Tue Sep 11 14:21:27 2007 From: wizzardx at gmail.com (David) Date: Tue, 11 Sep 2007 20:21:27 +0200 Subject: customizing a logging logger In-Reply-To: <1189527296.426004.17600@19g2000hsx.googlegroups.com> References: <1187412814.493872.325190@j4g2000prf.googlegroups.com> <1189527296.426004.17600@19g2000hsx.googlegroups.com> Message-ID: <18c1e6480709111121od75650bi9ec814f9bdcaad5e@mail.gmail.com> On 9/11/07, garyjefferson123 at gmail.com wrote: > I think the following question is clearer. > > I want to make it so that method1 below can be transformed: > > logger = logging.getLogger("somelogger") > class SomeOp: > def __init__(self, ctx): > self.ctx = ctx > def method1(self): > logger.info("%s: here's a message", self.ctx) > logger.debug("%s: msg #2", self.ctx) > v = 'yessir' > logger.debug("%s: msg #3 %s", self.ctx, v) > > into something like: > > def method1(self): > logger.info("here's a message") > logger.debug("msg #2") > v = 'yessir' > logger.debug("msg #3 %s", v) > > > What is the best way to do this, so that I don't have to manually put > the self.ctx in the log string in hundreds of different places? One way to do it is to make a mixin class (eg: ContextLogging) which you construct with the context string. The mixin constructor has a line like this: self.logger = logging.getLogger(ctx). (assuming your context string is appropriate for a logger name) Then your methods call self.logger instead of the module-level logger. Another method is also to use a mixin class, which provides methods "log_debug", "log_info", etc methods which wrap calls to a logger object. Another (more advanced) method is to create a custom Logger class. It uses the call stack to determine if it's caller has a "ctx" attribute, and pushes the value of that attribute into the message string. Then you call logging.setLoggerClass so that you get instances of your custom logger class. From iamsidd at gmail.com Sun Sep 16 15:11:48 2007 From: iamsidd at gmail.com (Sidd) Date: Sun, 16 Sep 2007 19:11:48 -0000 Subject: Probstat Combination Objects and Persistence In-Reply-To: <1189954886.324005.325240@22g2000hsm.googlegroups.com> References: <1189954886.324005.325240@22g2000hsm.googlegroups.com> Message-ID: <1189969908.477201.137360@w3g2000hsg.googlegroups.com> On Sep 16, 8:01 am, dohertywa wrote: > Hi: > > I'm working with probstat module which does an excellent job for the > project I'm working on. > > I am passing the Combination objects I generate to generator functions > that allow me to scale down the results. > > I am trying to find a way however to store the end resultant > Combination object. Try to pickle it, and Python segfaults. > > I want to be able to store the Combination object at any point so I > may operate on it later without having to repeat previous work. > > Any suggestions? > > TVKIA, > Adam You might want to take a look at this tutorial:http://www.ibm.com/ developerworks/library/l-pypers.html From paul at boddie.org.uk Wed Sep 19 18:41:51 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 19 Sep 2007 15:41:51 -0700 Subject: Will Python 3.0 remove the global interpreter lock (GIL) In-Reply-To: <1190164166.378500.155990@o80g2000hse.googlegroups.com> References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> Message-ID: <1190241711.344058.238380@57g2000hsv.googlegroups.com> On 19 Sep, 03:09, TheFlyingDutchman wrote: > > How much faster/slower would Greg Stein's code be on today's > processors versus CPython running on the processors of the late > 1990's? And if you decide to answer, please add a true/false response > to this statement - "CPython in the late 1990's ran too slow". Too slow for what? And what's the fixation with CPython, anyway? Other implementations of Python 2.x don't have the GIL. Contrary to popular folklore, Jython has been quite a reasonable implementation of Python for about half as long as CPython has been around, if you don't mind the JVM. I'm sure people have lots of complaints about Jython like they do about CPython and the GIL, thinking that complaining about it is going to make the situation better, or that they're imparting some kind of "wisdom" to which the people who actually wrote the code must be oblivious, but nobody is withholding the code from anyone who wants to actually improve it. And there we learn something: that plenty of people are willing to prod others into providing them with something that will make their lives better, their jobs easier, and their profits greater, but not so many are interested in contributing back to the cause and taking on very much of the work themselves. Anyway, the response to your statement is "false". Now you'll have to provide us with the insight we're all missing. Don't disappoint! Paul From onurays23 at gmail.com Sat Sep 1 20:35:28 2007 From: onurays23 at gmail.com (onurays) Date: Sun, 2 Sep 2007 03:35:28 +0300 Subject: A big problem with _name_ == '_main_' Message-ID: Hi, I have begun to teach me Python today. The problem is : NameError: name 'name' is not defined. I am using winXP and i used that: if _name_ == '_main_' : MyClass() gtk.main() Onuray. From keherma at comcast.net Thu Sep 6 01:24:36 2007 From: keherma at comcast.net (keith) Date: Thu, 06 Sep 2007 01:24:36 -0400 Subject: Let's Unite Against Jews and Mongrels! In-Reply-To: <1188849476.067121.119110@r34g2000hsd.googlegroups.com> References: <1188198797.772672.60840@r29g2000hsg.googlegroups.com> <1188300284.507909.126770@57g2000hsv.googlegroups.com> <46D40BFE.2020301@comcast.net> <1188744204.822322.198360@57g2000hsv.googlegroups.com> <46DAD433.1030503@comcast.net> <1188849476.067121.119110@r34g2000hsd.googlegroups.com> Message-ID: devondejohn at comcast.net wrote: > > HEY! NOBODY BASHES THE TOOTH FAIRY! > they can, only if they had their penis enlarged 3 inches within the last six months.. :P From jcd at sdf.lonestar.org Thu Sep 20 23:14:04 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 20 Sep 2007 23:14:04 -0400 Subject: UTF-8 characters in doctest In-Reply-To: <46F334D1.20909@sdf.lonestar.org> References: <1190202459.229197.297350@n39g2000hsh.googlegroups.com> <878x71jfwo.fsf@pobox.com> <46F334D1.20909@sdf.lonestar.org> Message-ID: <46F336FC.3070806@sdf.lonestar.org> J. Cliff Dyer wrote: > John J. Lee wrote: > >> Peter Otten <__peter__ at web.de> writes: >> [...] >> >> >>> def f(s): >>> return (s,) >>> >>> >> Forgive me if this is a stupid question, but: What purpose does >> function f serve? >> >> >> John >> >> > > Well, it has nothing to do with the unicode bit that came before it. It > just takes an argument, and wraps it in a 1-tuple. Guessing by the > argument of "s", that argument is expected to be a string. > > One use I can think of is that sometimes you'll find a function that > returns a string or a list or tuple of strings. If you want to pass that > result on to a for loop, and only loop once on the string (instead of > looping on each letter of the string), you might want to wrap it in a > tuple or a list before passing it to the loop. > > Cheers, > Cliff (replying to my own post) Sorry. Itchy trigger finger and tired brain. I didn't read the whole context of the thread. Dunno what it's doing here. Forcing __repr__ to be called on a print statement? Funny way to do that. Like I said, I don't know, so I'll leave it to someone else to say. Cheers, Cliff From iclark at mail.ewu.edu Thu Sep 6 14:50:49 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Thu, 06 Sep 2007 11:50:49 -0700 Subject: Beginners Query - Simple counter problem In-Reply-To: <1189104274.3376.32.camel@dot.uniqsys.com> References: <13e0g0id9rlmg71@corp.supernews.com> <1189102450.3376.17.camel@dot.uniqsys.com> <1189104274.3376.32.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > On Thu, 2007-09-06 at 11:24 -0700, Ian Clark wrote: >> Carsten Haese wrote: >>> def d6(count): >>> return sum(random.randint(1, 6) for die in range(count)) >>> >> My stab at it: >> >> >>> def roll(times=1, sides=6): >> ... return random.randint(times, times*sides) > > That produces an entirely different probability distribution if times>1. > Consider times=2, sides=6. Your example will produce every number > between 2 and 12 uniformly with the same probability, 1 in 11. When > rolling two six-sided dice, the results are not evenly distributed. E.g. > the probability of getting a 2 is only 1 in 36, but the probability of > getting a 7 is 1 in 6. > Doh. I stand corrected. Probability was never a fun subject for me. :) Ian From mclausch at gmail.com Fri Sep 7 17:46:26 2007 From: mclausch at gmail.com (Matthew Lausch) Date: Fri, 07 Sep 2007 14:46:26 -0700 Subject: Subprocess module and unicode input Message-ID: <1189201586.423477.28200@g4g2000hsf.googlegroups.com> I'd like to use the subprocess module with upper level characters in the process name or in the arguments to the process. Something like this: cmd = [ u'test_\u65e5\u672c\u8a9e_exec.bat', u'arg1', u'arg2' ] subprocess.call(cmd) But this gives the error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 5-7: ordinal not in range(128) Is there a way around this problem? I don't want to assume any particular set of characters. The example above uses Japanese characters, but I would like to support anything. Thanks. From ladaan at iptel.org Thu Sep 27 02:46:56 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Thu, 27 Sep 2007 08:46:56 +0200 Subject: ~ bit-wise unary operator In-Reply-To: References: Message-ID: <46FB51E0.6010400@iptel.org> Wow, so many answers :). Thank you, guys :). Lada Michal Bozon wrote: > cau, > maybe int is represented internally as a signed integer > > you can use numpy types: > > >>>> import numpy >>>> ~ numpy.uint16(7978) >>>> > 57557 > > -m. > > > On Thu, 27 Sep 2007 00:14:49 +0200, Ladislav Andel wrote: > > >> Hello, >> why ~ bit-wise unary operator returns -(x+1) and not bit inversion of >> the given integer? >> >> example: >> a = 7978 >> a = ~a >> python returns -7979 >> >> but I need to get back 57557 as in C language. >> >> which is also in binary >> 0001111100101010 >> and inverted >> 1110000011010101 >> >> Is here any other operator or do I have to write it on my own? >> >> Thank you, >> Lada >> > > From bj_666 at gmx.net Fri Sep 7 14:30:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2007 18:30:36 GMT Subject: How to determine the bool between the strings and ints? References: <1189182688.290480.102350@o80g2000hse.googlegroups.com> Message-ID: <5kdjmcF31i6hU7@mid.uni-berlin.de> On Fri, 07 Sep 2007 18:49:12 +0200, Jorgen Bodde wrote: > As for why caring if they are bools or not, I write True and False to > the properties, the internal mechanism works like this so I need to > make that distinction. Really? Can't you just apply the `int()` function? In [52]: map(int, [1, 0, True, False]) Out[52]: [1, 0, 1, 0] Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Mon Sep 3 20:43:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Sep 2007 21:43:29 -0300 Subject: metaclasses: timestamping instances References: <1188665051.107414.61200@50g2000hsm.googlegroups.com> Message-ID: En Mon, 03 Sep 2007 07:39:05 -0300, km escribi?: > But why does it show varied difference in the time between a and b > instance creations when __metaclass__ hook is used and when not used in > class Y ? I dont understand that point ! What do you expect from a._created, b._created, and its difference? You reset Meta.start each time - so _created measures the time between creation of two consecutive instances (minus a small delay because of the *two* calls to time.time()) And obviously the elapsed time until the second instance is created is larger, due to the intervening print statement. -- Gabriel Genellina From mark at qtrac.eu Tue Sep 25 06:40:53 2007 From: mark at qtrac.eu (Mark Summerfield) Date: Tue, 25 Sep 2007 11:40:53 +0100 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <59e9fd3a0709250313v76a7626dn69908b39e4ba100b@mail.gmail.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <59e9fd3a0709250313v76a7626dn69908b39e4ba100b@mail.gmail.com> Message-ID: <200709251140.53098.mark@qtrac.eu> On 2007-09-25, Andrew Durdin wrote: > On 9/25/07, Mark Summerfield wrote: > > Since the sorteddict's data is always kept in key order, indexes > > (integer offsets) into the sorteddict make sense. Five additional > > methods are proposed to take advantage of this: > > > > key(index : int) -> value > > > > item(index : int) -> (key, value) > > > > value(index : int) -> key > > > > set_value(index : int, value) > > > > delete(index : int) > > But what about using non-sequential integer keys (something I do quite > often)? > > e.g. sorteddict({1:'a', 3:'b': 5:'c', 99:'d'})[3] should return 'b', not > 'd'. > > Andrew Hmmm, managed to confuse myself with 'b' and 'd'! d = sorteddict({1:"one", 3:"three", 5:"five", 99:"ninetynine"}) d.items() [(1, 'one'), (3, 'three'), (5, 'five'), (99, 'ninetynine')] d[3], d.value(3) ('three', 'ninetynine') So using [] returns the value for the given key and using value() returns the value for the given index position. -- Mark Summerfield, Qtrac Ltd., www.qtrac.eu From erik at myemma.com Thu Sep 27 13:43:38 2007 From: erik at myemma.com (Erik Jones) Date: Thu, 27 Sep 2007 12:43:38 -0500 Subject: True of False In-Reply-To: References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> <5m254hFatlbuU2@mid.uni-berlin.de> Message-ID: On Sep 27, 2007, at 12:29 PM, Erik Jones wrote: > > On Sep 27, 2007, at 11:47 AM, Marc 'BlackJack' Rintsch wrote: > >> On Thu, 27 Sep 2007 09:33:34 -0700, koutoo wrote: >> >>> I tried writing a true and false If statement and didn't get >>> anything? I read some previous posts, but I must be missing >>> something. I just tried something easy: >>> >>> a = ["a", "b", "c", "d", "e", "f"] >>> >>> if "c" in a == True: >>> Print "Yes" >>> >>> When I run this, it runs, but nothing prints. What am I doing >>> wrong? >> >> Wow that's odd: >> >> In [265]: a = list('abcdef') >> >> In [266]: a >> Out[266]: ['a', 'b', 'c', 'd', 'e', 'f'] >> >> In [267]: 'c' in a >> Out[267]: True >> >> In [268]: 'c' in a == True >> Out[268]: False >> >> In [269]: ('c' in a) == True >> Out[269]: True >> >> In [270]: 'c' in (a == True) >> --------------------------------------------------------------------- >> - >> ----- >> Traceback (most recent >> call last) >> >> /home/bj/ in () >> >> : argument of type 'bool' is not >> iterable >> >> >> What's going on there? > > That is weird. Given 270, what's happening in 268. > > Erik Jones Cool, Richard Thomas answered this one for me. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From arnodel at googlemail.com Sat Sep 1 14:43:03 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 01 Sep 2007 11:43:03 -0700 Subject: datetime.timedelta division confusion In-Reply-To: References: Message-ID: <1188672183.410842.27070@r29g2000hsg.googlegroups.com> On Sep 1, 7:28 pm, s... at pobox.com wrote: > Running from Subversion, I see confusing (to me) behavior related to > division of datetime.timedelta objects by integers: > > % python > Python 2.6a0 (trunk:57277:57280M, Aug 28 2007, 17:44:49) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import datetime > >>> d = datetime.timedelta(1) > >>> d / 2 > Traceback (most recent call last): > File "", line 1, in > TypeError: unsupported operand type(s) for /: 'datetime.timedelta' and 'int' > >>> d.__div__(2) > datetime.timedelta(0, 43200) > > When I run the interpreter under gdb's control with a breakpoint set in > delta_divide, the breakpoint is not reached in the first case, but it is in > the second. Is there something amiss with division of timedelta objects by > ints or am I just missing something? > > Skip Try d // 2 ? It may be that v2.6 considers / as __truediv__ and not __div__. I can reproduce this behaviour on 2.4: daffodil:~ arno$ python2.4 Python 2.4.3 (#1, Oct 20 2006, 12:58:47) [GCC 4.0.1 (Apple Computer, Inc. build 5247)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import division >>> import datetime >>> d = datetime.timedelta(1) >>> d/2 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for /: 'datetime.timedelta' and 'int' >>> d // 2 datetime.timedelta(0, 43200) >>> HTH -- Arnaud From perl4hire at softouch.on.ca Wed Sep 12 21:05:44 2007 From: perl4hire at softouch.on.ca (Amer Neely) Date: Wed, 12 Sep 2007 21:05:44 -0400 Subject: Coming from Perl In-Reply-To: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> Message-ID: TheFlyingDutchman wrote: > On Sep 12, 5:30 pm, Amer Neely wrote: >> I'm a complete newbie with Python, but have several years experience >> with Perl in a web environment. >> >> A question I have, if someone here is familiar with Perl, does Python >> have something like Perl's 'here document'? I've just searched and read >> some postings on generating HTML but they all seem to refer to various >> template utilities. Is this the only way, or am I missing something? I'm >> used to generating X/HTML by hand, which makes the here document in Perl >> ideal for me. Also, many times a client already existing HTML code that >> I can use in a script. >> >> -- >> Amer Neely >> w:www.webmechanic.softouch.on.ca/ >> Perl | MySQL programming for all data entry forms. >> "Others make web sites. We make web sites work!" > > I am not sure if this is what you are looking for, but Python has a > special string with 3 quotes that I believe duplicates part of the > functionality of a here document: > > myHmtlHeader = """ > > My Page > > """ > > print myHtmlHeader > > > outputs: > > > > My Page > > Yep, I think that is the way I will have to go. Thanks. -- Amer Neely w: www.webmechanic.softouch.on.ca/ Perl | MySQL programming for all data entry forms. "Others make web sites. We make web sites work!" From tuomas.vesterinen at pp.inet.fi Tue Sep 4 21:18:05 2007 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Wed, 05 Sep 2007 01:18:05 GMT Subject: Undeterministic strxfrm? In-Reply-To: References: Message-ID: Peter Otten wrote: > Python seems to be the culprit as there is a relatively recent > strxfrm-related bugfix, see Thanks Peter. Can't find it, do you have the issue number? > http://svn.python.org/view/python/trunk/Modules/_localemodule.c?rev=54669 > > If I understand it correctly the error makes it likely that the resulting > string has trailing garbage characters. Reading the rev 54669 it seems to me, that the bug is not fixed. Man says: STRXFRM(3): ... size_t strxfrm(char *dest, const char *src, size_t n); ... The first n characters of the transformed string are placed in dest. The transformation is based on the program?s current locale for category LC_COLLATE. ... The strxfrm() function returns the number of bytes required to store the transformed string in dest excluding the terminating ?\0? character. If the value returned is n or more, the contents of dest are *indeterminate*. Accordin the man pages Python should know the size of the result it expects and don't trust the size strxfrm returns. I don't completely understand the collate algorithm, but it should offer different levels of collate. So Python too, should offer those levels as a second parameter. Hovever strxfrm don't offer more parameters either except there is another function strcasecmp. So Python should be able to calculate the expected size before calling strxfrm or strcasecmp. I don't how it is possible. May be strcoll knows better and I should kick strxfrm off and take strcoll instead. It costs converting the seach key in every step of the search. Tuomas > Peter From rustompmody at gmail.com Sun Sep 16 05:09:58 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 16 Sep 2007 14:39:58 +0530 Subject: generating list of sub lists In-Reply-To: <1189931217.415065.102820@w3g2000hsg.googlegroups.com> References: <1189931217.415065.102820@w3g2000hsg.googlegroups.com> Message-ID: On 9/16/07, cesco wrote: > Hi, > > is there a one-liner to accomplish the following task? > >From the list > l = ['string1', 'string2', 'string3'] > generate the list of lists > l = [['string1'], ['string1', 'string2'], ['string1', 'string2', > 'string3']] > > Any help would be appreciated. > > Thanks > Francesco >>> l = [1,2,3,4,5] >>> [l[:i] for i in range(len(l))] [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] >>> well almost works except for the first empty list. [Are you sure you dont want it?] Corrected >>> [l[:i+1] for i in range(len(l)-1)] [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] Though I wonder if there is as neat a way as the first? From ruoyu0088 at gmail.com Wed Sep 26 02:29:09 2007 From: ruoyu0088 at gmail.com (HYRY) Date: Tue, 25 Sep 2007 23:29:09 -0700 Subject: the address of list.append and list.append.__doc__ In-Reply-To: References: <1190775258.351819.24930@22g2000hsm.googlegroups.com> <1190780557.879816.13800@d55g2000hsg.googlegroups.com> Message-ID: <1190788149.477809.80130@g4g2000hsf.googlegroups.com> > "the problem"? > Perhaps if you explain what you really want to do, someone can think the > way to do that, most likely *not* using id() Thanks, now I know I cannot use id() for my problem. Here is my problem: I want to add a docstring translator into the Python interpreter. If the user input: >>> a = [1,2,3] >>> a.append( this translator will show the docstring of append in my native language. Because __doc__ is read only, I added a dict to the interpreter as follows: DOC[list.append.__doc__] = """ translated version of the __doc__ """ When it is the time to show docstring, the program get the translated version from DOC. This works, but I think the key of DOC is too long, so I want to use the id of list.append.__doc__ as the key; or use the id of list.append: DOC[id(list.append.__doc__)] = "..." DOC[id(list.append)] = "..." So, I asked how to get list.append from a.append, and why id(list.append.__doc__) changes. From hniksic at xemacs.org Wed Sep 26 06:27:01 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 26 Sep 2007 12:27:01 +0200 Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> <1190719164.587009.206340@19g2000hsx.googlegroups.com> <1190721061.573653.304110@r29g2000hsg.googlegroups.com> <1190744523.025029.227690@k79g2000hse.googlegroups.com> <2O-dnYn-b87Gx2TbnZ2dnUVZ_j-dnZ2d@comcast.com> <1190748509.786571.124150@n39g2000hsh.googlegroups.com> <1190753722.026806.254530@d55g2000hsg.googlegroups.com> <1190756003.292096.71130@o80g2000hse.googlegroups.com> <1190789981.385466.37870@57g2000hsv.googlegroups.com> <87sl51lshd.fsf@mulj.homelinux.net> <1190799759.367001.106400@r29g2000hsg.googlegroups.com> Message-ID: <87fy11lo22.fsf@mulj.homelinux.net> Mark Summerfield writes: > On 26 Sep, 09:51, Hrvoje Niksic wrote: >> Duncan Booth writes: >> > I that's the point though: you can't write one implementation >> > that has good performance for all patterns of use >> >> An implementation of sorted dict using a balanced tree as the >> underlying data structure would give decent performance in all the >> mentioned use cases. For example, red-black trees search, insert, and >> delete in O(log n) time. > > Basically, as implemented, I have to invalidate if there is any > change [...] No argument here, as long as the limitation is understood to be a consequence of the current implementation model. Seriously proposing a sorteddict that is a mere syntactic sugar over dict dooms the PEP to rejection. Major programming language libraries have included sorted mapping and set types for a while now, making the performance and complexity constraints generally well understood. We should make use of that knowledge when designing sorteddict. From fakeaddress at nowhere.org Sun Sep 9 20:08:28 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 10 Sep 2007 00:08:28 GMT Subject: Modul (%) in python not like in C? In-Reply-To: References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> <46E4466C.2030303@sdf.lonestar.org> Message-ID: <0W%Ei.14427$3x.11615@newssvr25.news.prodigy.net> Arnau Sanchez wrote: >> Dotan Cohen wrote: >>> Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or >>> the other in error? Is this a known gotcha? I tried to google the >>> subject however one cannot google the symbol %. Thanks in advance. [...] > In fact, what you get in C depends on the compiler and architecture, Not according to the C standard: When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.(87) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a. [...] 87) This is often called ??truncation toward zero??. [International Standard ISO/IEC 9899:1999, Section 6.5.5 Multiplicative operators, Paragraph 6 and footnote 87] > while Python is always consistent and returns positive remainders. Technically: The modulo operator always yields a result with the same sign as its second operand (or zero) [http://docs.python.org/ref/binary.html] -- --Bryan From ldo at geek-central.gen.new_zealand Mon Sep 24 22:52:39 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 25 Sep 2007 14:52:39 +1200 Subject: shutil.copy2 error References: <1190644477.380312.261840@d55g2000hsg.googlegroups.com> <1190673284.509807.110830@57g2000hsv.googlegroups.com> <1190681351.841370.100150@19g2000hsx.googlegroups.com> Message-ID: In message <1190681351.841370.100150 at 19g2000hsx.googlegroups.com>, Horse wrote: > I should've mentioned earlier, but this is > running on a windows 2000 system, and the destination folder is a > samba share on a Linux server. Could it be the connection to the Samba server has gone down temporarily? From gagsl-py2 at yahoo.com.ar Sat Sep 29 02:04:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Sep 2007 03:04:09 -0300 Subject: Bug: spurious indentation error References: <33dffc910709282143y76151e66r2f8641ed2972661a@mail.gmail.com> Message-ID: En Sat, 29 Sep 2007 01:43:53 -0300, Mridula Ramesh escribi?: > Lol, nope, I checked today too, and it happened again. Try running this > as a > script, not from the prompt - I got a SyntaxError on line 10 as expected. After correcting it, I got an `IndentationError: expected an indented block` on line 23, due to a long line being wrapped onto the next line. A syntax error may be reported some lines later than the actual mistake, if the following lines build a good construct. For example, a missing close parenthesis. -- Gabriel Genellina From kostaspaxos at yahoo.gr Sat Sep 22 05:37:01 2007 From: kostaspaxos at yahoo.gr (Konstantinos Pachopoulos) Date: Sat, 22 Sep 2007 12:37:01 +0300 Subject: find difference in days from YYYYMMDD to YYYYMMDD Message-ID: <46F4E23D.7050600@yahoo.gr> Hi, does any body now any such algorith? to find difference in days from YYYYMMDD to YYYYMMDD? Or just an algorithm, that converts YYYYMMDD to seconds since the epoch? Thanks From trekker182 at comcast.net Thu Sep 27 13:50:49 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Thu, 27 Sep 2007 13:50:49 -0400 Subject: ValueError: too many values to unpack,>>> In-Reply-To: <5m24sfFatlbuU1@mid.uni-berlin.de> References: <5m24sfFatlbuU1@mid.uni-berlin.de> Message-ID: <46FBED79.6070207@comcast.net> Marc 'BlackJack' Rintsch wrote: > On Thu, 27 Sep 2007 12:36:58 -0400, Shawn Minisall wrote: > > >> With the multiple value lines, python says this "ValueError: too many >> values to unpack" >> >> I've googled it and it says that happens when you have too few or too >> many strings that don't match with the variables in number your trying >> to assign them too. Below are the lines in reading in: >> >> line 3 - 19.18 29.15 78.75 212.10 >> line 4 - 100 20 410.29 >> >> And this is the code I'm using: >> >> #read withdrawls from file on line3 >> line = infile.readline() >> >> #split withdrawls up >> withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") >> >> #read deposits from file on line4 >> line = infile.readline() >> #split deposits up >> deposit1, deposit2, deposit3 = string.split(line, "\t") >> >> I have 4 strings to match line 3 and 3 to match the 3 on line 4...any >> thoughts? >> > > First thought is to find out which of the two lines triggers the > exception. This information is part of the full traceback. > > Ciao, > Marc 'BlackJack' Rintsch > Sorry, it looks like it's on the fourth line with the 3 values on line 4...its reading line 3 fine Traceback (most recent call last): File "", line 1, in main() File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line 33, in main deposit1, deposit2, deposit3 = string.split(line, "\t") ValueError: too many values to unpack From mrkafk at gmail.com Sun Sep 30 15:07:15 2007 From: mrkafk at gmail.com (mrkafk at gmail.com) Date: Sun, 30 Sep 2007 12:07:15 -0700 Subject: s.split() on multiple separators In-Reply-To: References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> Message-ID: <1191179235.520749.310670@o80g2000hse.googlegroups.com> > > ['ab', 'd', '', 'ab', '', ''] > > Given your original string, I'm not sure how that would be the > expected result of "split c on the characters in dels". Oops, the inner loop should be: for i in xrange(0,len(c)): Now it works. > >>> c=' abcde abc cba fdsa bcd ' > >>> import re > >>> r = re.compile('[ce ]') > >>> r.split(c) > ['', 'ab', 'd', '', 'ab', '', '', 'ba', 'fdsa', 'b', 'd', ''] > > given that a regexp object has a split() method. That's probably optimum solution. Thanks! Regards, Marcin From knipknap at gmail.com Mon Sep 3 16:38:36 2007 From: knipknap at gmail.com (Samuel) Date: Mon, 03 Sep 2007 13:38:36 -0700 Subject: Python object <-> XML In-Reply-To: References: <1188849714.128121.139450@r34g2000hsd.googlegroups.com> Message-ID: <1188851916.641275.133990@22g2000hsm.googlegroups.com> On Sep 3, 10:19 pm, Jarek Zgoda wrote: > > Is there an easy way (i.e. without writing a sax/dom parser) to load > > this into a (number of) Python object(s), manipulate the instance, and > > save the result back to XML? > > Yea, use ElementTree and you'd get a bunch of nested lists of very > simple objects. Sorry for being unclear. By "load this into a number of Python objects" I mean, filling already existing objects with data. In other words: class Item(object): def __init__(self, ref, name): self.ref = ref self.name = name class Group(object): def __init__(self, ref, name, item = []): self.ref = ref self.name = name self.item = item mapper = Mapper() objects = mapper.load('data.xml') print objects['1'] (Obviously, in my example the mapper could not always know where a list is required, but an existing mapper will surely have a solution implemented.) I guess what I am looking for is pretty much an ORM that also works with XML. -Samuel From x_john at timney.eclipse.co.uk Thu Sep 13 14:13:25 2007 From: x_john at timney.eclipse.co.uk (John Timney (MVP)) Date: Thu, 13 Sep 2007 19:13:25 +0100 Subject: Car-ac-systems References: <1189511932.371621.112970@o80g2000hse.googlegroups.com> <1189661753.315182.53630@22g2000hsm.googlegroups.com> Message-ID: ho ho......now thats quite funny! Regards John Timney (MVP) http://www.johntimney.com http://www.johntimney.com/blog wrote in message news:1189661753.315182.53630 at 22g2000hsm.googlegroups.com... > On Sep 11, 9:35 am, "John Timney \(MVP\)" > wrote: >> How do I control one with C# then! Thats not on your site, clearly not >> everything I need to know then. Waste of a site! > > C# is just as off topic in comp.lang.java.programmer as car air- > conditioning systems. The latter, however, have the redeeming > characteristic that they are not the demonic spawn of evil Microsoft. > From mccredie at gmail.com Tue Sep 18 15:22:40 2007 From: mccredie at gmail.com (Matt McCredie) Date: Tue, 18 Sep 2007 12:22:40 -0700 Subject: Using python to create windows apps that everyone can use? In-Reply-To: <7C008A37566.00000D2Atomharding@inbox.com> References: <7C008A37566.00000D2Atomharding@inbox.com> Message-ID: <9e95df10709181222h31b180faj56d050b8adaea7f1@mail.gmail.com> On 9/18/07, Thomas Harding wrote: > Hi guys, sorry to post another topic on this, as I am aware that it has > already been posted a few times, but not with specifically what I am looking > for. I want an app that makes a gui interface for python (similar to > Microsoft visual studio or qt designer, not a code based one) and/or an app > that can make this into a .exe that can be opened by any person on any > computer without python installed. check out py2exe: http://py2exe.org matt From paul.nospam at rudin.co.uk Wed Sep 5 06:35:05 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 05 Sep 2007 11:35:05 +0100 Subject: creating really big lists References: <1188985838.661821.41530@k79g2000hse.googlegroups.com> <87ejhd2zzt.fsf@rudin.co.uk> <5k7eacF2g23sU2@mid.uni-berlin.de> Message-ID: <874pi92yee.fsf@rudin.co.uk> "Diez B. Roggisch" writes: > Paul Rudin wrote: > >> Dr Mephesto writes: >> >>> Hi! >>> >>> I would like to create a pretty big list of lists; a list 3,000,000 >>> long, each entry containing 5 empty lists. My application will append >>> data each of the 5 sublists, so they will be of varying lengths (so no >>> arrays!). >>> >>> Does anyone know the most efficient way to do this? I have tried: >>> >>> list = [[[],[],[],[],[]] for _ in xrange(3000000)] >>> >>> but its not soooo fast. Is there a way to do this without looping? >> >> You can do: >> >> [[[],[],[],[],[]]] * 3000000 >> >> although I don't know if it performs any better than what you already >> have. > > You are aware that this is hugely different, because the nested lists are > references, not new instances? Thus the outcome is most probably (given the > gazillion of times people stumbled over this) not the desired one... Err, yes sorry. I should try to avoid posting before having coffee in the mornings. From steve at REMOVE-THIS-cybersource.com.au Sat Sep 22 19:50:21 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 22 Sep 2007 23:50:21 -0000 Subject: Getting rid of bitwise operators in Python 3? References: <46f49740$0$32514$4c368faf@roadrunner.com> <1190484589.890198.266430@y42g2000hsy.googlegroups.com> Message-ID: <13fbahtem90fp99@corp.supernews.com> On Sat, 22 Sep 2007 18:09:49 +0000, richyjsm wrote: > On that subject, I'd suggest that the pow() builtin (not the ** operator > - just the pow() function) should also be a candidate for removal... Help on built-in function pow in module __builtin__: pow(...) pow(x, y[, z]) -> number With two arguments, equivalent to x**y. With three arguments, equivalent to (x**y) % z, but may be more efficient (e.g. for longs). Everybody forgets that pow can take three arguments, except of course for those who use that functionality and would be mighty peeved if it went away. -- Steven. From bj_666 at gmx.net Sat Sep 1 15:57:31 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Sep 2007 19:57:31 GMT Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> Message-ID: <5jtuhbF16jr4U2@mid.uni-berlin.de> On Sat, 01 Sep 2007 13:37:29 -0600, Michael L Torrie wrote: > What's wrong, then, with doing: > > if i in list: > print list.index(i) If `i` is in the list this does the linear lookup twice. > If we were to program this .index() method in some language that > enforces contracts, like haskell, then we'd say that .index() expects a > value that exists in the list. So if you violate the contract, why > should you expect to *not* get an exception. Doing it any other way, > though, makes the code a lot more error prone. Does Haskell exceptions? In Haskell I would expect such a function to return the `Maybe` type. Ciao, Marc 'BlackJack' Rintsch From paul.hankin at gmail.com Tue Sep 25 07:19:24 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 25 Sep 2007 11:19:24 -0000 Subject: sorteddict PEP proposal [started off as orderedict] In-Reply-To: <1190710402.481693.5110@50g2000hsm.googlegroups.com> References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> Message-ID: <1190719164.587009.206340@19g2000hsx.googlegroups.com> Recall sorted... sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list So why not construct sorteddicts using the same idea of sortedness? sorteddict((mapping | sequence | nothing), cmp=None, key=None, reverse=None) Then we can specify the exact behaviour of sorteddicts: it's the same as a regular dict, except when the order of keys is important they're ordered as if they were sorted by sorted(keys, cmp=sd._cmp, key=sd._key, reverse=sd._reverse). Here I imagine cmp, key and reverse are stored in the new sorteddict as attributes _cmp, _key, _reverse - obviously the actual implementation may differ. This has the benefit of making sorteddict's behaviour explicit and easy to understand, and doesn't introduce a new sorting API when we already have a perfectly decent one. The only problem here is the **kwargs form of the dict constructor doesn't translate as we're using keyword args to pass in the sort criterion. Perhaps someone has an idea of how this can be solved. If nothing else, this constructor could be dropped for sorteddicts, and sorteddict(dict(**kwargs), cmp=..., key=..., reverse=...) when that behaviour is wanted. I don't like the integral indexing idea or the slicing: indexing and slicing are already part of python and it's bad to have different syntax for the same concept on sorteddicts. I'd say it's not an important enough for sorteddicts anyway. -- Paul Hankin From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Sep 21 07:34:33 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 21 Sep 2007 13:34:33 +0200 Subject: Odd files; just left behind? In-Reply-To: References: <878x725ts7.fsf@pobox.com> <46F191DF.7000908@jessikat.plus.net> <46f2bd9b$0$20143$426a74cc@news.free.fr> <46f3a032$0$26141$426a74cc@news.free.fr> Message-ID: <46f3ac48$0$13496$426a74cc@news.free.fr> Robin Becker a ?crit : > Bruno Desthuilliers wrote: > ........ >>> >>> >>> >>> it would seem simpler to have the .so files inside the site-packages >>> and there's the question of why this folder has to be obfuscated >>> (name starts with .). Even if these files are "resources" why should >>> they be assumed to belong to the user? >> >> Notice that you did install your lib/python in /myhome, not in >> /usr[/local] > > yes, so should I then assume that the root installs will put all the .so > files in /usr/local/lib/.python-eggs? > > In fact when I look at my root installed pythons they seem quite happy > to put the _mysql.so underneath site-packages. I suspect that if I just > installed from source I'd get that behaviour, but the egg stuff is > different. > >> >> (snip) >>> Just another nonsense from the eggworld >> >> Or just another example of not reading the FineManual(tm) ? > > well I didn't write the installer or the associated egg setup. The egg > things are supposed to do the right thing, but perhaps they're too > difficult for the egg layers. Can't tell. So far, I've had no problem with eggs, so... From nutsbreaker1 at gmail.com Tue Sep 11 09:05:22 2007 From: nutsbreaker1 at gmail.com (nutsbreaker1 at gmail.com) Date: Tue, 11 Sep 2007 13:05:22 -0000 Subject: Go Here to win a free guitar Message-ID: <1189515922.183328.245430@k79g2000hse.googlegroups.com> http://freeguitars.blogspot.com/ From kw at codebykevin.com Thu Sep 27 10:20:15 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 27 Sep 2007 10:20:15 -0400 Subject: Tkinter / Tk 8.5 In-Reply-To: References: Message-ID: <46FBBC1F.5010408@codebykevin.com> Michal Bozon wrote: > Today has been released a first beta of Tk 8.5, including a Ttk > (tile) style engine, which makes possible the native look > of widgets on MS > platform, without having to install any extension. > > http://wiki.tcl.tk/11075 > http://sourceforge.net/mailarchive/message.php?msg_name=1190813039.46fa5d6f6a06b%40webmail.nist.gov > > Is there a chance it will be included in 2.5.x, 2.6 or 3.0 ? > > -m. Did you know that a wrapper for use with Tk 8.4.x is located here? http://tkinter.unpythonic.net/wiki/TileWrapper This does require a separate installation of the Tile libraries, but those can be obtained from ActiveState. I use this wrapper myself on OS X with a commercial application I develop, and Tile makes a big difference. (I maintain and update this wrapper at the wiki, but am not the original author.) --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From simon at brunningonline.net Thu Sep 27 12:48:44 2007 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 27 Sep 2007 17:48:44 +0100 Subject: True of False In-Reply-To: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> Message-ID: <8c7f10c60709270948l3cecc08ds133004ed4709edc3@mail.gmail.com> On 9/27/07, koutoo at hotmail.com wrote: > I tried writing a true and false If statement and didn't get > anything? I read some previous posts, but I must be missing > something. I just tried something easy: > > a = ["a", "b", "c", "d", "e", "f"] > > if "c" in a == True: > Print "Yes" > > When I run this, it runs, but nothing prints. What am I doing wrong? Just use if "c" in a: and all will be well. The True object isn't the only truthy value in Python - see . -- Cheers, Simon B. simon at brunningonline.net From aleax at mac.com Sat Sep 1 21:38:59 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 1 Sep 2007 18:38:59 -0700 Subject: status of Programming by Contract (PEP 316)? References: <1188349440.309634.182800@z24g2000prh.googlegroups.com> <-OadnXBZP4QfaknbnZ2dnUVZ_tHinZ2d@comcast.com> <1188364909.397692.209170@q4g2000prc.googlegroups.com> <1188367108.393207.241970@g4g2000hsf.googlegroups.com> <1188369928.755777.142690@i38g2000prf.googlegroups.com> <46d75191$0$401$426a74cc@news.free.fr> <1188518054.298017.90610@x35g2000prf.googlegroups.com> <46d76595$0$4013$426a74cc@news.free.fr> <7xlkbsmqe4.fsf@ruckus.brouhaha.com> <1188525647.003223.199620@q5g2000prf.googlegroups.com> <1188537516.622167.115080@z24g2000prh.googlegroups.com> Message-ID: <1i3rxit.1750ghi14bbcm3N%aleax@mac.com> Ricardo Ar?oz wrote: ... > We should remember that the level > of security of a 'System' is the same as the level of security of it's > weakest component, Not true (not even for security, much less for reliability which is what's being discussed here). It's easy to see how this assertion of yours is totally wrong in many ways... Example 1: a toy system made up of subsystem A (which has a probability of 90% of working right) whose output feeds into subsystem B (which has a probability of 80% of working right). A's failures and B's faliures are statistically independent (no common-mode failures, &c). The ``level of goodness'' (probability of working right) of the weakest component, B, is 80%; but the whole system has a ``level of goodness'' (probability of working right) of just 72%, since BOTH subsystems must work right for the whole system to do so. 72 != 80 and thus your assertion is false. More generally: subsystems "in series" with independent failures can produce a system that's weaker than its weakest component. Example 2: another toy system made up of subsystems A1, A2 and A3, each trying to transform the same input supplied to all of them into a 1 bit result; each of these systems works right 80% of the time, statistically independently (no common-mode failures, &c). The three subsystems' results are reconciled by a simple majority-voting component M which emits as the system's result the bit value that's given by two out of three of the Ai subsystems (or, of course, the value given unanimously by all) and has extremely high reliability thanks to its utter simplicity (say 99.9%, high enough that we can ignore M's contribution to system failures in a first-order analysis). The whole system will fail when all Ai fail together (probability 0.2**3) or when 2 out of them fail while the hird one is working (probability 3*0.8*0.2**2): >>> 0.2**3+3*0.2**2*0.8 0.10400000000000004 So, the system as a whole has a "level of goodness" (probability of working right) of almost 90% -- again different from the "weakest component" (each of the three Ai's), in this case higher. More generally: subsystems "in parallel" (arranged so as to be able to survive the failure of some subset) with indipendent failures can produce a system that's stronger than its weakest component. Even in the field of security, which (changing the subject...) you specifically refer to, similar considerations apply. If your assertion was correct, then removing one component would never WEAKEN a system's security -- it might increase it if it was the weakest, otherwise it would leave it intact. And yet, a strong and sound tradition in security is to require MULTIPLE components to be all satisfied e.g. for access to secret information: e.g. the one wanting access must prove their identity (say by retinal scan), possess a physical token (say a key) AND know a certain secret (say a password). Do you really think that, e.g., removing the need for the retinal scan would make the system's security *STRONGER*...? It would clearly weaken it, as a would-be breaker would now need only to purloin the key and trick the secret password out of the individual knowing it, without the further problem of falsifying a retinal scan successfully. Again, such security systems exist and are traditional exactly because they're STRONGER than their weakest component! So, the implication accompanying your assertion, that strenghtening a component that's not the weakest one is useless, is also false. It may indeed have extremely low returns on investment, depending on system's structure and exact circumstances, but then again, it may not; nothing can be inferred about this ROI issue from the consideration in question. Alex From ivoras at _fer.hr_ Wed Sep 12 06:34:49 2007 From: ivoras at _fer.hr_ (Ivan Voras) Date: Wed, 12 Sep 2007 12:34:49 +0200 Subject: Python 3K or Python 2.9? In-Reply-To: <46e7974d$0$31726$426a74cc@news.free.fr> References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > TheFlyingDutchman a ?crit : >> Python user and advocate Bruce Eckel is disappointed with the >> additions (or lack of additions) in Python 3: >> >> http://www.artima.com/weblogs/viewpost.jsp?thread=214112 > > I'd say Mr Eckel fails to graps some of the great points about Python's > object model - the rant about the use of 'self' is a sure clue. What does "self" have to do with an object model? It's an function/method argument that might as well be hidden in the compiler without ever touching the role it has (if not, why?). I agree that it's needless noise in a language. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 257 bytes Desc: OpenPGP digital signature URL: From tjreedy at udel.edu Sun Sep 9 17:07:37 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Sep 2007 17:07:37 -0400 Subject: Modul (%) in python not like in C? References: <880dece00709091201n449d4c2k31998a5d426de17d@mail.gmail.com> Message-ID: "Dotan Cohen" wrote in message news:880dece00709091201n449d4c2k31998a5d426de17d at mail.gmail.com... | FIrst of all, how is the % symbol (as in 70%6=4) called in English? | | Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or | the other in error? Is this a known gotcha? I tried to google the | subject however one cannot google the symbol %. Thanks in advance. Call it a known gotcha inherent to integers. In the realm of counts (aka non-negative integers), there is one sensible definition of division and modulus (remainder). It has various nice properties. With mixed positive and negative integers, there are choices, and none have all the nice properties. The basic problem is that '-infinity' and 0 are in opposite directions instead of the same direction ;-). Guido made one consistent choice (which matches some other languages, I believe). Others have made another consistent choice or no choice at all (leaving the choice to implementations). I believe I have seen at least one book, if not language, that defined // and % so that remainders have the same sign as the numerator. (Or was it denominator?) tjr From sisson.j at gmail.com Thu Sep 6 13:55:52 2007 From: sisson.j at gmail.com (J Sisson) Date: Thu, 6 Sep 2007 12:55:52 -0500 Subject: Beginners Query - Simple counter problem In-Reply-To: References: Message-ID: <4297a9020709061055o5c09213wb16d400842f0825b@mail.gmail.com> Silly question, but are you importing random somewhere in that file? It works on both my XP machine and my Linux machine (both from CLI) after importing random...though it runs through this: while count <= i: i + 1 times...(You initialize count to 0, then loop over it until it hits i+1 (at which point the while breaks), which means if you run d6(3), you're actually getting back random.randint(1,6) x 4, not x3 (as would be expected)). Initializing count to 1 will fix that, or you could change the while to: while count < i: Either way works. Jonathon On 9/6/07, David Barr wrote: > > I am brand new to Python (this is my second day), and the only > experience I have with programming was with VBA. Anyway, I'm posting > this to see if anyone would be kind enough to help me with this (I > suspect, very easy to solve) query. > > The following code is in a file which I am running through the > interpreter with the execfile command, yet it yeilds no results. I > appreciate I am obviously doing something really stupid here, but I > can't find it. Any help appreciated. > > > def d6(i): > roll = 0 > count = 0 > while count <= i: > roll = roll + random.randint(1,6) > count += 1 > > return roll > > print d6(3) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Computers are like air conditioners... They quit working when you open Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From m.n.summerfield at googlemail.com Fri Sep 14 16:00:45 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Fri, 14 Sep 2007 20:00:45 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> <1189753968.917636.310120@19g2000hsx.googlegroups.com> Message-ID: <1189800045.642278.313860@o80g2000hse.googlegroups.com> On 14 Sep, 20:25, James Stroud wrote: > Mark Summerfield wrote: [snip] > May I also make one more suggestion, to call it a "sort_ordered_dict" > (or "sortordereddict", or even better a "sorteddict"--where the "ed" > comes from "ordered")? Its hard for me to move past the established > definition of "order", as we think of tuples being ordered--as in the > first sentence ofhttp://en.wikipedia.org/wiki/Tuple--tosomething that > is preserving an order according to a comparison. The distinction is so > firmly ingrained in my head that it took me a while to wake up to the > fact that you were describing something completely different than an > ordered dictionary (e.g.http://www.voidspace.org.uk/python/odict.html) > even though you were being very unambiguous with your description. > > And I also think the ability to drop it in for a built-in dict is very > valuable. > > James It seems that the correct Python terminology for this is indeed sorteddict (ordered by key), with ordereddict meaning (in insertion order). I guess I'll have to rename my module (although unfortunately, my book has just gone into production and I have a (simpler) example of what I considered to be an ordered dict, so I will be adding to the terminology confusion). That notwithstanding, given that it is a sorteddict, how is the API? From martin at v.loewis.de Tue Sep 11 17:10:11 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 11 Sep 2007 23:10:11 +0200 Subject: Compiler Python In-Reply-To: References: <000001c7f4a2$307fa720$917ef560$@com> Message-ID: <46e70434$0$16384$9b622d9e@news.freenet.de> > Someone knows since as I can obtain the information detailed about the > compiler of Python? (Table of tokens, lists of productions of the > syntactic one , semantic restrictions...) The EBNF grammar is in Grammar/Grammar; this also implies the list of tokens. Another list of tokens in Include/token.h. The semantic restrictions are mostly implemented as SyntaxError. These are raised under various circumstances - search the code for SyntaxError, for details. Regards, Martin From jzgoda at o2.usun.pl Mon Sep 3 16:19:52 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 03 Sep 2007 22:19:52 +0200 Subject: Python object <-> XML In-Reply-To: <1188849714.128121.139450@r34g2000hsd.googlegroups.com> References: <1188849714.128121.139450@r34g2000hsd.googlegroups.com> Message-ID: Samuel napisa?(a): > Say you have the following XML: > > > item 1 > > > item 2 > > > > > my group > > > Is there an easy way (i.e. without writing a sax/dom parser) to load > this into a (number of) Python object(s), manipulate the instance, and > save the result back to XML? Yea, use ElementTree and you'd get a bunch of nested lists of very simple objects. -- Jarek Zgoda http://jpa.berlios.de/ From ironfroggy at gmail.com Fri Sep 28 09:17:54 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Fri, 28 Sep 2007 09:17:54 -0400 Subject: Importing Module To Use Variables In A Second Module In-Reply-To: References: Message-ID: <76fd5acf0709280617s5a934b8cl459d92a428bdbdd5@mail.gmail.com> Most problems like this are caused by trying to access the attributes of the module before that module is fully executed, and thus before they are defined. For example, if you have A.py: import B data = "TEST" And B.py: import A print A.data Now, if you run A,py, it will import B before it defines its global variable 'data', so that when the B module tries to import A and then print A.data, it has not been defined yet. Look into the possibility that such an import loop is occurring in your code. You can import in loops, but not if you access things defined globally in one from a global scope in another. On 27 Sep 2007 21:30:10 GMT, rshepard at nospam.appl-ecosys.com wrote: > I'm stymied by what should be a simple Python task: accessing the value of > a variable assigned in one module from within a second module. I wonder if > someone here can help clarify my thinking. I've re-read Chapter 16 (Module > Basics) in Lutz and Ascher's "Learning Python" but it's not working for me. > > In one module (the "source"), variablePage.py, three wxPython widgets > display values that are assigned to variables: curVar, UoDlow, and UoDhigh. > I want to display then in equivalent widgets on a wxPython notebook tab in a > different module, the "importer." > > At the top of the importer module I have: > > from variablePage import curVar, UoDlow, UoDhigh > > and I try to display the values of those variables in widgets on this page. > But, python complains: > > from variablePage import curVar, UoDlow, UoDhigh > ImportError: cannot import name curVar > > I've also tried > > import variablePage as VP > > and referenced the variables as VP.curVar, VP.UoDlow, and VP.UoDhigh, but > python still doesn't like this: > > File "/data1/eikos/fuzSetPage.py", line 364, in loadParVar > first = VP.curVar > AttributeError: 'module' object has no attribute 'curVar' > > Both of these forms are used in the book (pages 260-261) in simple > examples. I also get errors if I try importing using the class name before > the variable name. > > A clue stick would be very helpful since I am not seeing just what I'm > doing incorrectly. > > Rich > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From bbxx789_05ss at yahoo.com Fri Sep 21 03:38:24 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 21 Sep 2007 00:38:24 -0700 Subject: newb: BeautifulSoup In-Reply-To: <1190343890.375836.78630@r29g2000hsg.googlegroups.com> References: <1190343890.375836.78630@r29g2000hsg.googlegroups.com> Message-ID: <1190360304.800016.219320@k79g2000hse.googlegroups.com> On Sep 20, 9:04 pm, crybaby wrote: > I need to traverse a html page with big table that has many row and > columns. For example, how to go 35th td tag and do regex to retireve > the content. After that is done, you move down to 15th td tag from > 35th tag (35+15) and do regex to retrieve the content? 1) You can find your table using one of these methods: a) target_table = soup.find('table', id='car_parts') b) tables = soup.findall('table') target_table = tables[2] The tables are put in a list in the order that they appear on the page. 2) You can get all the td's in the table using this statement: all_tds = target_table.findall('td') 3) You can get the contents of the tags using these statements: print all_tds[34].string print all_tds[49].string Here is an example: from BeautifulSoup import BeautifulSoup doc = """
hello
worldgoodbye
""" soup = BeautifulSoup(doc) tables = soup.findAll('table') target_table = tables[1] all_tds = target_table.findAll('td') print all_tds[0].string print all_tds[2].string --output:-- hello goddbye From adonisv at REMOVETHISearthlink.net Mon Sep 24 20:25:09 2007 From: adonisv at REMOVETHISearthlink.net (Adonis Vargas) Date: Mon, 24 Sep 2007 20:25:09 -0400 Subject: is there some module update(install tools)? In-Reply-To: <8520e$46f83ee4$4df9f6c6$14843@news2.tudelft.nl> References: <8520e$46f83ee4$4df9f6c6$14843@news2.tudelft.nl> Message-ID: <13fglb5p4bo82c7@corp.supernews.com> hyena wrote: > Hi, > > I am quite new to python and am looking for some tools that can > install and update modules a bit more intelligent then "python setup.py > install". Is there some thing like "yum" in fedora which can search and > install/update packages automatically? > > thanks in advance! setuptools is for you http://peak.telecommunity.com/DevCenter/setuptools Once installed, its easy as easy_install Hope this helps. Adonis Vargas From mouseit101 at gmail.com Fri Sep 14 23:45:57 2007 From: mouseit101 at gmail.com (mouseit) Date: Sat, 15 Sep 2007 03:45:57 -0000 Subject: List append In-Reply-To: <1189827762.011325.315840@r29g2000hsg.googlegroups.com> References: <1189826727.204061.310380@d55g2000hsg.googlegroups.com> <1189827762.011325.315840@r29g2000hsg.googlegroups.com> Message-ID: <1189827957.630379.54070@g4g2000hsf.googlegroups.com> On Sep 14, 11:42 pm, Stephen wrote: > In your code, "array" is a class attribute, so it is shared among all > instances. You need to use the __init__ method to define instance > (data) attributes instead: > > def __init__(self): > self.array = [] > > On Sep 14, 11:25 pm, mouseit wrote: > > > I'm trying to add an element to a list which is a property of an > > object, stored in an array. When I append to one element, all of the > > lists are appended! > > > Example Code: > > > class Test: > > array = [] > > > myTests = [Test() , Test() , Test()] > > print len(myTests[1].array) > > myTests[0].array.append( 5 ) > > print len(myTests[1].array) > > > prints: > > 0 > > 1 > > > This is probably a really easy question (I'm very new to python), so > > thanks in advance for your help! Awsome, that worked. Thanks! From hniksic at xemacs.org Fri Sep 28 20:12:24 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 29 Sep 2007 02:12:24 +0200 Subject: Can I overload the compare (cmp()) function for a Lists ([]) index function? References: <1191000652.430036.288400@y42g2000hsy.googlegroups.com> Message-ID: <87tzpel47r.fsf@mulj.homelinux.net> xkenneth writes: > Looking to do something similair. I'm working with alot of timestamps > and if they're within a couple seconds I need them to be indexed and > removed from a list. > Is there any possible way to index with a custom cmp() function? > > I assume it would be something like... > > list.index(something,mycmp) The obvious option is reimplementing the functionality of index as an explicit loop, such as: def myindex(lst, something, mycmp): for i, el in enumerate(lst): if mycmp(el, something) == 0: return i raise ValueError("element not in list") Looping in Python is slower than looping in C, but since you're calling a Python function per element anyway, the loop overhead might be negligible. A more imaginative way is to take advantage of the fact that index uses the '==' operator to look for the item. You can create an object whose == operator calls your comparison function and use that object as the argument to list.index: class Cmp(object): def __init__(self, item, cmpfun): self.item = item self.cmpfun = cmpfun def __eq__(self, other): return self.cmpfun(self.item, other) == 0 # list.index(Cmp(something, mycmp)) For example: >>> def mycmp(s1, s2): ... return cmp(s1.tolower(), s2.tolower()) >>> ['foo', 'bar', 'baz'].index(Cmp('bar', mycmp)) 1 >>> ['foo', 'bar', 'baz'].index(Cmp('Bar', mycmp)) 1 >>> ['foo', 'bar', 'baz'].index(Cmp('nosuchelement', mycmp)) Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list The timeit module shows, somewhat surprisingly, that the first method is ~1.5 times faster, even for larger lists. From horpner at yahoo.com Mon Sep 3 01:05:11 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 03 Sep 2007 05:05:11 GMT Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188743299.664137.194760@d55g2000hsg.googlegroups.com> <46daeaec$0$19889$426a74cc@news.free.fr> <46DB04DD.80801@v.loewis.de> <46db085d$0$16113$9b4e6d93@newsspool1.arcor-online.net> <13dmctogeh19410@corp.supernews.com> Message-ID: On 2007-09-02, Steven D'Aprano wrote: > A big question mark in my mind is Lisp, which according to > aficionados is just as dynamic as Python, but has native > compilers that generate code running as fast as highly > optimized C. I'm not qualified to judge whether the lessons > learnt from Lisp can be applied to Python, but in any case Lisp > is an old, old language -- only Fortran is older. The amount of > development effort and money put into Lisp dwarfs that put into > Python by possibly a hundred or more. Lisp, as far as I know, requires type declarations, discipline, deep knowledge of Lisp, and more than passing knowledge of your Lisp implementation in order to generate code that's competitive with C. On the other hand, Lisp afficionados don't have a problem meeting those requirements. ;) > So... if you'd like to see Python run as fast as C or Lisp, and > you have a few tens of millions of dollars spare to invest in > development, I think the Python Software Foundation would love > to hear from you. Hmmm. I have four dollars... almost five... -- Neil Cerutti From bozonm at vscht.cz Wed Sep 26 20:24:14 2007 From: bozonm at vscht.cz (Michal Bozon) Date: Thu, 27 Sep 2007 02:24:14 +0200 Subject: ~ bit-wise unary operator References: Message-ID: cau, maybe int is represented internally as a signed integer you can use numpy types: >>> import numpy >>> ~ numpy.uint16(7978) 57557 -m. On Thu, 27 Sep 2007 00:14:49 +0200, Ladislav Andel wrote: > Hello, > why ~ bit-wise unary operator returns -(x+1) and not bit inversion of > the given integer? > > example: > a = 7978 > a = ~a > python returns -7979 > > but I need to get back 57557 as in C language. > > which is also in binary > 0001111100101010 > and inverted > 1110000011010101 > > Is here any other operator or do I have to write it on my own? > > Thank you, > Lada From jelleferinga at gmail.com Thu Sep 6 14:18:00 2007 From: jelleferinga at gmail.com (jelle) Date: Thu, 06 Sep 2007 18:18:00 -0000 Subject: initializing cooperative method In-Reply-To: <13e0bgg5lo0p2ec@corp.supernews.com> References: <1189095131.853954.233660@r34g2000hsd.googlegroups.com> <13e0bgg5lo0p2ec@corp.supernews.com> Message-ID: <1189102680.957512.152950@k79g2000hse.googlegroups.com> Ai, calling super(Abstract) is just getting object, sure... However, I'm still curious to know if there's a good idiom for repeating the argument in __init__ for the super(Concrete, self).__init__ ? Thanks, -jelle From mickey at disney.com Fri Sep 7 21:58:21 2007 From: mickey at disney.com (Wiseman) Date: Fri, 07 Sep 2007 21:58:21 -0400 Subject: Python Problem Message-ID: Hi, The line: import enchant works perfectly OK when I call a Python progrma (sp.py) from IDLE (WInXP). When I try to run it ftom the command line (python sp.py) the response is: Traceback (most recent call last): File "sp.py", line 3, in import enchant ImportError: No module named enchant Searching my computer (the whole of drive c:\) I could not find ANY file called enchant.*. Does anyone know what is wrong? Thanks ((:-() Meir From hat at se-162.se.wtb.tue.nl Wed Sep 12 03:09:02 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 12 Sep 2007 09:09:02 +0200 Subject: Python Problem References: Message-ID: On 2007-09-11, Wiseman wrote: > > Hi, > > OK - it works in WindowsXP. > I installed "enchant" on my SuSE 10.0 (using YAST). > The enchant Suse package looks like a general Linux package, not a > Python specific. You'd seem to be right judging by this web-page: http://www.novell.com/products/linuxpackages/suselinux/enchant.html As you can see, there is no file installed at a path with "python" in it. > What am I missing? Python bindings to the library perhaps? You may be more lucky with an enchant-dev package (if it exists). I am however not a Suse user and not an echant user (well, not from my Python code at least). Albert From rshepard at nospam.appl-ecosys.com Thu Sep 27 17:30:10 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 27 Sep 2007 21:30:10 GMT Subject: Importing Module To Use Variables In A Second Module Message-ID: I'm stymied by what should be a simple Python task: accessing the value of a variable assigned in one module from within a second module. I wonder if someone here can help clarify my thinking. I've re-read Chapter 16 (Module Basics) in Lutz and Ascher's "Learning Python" but it's not working for me. In one module (the "source"), variablePage.py, three wxPython widgets display values that are assigned to variables: curVar, UoDlow, and UoDhigh. I want to display then in equivalent widgets on a wxPython notebook tab in a different module, the "importer." At the top of the importer module I have: from variablePage import curVar, UoDlow, UoDhigh and I try to display the values of those variables in widgets on this page. But, python complains: from variablePage import curVar, UoDlow, UoDhigh ImportError: cannot import name curVar I've also tried import variablePage as VP and referenced the variables as VP.curVar, VP.UoDlow, and VP.UoDhigh, but python still doesn't like this: File "/data1/eikos/fuzSetPage.py", line 364, in loadParVar first = VP.curVar AttributeError: 'module' object has no attribute 'curVar' Both of these forms are used in the book (pages 260-261) in simple examples. I also get errors if I try importing using the class name before the variable name. A clue stick would be very helpful since I am not seeing just what I'm doing incorrectly. Rich From bj_666 at gmx.net Sat Sep 8 04:42:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Sep 2007 08:42:51 GMT Subject: python sqlite THREADSAFE? References: Message-ID: <5kf5kbF33dv5U2@mid.uni-berlin.de> On Sat, 08 Sep 2007 10:37:51 +0200, EuGeNe Van den Bulke wrote: > Is the sqlite distributed with Python 2.5 compiled with the > -DTHREADSAFE=1 flag? My gutt feeling is Windows (yes) MacOS/Linux (no) > but ... Take a look at the `threadsafety` attribute of the module. Ciao, Marc 'BlackJack' Rintsch From michele.simionato at gmail.com Fri Sep 7 02:01:30 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 07 Sep 2007 06:01:30 -0000 Subject: concise code (beginner) In-Reply-To: <13dv4uqqb806ff0@corp.supernews.com> References: <13dsvqrqivtf092@corp.supernews.com> <13dv4uqqb806ff0@corp.supernews.com> Message-ID: <1189144890.994819.55200@w3g2000hsg.googlegroups.com> On Sep 6, 7:44 am, "bambam" wrote: > First, thank you. > > All of the suggestions match what we want to do much better > than what we are doing. We have a script, written in python, > which is doing testing. But the python script doesn't look anything > like the test script, because the python script is written in python, > and the test script is a series of instrument command macros. > > By putting the script sequence into a collection that is separate > from the python code, we will get script list that general engineering > will find much easier to understand: > > def script(self) > def a0010(): global self; self.power_on([self.dev]); > def a0020(): global self; self.dev.addLog([self.name, ' started']); > def a0030(): global self; self.resetMinuteReg([self.dev]); > def a0040(): global self; self.disablePLmessages([self.dev]); > def a0050(): global self; self.dev.testH.writePLram((PL.BCAL12<<8)); Look at generative tests in py.test or nose: they are a much better solution for what you are doing. Michele Simionato From http Sat Sep 22 23:14:20 2007 From: http (Paul Rubin) Date: 22 Sep 2007 20:14:20 -0700 Subject: Factory function with keyword arguments References: <13fbl9ertj5es12@corp.supernews.com> Message-ID: <7xejgqysxf.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > def factory(flag): > if flag: kw = 'spam' > else: kw = 'ham' > def foo(obj, arg): > kwargs = dict([(kw, arg)]) > return obj.method(**kwargs) > return foo Untested: def factory(flag): def foo(obj, arg): p = 'spam' if flag else 'ham' return obj.method(**{p:arg}) return foo is the obvious way in that style. From Brian.McCann at viziant.net Fri Sep 7 14:11:14 2007 From: Brian.McCann at viziant.net (Brian McCann) Date: Fri, 7 Sep 2007 14:11:14 -0400 Subject: passing command line arguments References: <93066C069973ED448DC2BCEA9C44A7383BE32D@efmailx> <200709071158.35779.bulliver@badcomputer.org> Message-ID: <93066C069973ED448DC2BCEA9C44A7383BE330@efmailx> Darren, Thanks ________________________________ From: python-list-bounces+brian.mccann=viziant.net at python.org on behalf of darren kirby Sent: Fri 9/7/2007 1:58 PM To: python-list at python.org Subject: Re: passing command line arguments quoth the Brian McCann: > Hi, > > when I run the script show_args2.py > > # ./show_args2.py 1 2 3 > > I get the following error > > Traceback (most recent call last): > File "./show_args2.py", line 4, in ? > print 'The arguments of %s are "%s"' %s \ > NameError: name 's' is not defined > > > ##################################### > > this is the script > #!/usr/bin/python > import sys, string > print 'The arguments of %s are "%s"' %s \ > (sys.argv[0], string.join(sys.argv[1:])) You don't want the 's' on the last format operator. Try: print 'The arguments of %s are "%s"' % \ (sys.argv[0], string.join(sys.argv[1:])) > any help would be greatly appreciated > > -Brian -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Fri Sep 7 08:03:23 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Sep 2007 12:03:23 -0000 Subject: Generating a unique identifier Message-ID: <13e2fgbbpsatm39@corp.supernews.com> I have an application that will be producing many instances, using them for a while, then tossing them away, and I want each one to have a unique identifier that won't be re-used for the lifetime of the Python session. I can't use the id() of the object, because that is only guaranteed to be unique during the lifetime of the object. For my application, it doesn't matter if the ids are predictable, so I could do something as simple as this: def unique_id(): n = 1234567890 while True: yield n n += 1 unique_id = unique_id() while Application_Is_Running: make_an_object(id=unique_id()) do_stuff_with_objects() delete_some_of_them() which is easy enough, but I thought I'd check if there was an existing solution in the standard library that I missed. Also, for other applications, I might want them to be rather less predictable. -- Steven. From bignose+hates-spam at benfinney.id.au Fri Sep 21 10:07:28 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 22 Sep 2007 00:07:28 +1000 Subject: SHOCK: WHY None? References: <1190383137.015553.235870@o80g2000hse.googlegroups.com> Message-ID: <87ps0cru1r.fsf@benfinney.id.au> n00m writes: > def f(i,sm): > if i+1==len(a): > print sm+a[i] > return sm+a[i] > else: > f(i+1,sm+a[i]) > > a=[1,2,3,4,5] > > print f(0,0) > > >>> > 15 > None > >>> Here's one to meditate on: >>> def foo(): ... print "foo" ... >>> print foo() foo None >>> def bar(): ... return "bar" ... >>> print bar() bar >>> def baz(): ... pass ... >>> print baz() None It should be fairly clear how these three are different. If not, I suspect you haven't worked your way through the Python tutorial; please do so. -- \ "Are you pondering what I'm pondering?" "Well, I think so, | `\ Brain, but if Jimmy cracks corn, and no one cares, why does he | _o__) keep doing it?" -- _Pinky and The Brain_ | Ben Finney From robert.kern at gmail.com Fri Sep 7 15:43:10 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 07 Sep 2007 14:43:10 -0500 Subject: Python and CUDO In-Reply-To: <1189148811.336283.72920@50g2000hsm.googlegroups.com> References: <46E05DC0.7090102@glocalnet.net> <1189148811.336283.72920@50g2000hsm.googlegroups.com> Message-ID: Paddy wrote: > On Sep 6, 10:12 pm, Robert Kern wrote: >> Veronika Lindstrand Kant wrote: >>> Hi! >>> I just wonder if there are any plans for building any support using >>> NIVIDAS CUDO plattform into python? >> Not into Python itself, but we are working on interfacing with NVIDIA's CUDA, >> yes (presuming you actually meant "NVIDIA's CUDA" rather than "NIVIDAS CUDO"). >> >> http://code.google.com/p/pystream/ >> >> -- >> 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 > > Maybe you and the CorePy guys at http://www.corepy.org/ could swap > notes and give us a similar way to work with these accellerators? We had a productive discussion at the SciPy '07 conference. -- 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 martin at v.loewis.de Mon Sep 3 23:46:35 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 04 Sep 2007 05:46:35 +0200 Subject: py3k - format specifier for strings In-Reply-To: References: Message-ID: <46DCD51B.7040508@v.loewis.de> >>>> a = "{0}".format(5.66) >>>> a > '5.66' > > There are more options in PEP 3101 (fill, alignment, etc.), but I'm having > trouble implementing them. It would be good if you could describe these troubles in more detail. What have you been trying, what happened, and what did you expect to happen instead? > Any help in the way of examples would be appreciated. >From test_unicode.py: "My name is {0}".format('Fred') "My name is {0[name]}".format(dict(name='Fred') "My name is {0} :-{{}}".format('Fred') d = datetime.date(2007, 8, 18) "The year is {0.year}".format(d) '{0:.3s}'.format('abc') '{0:.0s}'.format('abcdef') '{0:3.3s}'.format('abc') '{0:3.2s}'.format('abc') '{0:x<0s}'.format('result') '{0:x<7s}'.format('result') '{0:^10s}'.format('result') '{0!s}'.format('Hello') '{0!s:15s}'.format('Hello') '{0!r:}'.format('Hello') Regards, Martin From pavlovevidence at gmail.com Thu Sep 13 21:36:25 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Sep 2007 18:36:25 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> Message-ID: <1189733785.813953.77370@k79g2000hse.googlegroups.com> On Sep 13, 4:20 pm, James Stroud wrote: > Mark Summerfield wrote: > > - If an item is inserted it is put in the right place (because the > > underlying data structure, b*tree, skiplist or whatever is > > intrinsically ordered by < on the key) > > +1 for all your suggestions below, but -1 for the above. You suggest that > > myOrderedDict['key'] = value > > would place it in the dictionary in sorted order depending on 'key'. > More natural to some of us (or maybe its just me) would be to append the > key/value pair to the end of items. Or, maybe, like, you know, you could have two different types that maintain two different orders? Carl Banks From steve at holdenweb.com Tue Sep 4 01:10:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Sep 2007 01:10:22 -0400 Subject: So what exactly is a complex number? In-Reply-To: References: Message-ID: Roy Smith wrote: > Boris Borcic wrote: >> Complex numbers are like a subclass of real numbers > > I wouldn't use the term "subclass". It certainly doesn't apply in the same > sense it applies in OOPLs. For example, you can't say, "All complex > numbers are real numbers". In fact, just the opposite. > > But, it's equally wrong to say, "real numbers are a subclass of complex > numbers", at least not if you believe in LSP > (http://en.wikipedia.org/wiki/Liskov_substitution_principle). For example, > it is true that you can take the square root of all complex numbers. It is > not, however, true that you can take square root of all real numbers. > That's not true. I suspect what you are attempting to say is that the complex numbers are closed with respect to the square root operation, but the reals aren't. Clearly you *can* take the square root of all real numbers, since a real number *is* also a complex number with a zero imaginary component. They are mathematically equal and equivalent. > Don't confuse "subset" with "subclass". The set of real numbers *is* a > subset of the set of complex numbers. It is *not* true that either reals > or complex numbers are a subclass of the other. I don't think "subclass" has a generally defined meaning in mathematics (though such an assertion from me is usually a precursor to someone presenting evidence of my ignorance, so I should know better than to make them). obpython: I have always thought that the "key widening" performed in dictionary lookup is a little quirk of the language: >>> d = {2: "indeedy"} >>> d[2.0] 'indeedy' >>> d[2.0+0j] 'indeedy' >>> but it does reflect the fact that the integers are a subset of the reals, which are (as you correctly point out) a subset of the complexes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From thorsten at thorstenkampe.de Sat Sep 15 01:16:42 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 15 Sep 2007 13:16:42 +0800 Subject: Https conversation - debug? References: <1189799482.314951.238470@r34g2000hsd.googlegroups.com> Message-ID: * Johny (Fri, 14 Sep 2007 12:51:22 -0700) > Is there any good sniffer for https protocol? What's the connection to Python? > How can be watched https conversation? ssldump. Note that in order to decrypt the traffic you need to have the server's private key. From tjreedy at udel.edu Fri Sep 14 13:06:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Sep 2007 13:06:03 -0400 Subject: recursion References: <5kvbn3F5h7l3U1@mid.uni-berlin.de> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:5kvbn3F5h7l3U1 at mid.uni-berlin.de... | f([1, 2, 3]) | r1 f([2, 3]) + [1] | r2 f([3]) + [2] + [1] | r3 f([]) + [3] + [2] + [1] | r4 [] + [3] + [2] + [1] I might help to note that the above is effectively parenthesized ( ( ([]+{3]) + [2]) +[1]) *and* that each addition (in each pair of parentheses) is done in a different execution frame (see below). | And now the calls return: | | r3 [3] + [2] + [1] | r2 [3, 2] + [1] | r1 [3, 2, 1] | > [3, 2, 1] # how this come here? how python save variables from each | > recursion? *Each time* a function is called, an execution frame is created(1) that is separate from the function object itself. Each execution frame has its own set of local variables. In particular, each has its own slices of the original list. There have been languages, for instance, Fortran IV, where local variables were part of the function 'object' and which therefore prohibited recursion because of the very problem you alluded to in your question. (My guess is the functions had an InUse flag that was checked when the function was called.) tjr (1) A minor variation would be for function objects to have one pre-allocated execution frame for non-recursive calls and others allocated as needed for recursive calls. From daniel.j.larsson at gmail.com Sun Sep 16 10:47:13 2007 From: daniel.j.larsson at gmail.com (Daniel Larsson) Date: Sun, 16 Sep 2007 16:47:13 +0200 Subject: We need PIGs :) In-Reply-To: References: <46d74472$0$402$426a34cc@news.free.fr> <87hcm81dot.fsf@kip.sateh.com> <5k9qpsF2mrncU3@mid.uni-berlin.de> Message-ID: <2bfa72fa0709160747o53d4b767ne7da25c33498c19a@mail.gmail.com> On 9/16/07, Colin J. Williams wrote: > > Marc 'BlackJack' Rintsch wrote: > > On Thu, 06 Sep 2007 09:00:02 +0200, Stefan Arentz wrote: > > > >> What I find really frustrating in Python (combined with usually bad > >> documentation) is that many people have different styles. The most > >> frustratinng being getFoo() vs .foo, vs get_foo(). > > > > `getFoo()` is discouraged by PEP 8. You don't have the choice between > > `.foo` and `.get_foo()` in Java because Java has no properties and > people > > are trained to write getters and setters for everything. I like that > > choice in Python because I can write shorter code that is not cluttered > > with very simple getters and setters. > > > > Ciao, > > Marc 'BlackJack' Rintsch > Perhaps PEP 8 needs rethinking. I prefer getFoo(). > Similarly, I feel that the standard indent of 4 increases the > likelihood of running off the end of a line. An indent of 1 isn't > quite clear visually, but 2 is. The point with a style guide is not to cater for everyones preferences, but to set a common compromise. If you find yourself going off the right margin a lot, perhaps you should consider restructuring and refactoring your application, rather than reducing your indentation. Colin W. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Tue Sep 4 01:15:45 2007 From: nagle at animats.com (John Nagle) Date: Mon, 03 Sep 2007 22:15:45 -0700 Subject: FCGI app reloading on every request In-Reply-To: <46DCE052.40708@v.loewis.de> References: <46DCDE59.8060109@animats.com> <46DCE052.40708@v.loewis.de> Message-ID: Martin v. L?wis wrote: > John Nagle schrieb: > >> I'm converting a web app from CGI to FCGI. The application works fine >>under FCGI, but it's being reloaded for every request, which makes FCGI >>kind of pointless. I wrote a little FCGI app which prints when the >>program is loaded and when it gets a request. And indeed, the program >>gets reloaded for >>each HTTP request. Something is probably misconfigured. But what? > > > The most likely reason is that your FastCGI server voluntarily choses > to exit after one request. Can you share the mainloop of your > application? > > Regards, > Martin It turns out that's not the problem. What's actually happening is that FCGI isn't running at all. My .fcgi file is being executed by Apache's CGI handler, and "fcgi.py" recognizes this, then reads the parameters as if a CGI program. So it works just like a CGI program: one load per request. Not sure why Apache is doing that yet. I'm looking at Apache configuration files now. The main loop is in "fcgi.py", which calls the user application as a function. The user app doesn't have the option of exiting after one request, short of aborting without returning a result. John Nagle From gagsl-py2 at yahoo.com.ar Fri Sep 7 21:33:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Sep 2007 22:33:36 -0300 Subject: creating really big lists References: <874pi92tr4.fsf@mulj.homelinux.net> <1189057626.943757.210420@d55g2000hsg.googlegroups.com> <1189063849.118900.327540@22g2000hsm.googlegroups.com> <1189192606.119578.100820@r34g2000hsd.googlegroups.com> Message-ID: En Fri, 07 Sep 2007 16:16:46 -0300, Dr Mephesto escribi?: > hey, that defaultdict thing looks pretty cool... > > whats the overhead like for using a dictionary in python? Dictionaries are heavily optimized in Python. Access time is O(1), adding/removing elements is amortized O(1) (that is, constant time unless it has to grow/shrink some internal structures.) -- Gabriel Genellina From antroy at gmail.com Sat Sep 29 06:39:43 2007 From: antroy at gmail.com (Ant) Date: Sat, 29 Sep 2007 03:39:43 -0700 Subject: question about for cycle In-Reply-To: References: Message-ID: <1191062383.322949.55300@d55g2000hsg.googlegroups.com> On Sep 29, 11:04 am, "fdu.xia... at gmail.com" wrote: ... > What should I do if I want the outer "for" cycle to continue or break ? If I > put a "continue" or "break" in the inner cycle, it has no effect on the outer > cycle. I'd also be interested in the idiomatic solution to this one. I can see a number of solutions, from the ugly: for i in range(10): do_break = True for j in range(10): if j == 6: break else: do_break = False if do_break: break This will break the outer loop if the inner loop exited with a break. Using exceptions: for i in range(10): try: for j in range(10): print i, j if j == 6: raise MyException except MyException, e: break # or continue or whatever. Encapsulating in a function and using return: def get_value(): for i in range(10): for j in range(10): print i, j if j == 6: return fn(i, j) I guess to an extent it would depend on the exact situation as to which of these is more suitable. Are there any other recommended solutions to this? -- Ant... From duncan.booth at invalid.invalid Wed Sep 12 08:59:32 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Sep 2007 12:59:32 GMT Subject: cpython list __str__ method for floats References: <13ectngf3aeqrb0@corp.supernews.com> <5kndseF4iskqU1@mid.individual.net> <13eehfo8nr5eu1d@corp.supernews.com> <5kq2n9F4uhr0U1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: >> The idea that 13.3 is a 'rounded' value for the number, >> and that 13.300000000000001 is not a 'rounded' value of >> the number, is a common error of intuitive mathematics. > > I'm intrigued how /you/'d explain this, please do explain. I think he is correct here: 13.300000000000001 is not exactly representable in IEEE 754. It is a rounded approximation to the true value just as is 13.3. An argument can be made that instead of rounding the internal value to 17 digits which is sufficient to ensure that you can roundtrip float-> string->float for all values, you could just round it to the minimum number of digits which guarantee the float->string->float roundtrip for that particular value. Consider this as we gradually lose the more significant digits we see that last digit wasn't exactly 1 at all: >>> 13.3 13.300000000000001 >>> 13.3-13 0.30000000000000071 >>> (13.3-13)*10-3 7.1054273576010019e-015 but why shouldn't Python do this instead?: >>> 13.3 13.3 >>> 13.3-13 0.3 >>> (13.3-13)*10-3 7.1054273576e-015 These values will still roundtrip to the exact same internal representations. BTW, I didn't have to work too hard to figure out what that last value should be, the first is cut/paste from CPython, the second is what IronPython gives you. I believe the claim is that using the full 17 digits ensures the round- tripping works even if you serialise and deserialise on different systems, so perhaps we all pay a cost in our interactive sessions for something which should really be buried deep in IPC code. From tim.arnold at sas.com Fri Sep 21 10:49:53 2007 From: tim.arnold at sas.com (Tim Arnold) Date: Fri, 21 Sep 2007 10:49:53 -0400 Subject: elementtree question Message-ID: Hi, I'm using elementtree and elementtidy to work with some HTML files. For some of these files I need to enclose the body content in a new div tag, like this:
original contents...
I figure there must be a way to do it by creating a 'div' SubElement to the 'body' tag and somehow copying the rest of the tree under that SubElement, but it's beyond my comprehension. How can I accomplish this? (I know I could put the class on the body tag itself, but that won't satisfy the powers-that-be). thanks, --Tim Arnold From bj_666 at gmx.net Thu Sep 20 03:20:27 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Sep 2007 07:20:27 GMT Subject: Sets in Python References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <1190239608.835359.51150@22g2000hsm.googlegroups.com> <1190244370.741482.6540@y27g2000pre.googlegroups.com> <1190247922.835055.31950@y42g2000hsy.googlegroups.com> <1190259968.214528.158370@v29g2000prd.googlegroups.com> Message-ID: <5lel9rF7r3c0U1@mid.uni-berlin.de> On Thu, 20 Sep 2007 03:46:08 +0000, prikar20 wrote: > On Sep 19, 5:25 pm, Mark Dickinson wrote: >> On Sep 19, 7:26 pm, Karthik Gurusamy wrote: >> >> > If I did, a = [10, 20] and I did d[a]= 'foo', then a.append(30). >> > If dict complains key error on d[a] now, I won't be surprised. If I do >> > d[[10, 20, 30]], I will be surprised if it doesn't find the item. Of >> > course, in today's behavior the above is syntax error. >> >> It sounds as though you're proposing something like the following: >> >> >>> k = mylist([1, 2]) >> >>> d = {k : 'test'} >> >>> d[k] >> 'test' >> >>> k.append(3) >> >>> d[k] >> >> Traceback (most recent call last): >> File "", line 1, in >> KeyError: [1, 2, 3] >> >> So far, so good. But how do you explain the following to a confused >> newcomer? >> >> >>> d.keys() >> [[1, 2, 3]] >> >>> k in d.keys() >> True >> >>> k in d >> False >> >>> d[k] >> >> Traceback (most recent call last): >> File "", line 1, in >> KeyError: [1, 2, 3] >> >> In other words, to repeat Sion Arrowsmith's question, what would you >> expect d.keys() to return after a key of d has been modified? > > In the new model, it should be the value at the time of addition. > That is [1,2] (not [1,2,3]). This does mean a copy of key in > maintained internally in the dict. A copy!? That has to be a deep copy. Which would make `dict`\s alot slower and use more memory. Plus you can't store objects that can't be copied anymore. That doesn't sound like a good trade off to me. Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Sun Sep 9 08:59:41 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Sep 2007 12:59:41 -0000 Subject: unexpected behavior: did i create a pointer? References: <46e106ab$0$36439$4fafbaef@reader5.news.tin.it> <46e11dfe$0$4517$9b4e6d93@newsspool3.arcor-online.net> <13e2jdobu2kqkf1@corp.supernews.com> <13e4rno5qal6h4b@corp.supernews.com> <1189330200.935267.107970@19g2000hsx.googlegroups.com> Message-ID: <13e7rhtqelbcb54@corp.supernews.com> On Sun, 09 Sep 2007 02:30:00 -0700, Arnaud Delobelle wrote: >> You know, maybe because I came to Python with no C experience, I never >> had trouble with the "unexpected behaviour" that so confused the >> original poster. It's just obvious. > > The funny thing is that if the OP had thought of both 'a' and 'copyOfA' > as C-like pointers then he wouldn't have been confused :) You're almost certainly wrong. He would have written to ask why this doesn't do what he expects: >>> x = 3 >>> y = x # x and y are both pointers to the same value >>> x += 1 >>> print x == y # of course, they are pointers to the same value False Or why lower_list() works as expected, but lower_string() doesn't: >>> def lower_list(L): ... for i, x in enumerate(L): ... L[i] = x.lower() ... >>> s = ['STRING'] >>> lower_list(s) >>> print s == ['string'] True >>> >>> def lower_string(s): ... s = s.lower() ... >>> s = "STRING" >>> lower_string(s) >>> print s == "string" False The "names in Python are pointers" analogy only gives you the right answer half the time. The "names in Python are names" analogy gives you the right answer ALL THE TIME, no exceptions. -- Steven. From richardlev at gmail.com Mon Sep 17 00:33:14 2007 From: richardlev at gmail.com (Richard Levasseur) Date: Mon, 17 Sep 2007 04:33:14 -0000 Subject: Python Unicode to String conversion In-Reply-To: <1189962693.168033.258520@d55g2000hsg.googlegroups.com> References: <1188600916.528901.189680@d55g2000hsg.googlegroups.com> <1188631034.968347.116170@d55g2000hsg.googlegroups.com> <1189962693.168033.258520@d55g2000hsg.googlegroups.com> Message-ID: <1190003594.207618.314480@22g2000hsm.googlegroups.com> > On 1 sep, 09:17, iapain wrote: > > > First make sure your DB encoding is UTF-8 not the latin1 > It took me days to figure out what was going on when dealing with unicode, ascii, latin1, utf8, decodeerrors, etc, so I'm just chiming in to echo something similar iapain's comments: When dealing with unicode, i've run into situations where I have multiple encodings in the same string, usually latin1 and utf8 (latin1 != ascii, and latin1 != utf8, and they don't play nice together). So, for future readers, if you have problems dealing with unicode encode and decode, try using a mix of latin1 and utf8 encodings to figure out whats going on, and what characters are fubar'ing the process. From filipe at ipb.pt Wed Sep 5 11:40:23 2007 From: filipe at ipb.pt (Filipe Sousa) Date: Wed, 05 Sep 2007 16:40:23 +0100 Subject: sqlite3.OperationalError: Could not decode to UTF-8 column Message-ID: Hi I'm trying to use sqlite with python 2.5 but I have this problem: Traceback (most recent call last): File "converter.py", line 13, in c_old.execute('select id_aluno, nome from aluno') sqlite3.OperationalError: Could not decode to UTF-8 column 'nome' with text 'Ana Margarida Fernandes Gon?alves de S?' The database was created with another program and all data is in database is in latin1. Thanks, Filipe Sousa From steve at REMOVE-THIS-cybersource.com.au Wed Sep 19 20:32:29 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Sep 2007 00:32:29 -0000 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> <13f2hctdoob87e5@corp.supernews.com> <1190225268.547042.55370@d55g2000hsg.googlegroups.com> Message-ID: <13f3fsto5bo7i7e@corp.supernews.com> On Wed, 19 Sep 2007 11:07:48 -0700, TheFlyingDutchman wrote: > On Sep 19, 8:51 am, Steven D'Aprano cybersource.com.au> wrote: >> On Tue, 18 Sep 2007 18:09:26 -0700, TheFlyingDutchman wrote: >> > How much faster/slower would Greg Stein's code be on today's >> > processors versus CPython running on the processors of the late >> > 1990's? >> >> I think a better question is, how much faster/slower would Stein's code >> be on today's processors, versus CPython being hand-simulated in a >> giant virtual machine made of clockwork? >> >> -- >> Steven. > > Steven, You forgot this part: > > "And if you decide to answer, please add a true/false response to this > statement - "CPython in the late 1990's ran too slow"'. No, I ignored it, because it doesn't have a true/false response. It's a malformed request. "Too slow" for what task? Compared to what alternative? Fast and slow are not absolute terms, they are relative. A sloth is "fast" compared to continental drift, but "slow" compared to the space shuttle. BUT even if we all agreed that CPython was (or wasn't) "too slow" in the late 1990s, why on earth do you imagine that is important? It is no longer the late 1990s, it is now 2007, and we are not using Python 1.4 any more. -- Steven. From BjornSteinarFjeldPettersen at gmail.com Wed Sep 26 00:53:35 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Wed, 26 Sep 2007 04:53:35 -0000 Subject: ANN: PyPE 2.8.7 In-Reply-To: References: Message-ID: <1190782415.470011.226800@w3g2000hsg.googlegroups.com> On Sep 25, 12:46 pm, stef wrote: > Another problem, > I tried to run PyPE in my "old IDE", instead of double-clicking on the PyPE.exe file? Why? -- bjorn From ptmcg at austin.rr.com Sun Sep 30 16:49:41 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 30 Sep 2007 13:49:41 -0700 Subject: Create a string array of all comments in a html file... In-Reply-To: <1191166775.660477.97840@o80g2000hse.googlegroups.com> References: <1191166775.660477.97840@o80g2000hse.googlegroups.com> Message-ID: <1191185381.347004.189530@50g2000hsm.googlegroups.com> On Sep 30, 10:39 am, sophie_newbie wrote: > Hi, I'm wondering how i'd go about extracting a string array of all > comments in a HTML file, HTML comments obviously taking the format > "". > > I'm fairly stumped on how to do this? Maybe using regular expressions? > > Thanks. >>> from pyparsing import htmlComment >>> htmlComment.searchString("""And so funny! ...

""").asList() [[''], ['']] -- Paul From pcooke at philc.net Tue Sep 4 05:52:20 2007 From: pcooke at philc.net (PhilC) Date: Tue, 04 Sep 2007 05:52:20 -0400 Subject: Applying transformation matrix to 3D vertex coordinates References: <5rjod3lih4mnupjcm2184k5no15eodlc8r@4ax.com> Message-ID: On Mon, 03 Sep 2007 23:24:42 -0500, Robert Kern wrote: >transpose() ahh yes I can see where that would work. Just tried it in the above and I do get a last line of ones. OK onward and upward :) Many thanks Robert. From torriem at chem.byu.edu Sat Sep 1 15:37:29 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Sat, 01 Sep 2007 13:37:29 -0600 Subject: list index() In-Reply-To: <1188495863.242815.236900@o80g2000hse.googlegroups.com> References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <1188495863.242815.236900@o80g2000hse.googlegroups.com> Message-ID: <46D9BF79.6030000@chem.byu.edu> zzbbaadd at aol.com wrote: > In my case of have done os.listdir() on two directories. I want to see > what files are in directory A that are not in directory B. > I have used exceptions in other languages and only do so on logic that > should never happen. In this case it is known that some of the files > will not be in both lists. I just want to know which ones. > What's wrong, then, with doing: if i in list: print list.index(i) Since if, as you proposed, list.index() returned some value to represent "not found", you'd require an if anyway. This is probably not pythonic, but at least it would overcome your exceptions excuse. If we were to program this .index() method in some language that enforces contracts, like haskell, then we'd say that .index() expects a value that exists in the list. So if you violate the contract, why should you expect to *not* get an exception. Doing it any other way, though, makes the code a lot more error prone. From grante at visi.com Tue Sep 4 12:30:48 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 04 Sep 2007 16:30:48 -0000 Subject: How do I get triangles from a vtkPolyData object? References: <13do9eh8dtqa236@corp.supernews.com> <13dquoa1r252o60@corp.supernews.com> Message-ID: <13dr21opqrdrq4d@corp.supernews.com> On 2007-09-04, Grant Edwards wrote: > On 2007-09-03, Grant Edwards wrote: > > Is there _any_ documentation for the Python bindings to the vtk > library? I'm still beating my head against a wall trying to > figure out how to get the actual data out of vtk objects when > Python doesn't make visible the required "Get" methods.... I found a way to get at the object's "raw data" (a raw list of floats) and parse out the cell/polygon information, but it's bafflingly lame that Python doesn't make the normal "Get" methods available so that one can actually retrieve the individual cell elements of the vtkCellArray object. -- Grant Edwards grante Yow! All right, you at degenerates! I want visi.com this place evacuated in 20 seconds! From Brad.Johnson at ballardtech.com Tue Sep 18 20:17:09 2007 From: Brad.Johnson at ballardtech.com (Brad Johnson) Date: Wed, 19 Sep 2007 00:17:09 +0000 (UTC) Subject: Multiline command line parsing Message-ID: I am implementing a Python command line from scratch in a Win32 application. Examples online ("How do I tell incomplete input from invalid input" in the Extending and Embedding Python FAQ) show how to implement this from scratch using C code. The examples don't work. This brief snippit illustrates the problem: char* code = "class Foo:\n" "\tdef Bar():\n"; PyObject* temp = PyRun_String(code, Py_single_input, glb, loc); The syntax is completely valid, but should return an "unexpected EOF while parsing" (which I can handle). However, I receive "expected an indented block." Shouldn't this example work as stated? Is there something I am missing about my indentation technique, or any specific Win32 issues lurking? From carl at personnelware.com Thu Sep 20 21:26:47 2007 From: carl at personnelware.com (Carl K) Date: Thu, 20 Sep 2007 20:26:47 -0500 Subject: looking for ocbc example Message-ID: I am sure this is what I want: http://www.python.org/topics/database/docs.html "The documentation for the PythonWin ODBC module." but it is 404. google isn't being nice. Anyone know where I can find some simple examples? I have used odbc in other environments, so just need to know what modules, and the lines to connect and execute a sql command. It seems there are 2 odbc modules - pyOdbc and mxOdbc - anyone know the difference? Carl K From junchi.tang at gmail.com Thu Sep 20 12:47:24 2007 From: junchi.tang at gmail.com (Junchi Tang) Date: Thu, 20 Sep 2007 11:47:24 -0500 Subject: os.path.getmtime() and compare with a date type In-Reply-To: <46F29E2D.2040808@gmail.com> References: <1190302285.127448.288010@22g2000hsm.googlegroups.com> <46F29E2D.2040808@gmail.com> Message-ID: <8ee4d7a40709200947tf53ff9fub00302b30d02f6e2@mail.gmail.com> Thanks, that works perfectly! On 9/20/07, Anthony Greene wrote: > > junchi.tang at gmail.com wrote: > > Hi, > > I am new to python and are tryint to write a simple program delete log > > files that are older than 30 days. > > > > So I used os.path.getmtime(filepath) and compare it with a date but it > > does not compile. > > > > threshold_time = datetime.date.today() - datetime.timedelta(days=30) > > mod_time = os.path.getmtime(file_path) > > > > if( mod_time < threshold_time): > > #delete file > > > > However the interpreter complains at the if line, say "can't comapre > > datetime.date to int > > > > How can I covert one of them to make it work? > > > > Thank you! > > > > > You are looking for datetime.datetime.fromtimestamp(mod_time) > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jaywgraves at gmail.com Fri Sep 21 06:41:20 2007 From: jaywgraves at gmail.com (jay graves) Date: Fri, 21 Sep 2007 10:41:20 -0000 Subject: looking for ocbc example In-Reply-To: References: Message-ID: <1190371280.070392.55700@22g2000hsm.googlegroups.com> On Sep 21, 2:43 am, Tim Golden wrote: > Carl K wrote: > > It seems there are 2 odbc modules - pyOdbc and mxOdbc - anyone know the difference? > > In short, pyodbc is open source; mxOdbc requires a commercial license. > pyodbc is a newcomer, but appears to work for everything I've thrown > at it (which is not much). mxOdbc has been around longer, and is sure > to be a more mature product. It may offer more features & functionality. There is also a brand new module 'ceODBC'. http://ceodbc.sourceforge.net/ I haven't used it yet but I want to give it a try. ... Jay From timr at probo.com Wed Sep 19 02:27:48 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 19 Sep 2007 06:27:48 GMT Subject: Web Programming thru python References: <1190027654.008396.326100@57g2000hsv.googlegroups.com> Message-ID: python_lover wrote: > >Please help how to execute a py file with xitami. > >I installed xitami , downloaded lrwp file. > >accessing the first web application program >... >through browser like "http://localhost/first.py > >it is dispaying the source code of the first.py. > >Please help me how to execute the file. If you want this called as a CGI script, then you probably want this in the cgi-bin directory. You can use [Cgi-Alias] to make other directories into CGI directories as well. If you want ALL .py files to be executed, you should be able to create a filter using Xitami's configuration stuff at http://localhost/admin. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From hvendelbo.dev at googlemail.com Wed Sep 12 15:47:51 2007 From: hvendelbo.dev at googlemail.com (hvendelbo.dev at googlemail.com) Date: Wed, 12 Sep 2007 19:47:51 -0000 Subject: pwdmodule.c In-Reply-To: References: <1189622437.459458.129390@57g2000hsv.googlegroups.com> Message-ID: <1189626471.645309.259770@w3g2000hsg.googlegroups.com> > > http://mail.python.org/pipermail/python-dev/2007-July/073912.html Thanks. I tried his files against trunk and it didn't work. From Summercoolness at gmail.com Tue Sep 18 01:40:57 2007 From: Summercoolness at gmail.com (Summercool) Date: Tue, 18 Sep 2007 05:40:57 -0000 Subject: The meaning of a = b in object oriented languages Message-ID: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> The meaning of a = b in object oriented languages. ==================================================== I just want to confirm that in OOP, if a is an object, then b = a is only copying the reference. (to make it to the most basic form: a is 4 bytes, let's say, at memory location 0x10000000 to 0x10000003 b is 4 bytes, let's say, at memory location 0x20000000 to 0x20000003 in 0x10000000 to 0x10000003, it is the value 0xF0000000, pointing to an object b = a just means copy the 4 bytes 0xF0 0x00 0x00 0x00 into 0x20000000 to 0x2000003 so that b now points to 0xF0000000 which is the same object.) so essentially, a is just a pointer to an object. and b = a just means that put that same pointer into b. and that's why in Python or Ruby, it is like: >>> a = {"a" : 1, "b" : 2} >>> b = a >>> a {'a': 1, 'b': 2} >>> b {'a': 1, 'b': 2} >>> a["a"] = 999 >>> a {'a': 999, 'b': 2} >>> b {'a': 999, 'b': 2} so most or all object oriented language do assignment by reference? is there any object oriented language actually do assignment by value? I kind of remember in C++, if you do Animal a, b; a = b will actually be assignment by value. while in Java, Python, and Ruby, there are all assignment by reference. ("set by reference") Is that the case: if a is an object, then b = a is only copying the reference? From bj_666 at gmx.net Thu Sep 27 13:54:23 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Sep 2007 17:54:23 GMT Subject: True of False References: <1190910814.594559.30880@n39g2000hsh.googlegroups.com> <5m254hFatlbuU2@mid.uni-berlin.de> Message-ID: <5m292fFatlbuU5@mid.uni-berlin.de> On Thu, 27 Sep 2007 17:06:30 +0000, Duncan Booth wrote: > Marc 'BlackJack' Rintsch wrote: > >> In [268]: 'c' in a == True >> Out[268]: False >> >> In [269]: ('c' in a) == True >> Out[269]: True >> >> In [270]: 'c' in (a == True) >> ----------------------------------------------------------------------- >> ---- >> Traceback (most recent call >>last) >> >> /home/bj/ in () >> >>: argument of type 'bool' is not iterable >> >> >> What's going on there? > > See http://docs.python.org/ref/comparisons.html > >> Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent >> to x < y and y <= z, except that y is evaluated only once (but in both >> cases z is not evaluated at all when x < y is found to be false). > > In exactly the same way: > > 'c' in a == True > > is equivalent to: > > 'c' in a and a == True > > which is False. Aaah *enlightenment*, I'm using this for range checks like in the docs, but it wasn't obvious to me in this case. Thanks. Ciao, Marc 'BlackJack' Rintsch From ricaraoz at gmail.com Thu Sep 6 10:50:21 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 06 Sep 2007 11:50:21 -0300 Subject: Looping through File Question In-Reply-To: <1188997229.977198.23100@22g2000hsm.googlegroups.com> References: <1188989934.436165.213680@w3g2000hsg.googlegroups.com> <1188992047.858695.174790@r34g2000hsd.googlegroups.com> <1188995195.932117.111440@k79g2000hse.googlegroups.com> <1188997229.977198.23100@22g2000hsm.googlegroups.com> Message-ID: <46E013AD.7050005@bigfoot.com> John Machin wrote: > On Sep 5, 10:26 pm, planetmatt wrote: >> On 5 Sep, 12:34, John Machin wrote: >> >> >> >>> On Sep 5, 8:58 pm, planetmatt wrote: >>>> I am a Python beginner. I am trying to loop through a CSV file which >>>> I can do. What I want to change though is for the loop to start at >>>> row 2 in the file thus excluding column headers. >>>> At present I am using this statement to initiate a loop though the >>>> records: >>>> for line in f.readlines(): >>>> How do I start this at row 2? >>> The quick answer to your literal question is: >>> for line in f.readlines()[1:]: >>> or, with extreme loss of elegance, this: >>> for lino, line in enumerate(f.readlines()): >>> if not lino: >>> continue >>> But readline and readlines are old hat, and you wouldn't want to read >>> a file of a few million lines into a big list, so a better answer is: >>> _unused = f.next() >>> for line in f: >>> But you did say you were reading a CSV file, and you don't really want >>> to do your own CSV parsing, even if you think you know how to get it >>> right, so best is: >>> import csv >>> rdr = csv.reader(f) >>> heading_row = rdr.next() >>> for data_row in rdr: >>> HTH, >>> John >> Thanks so much for the quick response. All working now. >> >> I had looked at the CSV module but when I ran into another problem of >> trying to loop through all columns, I was given a solution in another >> forum which used the readlines() method. > > Antique advice which still left you doing the CSV parsing :-) > >> I have looked at the CSV documentation but didn't see any mention of >> heading_row or data_row. > > Ummm ... 'heading_row' and 'data_row' are identifiers of the kind that > you or I would need to make up in any language; why did you expect to > find them in the documentation? > >> Is there a definitive Python documentation >> site with code examples like MS's MSDN? > > The definitive Python documentation site is (I suppose) http://www.python.org/doc/ > > I don't know what "code examples like MS's MSDN" means. I avoid MSDN > like I'd avoid a nurse carrying a bottle of Dettol and a wire > brush :-) > > Here's an example of sucking your data into a list of lists and > accessing it columnwise: > > rdr = csv.reader(f) > whatever_you_want_to_call_the_heading_row = rdr.next() > data = list(rdr) > sum_col_5 = sum(float(row[5]) for row in data) > print "The value in row 3, column 4 is", data[3][4] > > HTH, > John > Given that you have a header row you could also do (untested): rdr = csv.DictReader(f) data = list(rdr) sum_Value = sum(float(row['Value']) for row in data) print "The value in row 3, column 'ColName' is", data[3]['ColName'] DictReader generates a list of dictionaries which take the keys from your header row. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 13 18:14:51 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Sep 2007 22:14:51 -0000 Subject: newbie: self.member syntax seems /really/ annoying References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189666095.727426.135170@o80g2000hse.googlegroups.com> <1189685403.306218.13270@22g2000hsm.googlegroups.com> <13eigagsuk74l55@corp.supernews.com> <46e94623$0$30375$9b4e6d93@newsspool4.arcor-online.net> <13eiosgssjkt3dd@corp.supernews.com> Message-ID: <13ejdir657npk7a@corp.supernews.com> On Thu, 13 Sep 2007 13:14:25 -0400, J. Clifford Dyer wrote: > On Thu, Sep 13, 2007 at 04:21:36PM -0000, Steven D'Aprano wrote > regarding Re: newbie: self.member syntax seems /really/ annoying: >> >> It's not just a matter of taste. >> >> Reading comprehensibility is an objective, measurable quantity, and I >> would bet that "(self.foo + self.bar) * self.baz" would be measurably >> more readable on average than either of your two alternatives _even for >> those people who claim to hate it_. >> >> > It may be measurable, but it is also contextual. Depending on what > you've been trained in, one way or the other might be more readable. > For a teenager in a major city, tagging is far more readable than a > Fraktur font, but for Mad King Ludwig, it was certainly quite the > opposite. Cliff, we're discussing Python programming, not Java programming or assembly language programming or tagging trains. Let the damn taggers invent their own programming language and stop graffiti-ing Python. And speaking of readability... your post shows up in my news reader with each paragraph as a single, long, long LONG line scrolling about five full screens to the right. Please configure your software to follow the Usenet convention of putting newline characters at the end of each line, or every 72 (?) characters, whichever comes first. > Moreover, it may be that the best solution is to stop trying for an > object-oriented solution. Why not use a functional programming style to > represent mathematical functions? Go back to the beginning of the thread, and you'll see that that's just what I suggested. -- Steven. From bignose+hates-spam at benfinney.id.au Wed Sep 12 21:11:56 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 13 Sep 2007 11:11:56 +1000 Subject: Coming from Perl References: <87wsuv5r83.fsf@benfinney.id.au> Message-ID: <87myvr5pyb.fsf@benfinney.id.au> Amer Neely writes: > print < > > Hello > > > EndHTML The equivalent in Python would be:: print """ Hello """ You can even use Python's standard textwrap module to indent your code properly:: import textwrap def foo(bar): if baz: print textwrap.dedent(""" Hello """) The 'textwrap.dedent' function strips *common* leading whitespace from all lines in the string, so in the above example the resulting string will be as though the original string were typed flush to the left margin. See 'help(textwrap.dedent)' for what that function does, or read it online . -- \ "Madness is rare in individuals, but in groups, parties, | `\ nations and ages it is the rule." -- Friedrich Nietzsche | _o__) | Ben Finney From cai.haibin at gmail.com Wed Sep 26 01:14:38 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 26 Sep 2007 05:14:38 -0000 Subject: %s shortcut? In-Reply-To: <1190780264.426322.237690@g4g2000hsf.googlegroups.com> References: <1190775317.062210.234400@g4g2000hsf.googlegroups.com> <1190780264.426322.237690@g4g2000hsf.googlegroups.com> Message-ID: <1190783678.074965.33150@19g2000hsx.googlegroups.com> hi bjorn, > You could do [year]*12 + [order_by] like so: > > >>> [1970] * 12 + ['foo'] > > [1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, > 1970, 'foo'] > > > > I don't know which database you're using, but the above doesn't look > like SQL'92... > Thanks, it works! I am using mysql 5, and it works (i am having a hard time with mysql's SP, firebird is very easy and nice) cheers, james From deets at nospam.web.de Mon Sep 10 16:39:22 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Sep 2007 22:39:22 +0200 Subject: Mac OSX sqlite problem. Missing? In-Reply-To: <1189455305.994439.107100@r34g2000hsd.googlegroups.com> References: <1189455305.994439.107100@r34g2000hsd.googlegroups.com> Message-ID: <5klocbF498ruU1@mid.uni-berlin.de> ricardo.turpino at gmail.com schrieb: > Hi, > > I've installed Mac Python 2.5. I'm running Mac OS X 10.4.10 on a > Macbook 1.83GHz. I though that the python sqlite library was > installed by default as part of Mac Python 2.5, however, I still have > a problem. > > Sqlite does not appear to be my system: > >>>> import sqlite > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named sqlite > > I ran 'sudo easy_install pysqlite' which gave me the file > 'pysqlite-2.3.5-py2.5-macosx-10.3-fat.egg', but no working pysqlite. > > I then downloaded the source files and ran 'python ez_setup.py > pysqlite==2.3.5', which told me 'Using /Library/Frameworks/ > Python.framework/Versions/2.5/lib/python2.5/site-packages/ > pysqlite-2.3.5-py2.5-macosx-10.3-fat.egg' > > Still no working version of pysqlite. > > Tried installing from source. No problems appeared, but I still can't > use pysqlite. > > The reason I am trying to install pysqlite, is to use turbogears, > which initially failed when I ran 'tg-admin sql create', it failed > with 'import sqlite. ImportError: No module named sqlite'. > > Any ideas gratefully received. Are you by any chance using the python 2.3 when issuing that import statement? Diez From bj_666 at gmx.net Sat Sep 22 02:35:54 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2007 06:35:54 GMT Subject: Who can develop the following Python script into working application ? References: <1190334828.210230.293980@50g2000hsm.googlegroups.com> <1190372423.768184.60080@19g2000hsx.googlegroups.com> <5lho31F84jgjU1@mid.uni-berlin.de> <1190419744.390216.19040@w3g2000hsg.googlegroups.com> Message-ID: <5ljreaF8gic1U2@mid.uni-berlin.de> On Fri, 21 Sep 2007 17:09:04 -0700, http://members.lycos.co.uk/dariusjack/ wrote: > On Sep 21, 1:26 pm, "Diez B. Roggisch" wrote: >> > Is Python not fit to a task of this kind ? It is, and it should be quite simple. > Is there no a library of Python free scripts to accomplish the above > like many for javascripts ? > I am asking just of curosity, as an author of this script didn't > respond to my second request to tell me how complicated is the > problem and what made him not to write that script as a fully working > version. > > Is Python so difficult, complicated, even for experienced developers ? What makes you think it is? This group is about the Python programming language, discussing it and helping people to learn it. It seems that people here don't like fixing code for free for people who are not interested in the language themselves. There are platforms like guru.com or rentacoder.com for such assignments. Ciao, Marc 'BlackJack' Rintsch From Dolka1 at gmail.com Sat Sep 1 21:11:45 2007 From: Dolka1 at gmail.com (goodol) Date: Sun, 02 Sep 2007 01:11:45 -0000 Subject: [python-win32] How can I get the parentWindow.document object? Message-ID: <1188695505.993750.180020@19g2000hsx.googlegroups.com> hello everybody i am trying to automatie IE using python, and i want to access at the parentWindow.document object the code is like this, import win32com.client import pythoncom ie = win32com.client.Dispatch("InternetExplorer.Application") doc=ie.Document.parentWindow.document the code always failed. the error message is "pywintypes.com_error: (-2147352567, ...." How can i get the parentWindow.document object? what' the reason the code failed? Thanks in advance. From trekker182 at gmail.com Sat Sep 22 17:00:47 2007 From: trekker182 at gmail.com (Shawn Minisall) Date: Sat, 22 Sep 2007 17:00:47 -0400 Subject: too many values with string.split Message-ID: <46F5827F.6050002@gmail.com> I'm trying to unpack a list of 5 floats from a list read from a file and python is telling me 5 variables are too many for the string.split statement. Anyone have any other idea's? NOTE: the only reason I convert it to a float instead of just leaving it as a string in the loop is because I have to have it printed out as a float besides the names and then the average displayed underneath thx #read in data line by line for line in infile: mylist = string.split(line) firstName[counter] = mylist[0] lastName[counter] = mylist[1] grades[counter] = float(mylist[2]) print firstName[counter], lastName[counter],":","\t\t",grades[counter] #increment counter counter = counter + 1 #calculates and prints average score grades = str(grades) num1, num2, num3, num4, num5 = string.split(grades,",") average = float(num1 + num2 + num3 + num4 + num5) / 5 print print "Average:" From ldo at geek-central.gen.new_zealand Sat Sep 1 02:45:36 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 01 Sep 2007 18:45:36 +1200 Subject: Automation and scheduling of FrontPage publishing using Python References: <1188517723.279932.299400@x40g2000prg.googlegroups.com> Message-ID: In message , Steve Holden wrote: > Lawrence D'Oliveiro wrote: > >> In message <1188517723.279932.299400 at x40g2000prg.googlegroups.com>, >> andrew.arobert at gmail.com wrote: >> >>> We have numerous web sites which are currently being manually >>> published via Front Page. >>> >>> Doing one or two sites on an ad-hoc basis was not too bad but we are >>> now over 20 or thirty at set times during a business day. >> >> Let me open the bidding by suggesting that you stop using FrontPage. > > But that would mean reprogramming the functionality they now implement > using FrontPage extensions. Any help with that? If they were using FrontPage extensions, they deserve everything they get. From exhuma at gmail.com Wed Sep 19 03:00:49 2007 From: exhuma at gmail.com (exhuma.twn) Date: Wed, 19 Sep 2007 00:00:49 -0700 Subject: Tutorial or Example (or Tutorial) of Using Canvas to Produce a Plot In-Reply-To: <9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com> References: <13evohih7rkd030@corp.supernews.com> <13f0b2qlvj5ige6@corp.supernews.com> <9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com> Message-ID: <1190185249.235840.263260@50g2000hsm.googlegroups.com> On Sep 18, 11:58 pm, Richard Townsend wrote: > On Tue, 18 Sep 2007 13:18:36 -0700, "W. Watson" > > wrote: > >Tk is it. I'm really not interested in the others at this point. > > John Grayson's book 'Python and Tkinter Programming' has a chapter on > plotting Graphs and Charts. You can even download that chapter as a > PDF file: > > http://www.manning-source.com/books/grayson/grayson_ch11.pdf > > Seehttp://www.manning.com/grayson/for more info about the book. Also, if the graph is really all you need, matplotlib might be a very interesting choice: http://matplotlib.sourceforge.net/ It's got some user-interface facilities as well. But I never used those so far. From david at boddie.org.uk Sat Sep 29 13:06:06 2007 From: david at boddie.org.uk (David Boddie) Date: Sat, 29 Sep 2007 19:06:06 +0200 Subject: How to display a videostream in the PyQt GUI by a efficient way Message-ID: <200709291906.08380.david@boddie.org.uk> On Sat Sep 29 05:12:25 CEST 2007, kivilaya wrote: > As required, I need to get a videostream from a camera, and process > every frame to add some information on it, and then display the frame > in a PyQt GUI. > But I don't know how to display the videostream in the PyQt GUI by a > efficient way. > > Currently, I do these like this: > 1. Get the videostream by the videocapture module (a useful module > written by Markus Gritsch) in the format of PIL images; This sounds interesting. I wasn't aware of that module. > 2. Process every PIL image and add the information; > 3. Convert every PIL image to QPixmap and display it using > QLabel.setPixmap. This could be quite inefficient, though I think there's some support for Qt's image classes in PIL these days. > I think it is a very inefficient way, but I don't known how to display > the videostream in other ways, so I need your help, Thanks! > > PS:I do it with Windows XP, Python 2.5.1, PyQt4.3.0 If you're using a commercially-licensed Qt library, you'll have access to the ActiveQt classes that can be used to embed ActiveX controls: http://doc.trolltech.com/4.3/activeqt.html Otherwise, you might find this recent thread on qt-interest to be of interest: http://lists.trolltech.com/qt-interest/2007-09/msg00806.html I also tried to document ways to do this on the PyQt/PyKDE Wiki: http://www.diotavelli.net/PyQtWiki/Multimedia_Resources David From resist_think at hushmail.com Wed Sep 5 05:14:32 2007 From: resist_think at hushmail.com (resist_think at hushmail.com) Date: Wed, 05 Sep 2007 12:14:32 +0300 Subject: 2 python questions! Message-ID: <20070905091437.C7C09C3821@mailserver10.hushmail.com> Hi python community! First question has to do with threading support. There is the following simple case: I have a dictionnary that gets it's values -which are url's-from a function. Sort of dictionnary['1'] = "http://www.google.com" dictionnary['2'] = "http://www.python.com" .... I need to fill in the dictionnary with some url's. If I do it on the simplest way, it would be like: for i in range(20): dictionnary["%s" % i] = get_urls(args) and wait a long long time till it finishes. Can I do it easily with threads, without having to add too much code? Ideal case would be if all threads start simultaneously :) Now the second question has to do with images retrieval and manipulation. Which libraries do you propose to work with to retrieve and resize images from the web? Thanks in advance for any help! -- Handyman Franchises. Click Here. http://tagline.hushmail.com/fc/Ioyw6h4fMyhGJzTqAUMT4o9Inh2I0NfM85HrFhPDGb7fSaLiZQZqWk/ From bignose+hates-spam at benfinney.id.au Wed Sep 12 23:57:56 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 13 Sep 2007 13:57:56 +1000 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> <87ir6f5mrq.fsf@benfinney.id.au> <1189651204.408268.57580@19g2000hsx.googlegroups.com> Message-ID: <874phz5i9n.fsf@benfinney.id.au> TheFlyingDutchman writes: (Please, preserve attribution lines so it's clear who wrote what in your quoted material.) > > >>> Foo.bar(foo, "spam") > > >>> foo.bar("spam") > > That looks like a case of "There's more than one way to do it". ;) Indeed, but there's only one *obvious* way to do it. (The latter, in this case.) > The first form is definitely consistent with the method declaration, > so there's a lot to be said for using that style when teaching > people to make classes -> send self, receive self. Sure, go ahead and teach that way if you like; it'll work fine. > I think I saw where Guido Van Rossum had referred to something as > "syntactic sugar" in some python.org page. I am not familiar with > sugar as related to syntax. Is it being used as a synonym for > "easier way of doing it"? Specifically an easier way of doing it provided by the language syntax (hence "syntactic sugar"). As in, "the form 'foo += 1' is syntactic sugar for 'foo = foo + 1'". -- \ "I don't know half of you half as well as I should like, and I | `\ like less than half of you half as well as you deserve." -- | _o__) Bilbo Baggins | Ben Finney From david at asdf.asdf Tue Sep 11 21:57:14 2007 From: david at asdf.asdf (bambam) Date: Wed, 12 Sep 2007 11:57:14 +1000 Subject: function to do dynamic import? References: <13ecb84p1ghrd64@corp.supernews.com> Message-ID: <13eehrpbv5c3i2c@corp.supernews.com> "J. Cliff Dyer" wrote in message news:mailman.371.1189509653.2658.python-list at python.org... > bambam wrote: >> import works in the main section of the module, but does >> not work as I hoped when run inside a function. >> >> That is, the modules import correctly, but are not visible to >> the enclosing (global) scope. >> >> Questions: >> (1) Where can I read an explanation of this? >> (2) Is there a work around? >> >> BTW, sys.modules("filename") shows that the module is >> loaded, I just don't know how to use it when loaded that >> way. Also, if I import again at the global scope, the module >> name becomes available. >> >> Steve. >> >> --- >> >>>>> def gim(): >>>>> >> ... exec "import gamel" >> ... >> > All you have done in this function is bind the module to the name gamel > within the scope of the function. As soon as the function exits, the > module goes out of scope. If you want to use it externally, return the > module. > > def: gim(): > import gamel > return gamel >>>>> gim() >>>>> > This will have to change to > > gamel = gim() > > and the rest should work as expected. >>>>> sys.modules["gamel"] >>>>> >> >> >>>>> gamel >>>>> >> NameError: name 'gamel' is not defined >> >>>>> exec "import gamel" >>>>> gamel >>>>> >> >> >> >> > def: gim(): import gamel return gamel Unfortunately, it needs to do dynamic import: I can't list all of the possible import modules because they are unknown until runtime. Steve. From steve at REMOVE-THIS-cybersource.com.au Wed Sep 19 23:54:59 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Sep 2007 03:54:59 -0000 Subject: Will Python 3.0 remove the global interpreter lock (GIL) References: <1188778898.007988.231180@d55g2000hsg.googlegroups.com> <1190164166.378500.155990@o80g2000hse.googlegroups.com> <1190241711.344058.238380@57g2000hsv.googlegroups.com> <1190242799.954176.279440@22g2000hsm.googlegroups.com> <7xps0ew0a8.fsf@ruckus.brouhaha.com> Message-ID: <13f3roj6gdfq6b7@corp.supernews.com> On Wed, 19 Sep 2007 19:14:39 -0700, Paul Rubin wrote: > We get cpu speed increases now through parallelism, not mhz. Intel and > AMD both have 4-core cpu's now and Intel has a 16-core chip coming. > Python is at a serious disadvantage compared with other languages if the > other languages keep up with developments and Python does not. I think what you mean to say is that Python _will be_ at a serious disadvantage if other languages keep up and Python doesn't. Python can't be at a disadvantage _now_ because of what happens in the future. Although, with the rapid take-up of multi-core CPUs, the future is *really close*, so I welcome the earlier comment from Terry Reedy that Guido has said he is willing to make changes to the CPython internals to support multiprocessors, and that people have begun to investigate practical methods of removing the GIL (as opposed to just bitching about it for the sake of bitching). > The platitude that performance doesn't matter Who on earth says that? I've never heard anyone say that. What I've heard people say is that _machine_ performance isn't the only thing that needs to be maximized, or even the most important thing. Otherwise we'd all be writing hand-optimized assembly language, and there would be a waiting line of about five years to get access to the few programmers capable of writing that hand-optimized assembly language. > that programmer time is more valuable than machine time Programmer time is more valuable than machine time in many cases, especially when tasks are easily parallisable across many machines. That's why your "comparatively wimpy site" preferred to throw extra web servers at the job of serving webpages rather than investing in smarter, harder-working programmers to pull the last skerricks of performance out of the hardware you already had. > etc. is at best an excuse for laziness. What are you doing about solving the problem? Apart from standing on the side-lines calling out "Get yer lazy behinds movin', yer lazy bums!!!" at the people who aren't even convinced there is a problem that needs solving? > And more and more often, in the > application areas where Python is deployed, it's just plain wrong. Take > web servers: a big site like Google has something like a half million of > them. Even the comparatively wimpy site where I work has a couple > thousand. If each server uses 150 watts of power (plus air > conditioning), then if making the software 2x faster lets us shut down > 1000 of them, What on earth makes you think that would be anything more than a temporary, VERY temporary, shutdown? My prediction is that the last of the machines wouldn't have even been unplugged before management decided that running twice as fast, or servicing twice as many people at the same speed, is more important than saving on the electricity bill, and they'd be plugged back in. > the savings in electricity bills alone is larger than my > salary. Of course that doesn't include environmental benefits, hardware > and hosting costs, the costs and headaches of administering that many > boxes, etc. For a lot of Python users, significant speedups are a huge > win. Oh, I wouldn't say "No thanks!" to a Python speed up. My newest PC has a dual-core CPU (no cutting edge for me...) and while Python is faster on it than it was on my old PC, it isn't twice as fast. But Python speed ups don't come for free. For instance, I'd *really* object if Python ran twice as fast for users with a quad-core CPU, but twice as slow for users like me with only a dual-core CPU. I'd also object if the cost of Python running twice as fast was for the startup time to quadruple, because I already run a lot of small scripts where the time to launch the interpreter is a significant fraction of the total run time. If I wanted something like Java, that runs fast once it is started but takes a LONG time to actually start, I know where to find it. I'd also object if the cost of Python running twice as fast was for Guido and the rest of the Python-dev team to present me with their wages bill for six months of development. I'm grateful that somebody is paying their wages, but if I had to pay for it myself it wouldn't be done. It simply isn't that important to me (and even if it was, I couldn't afford it). Now there's a thought... given that Google: (1) has lots of money; (2) uses Python a lot; (3) already employs both Guido and (I think...) Alex Martelli and possibly other Python gurus; (4) is not shy in investing in Open Source projects; (5) and most importantly uses technologies that need to be used across multiple processors and multiple machines one wonders if Google's opinion of where core Python development needs to go is the same as your opinion? -- Steven. From robert.kern at gmail.com Thu Sep 13 12:23:22 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 13 Sep 2007 11:23:22 -0500 Subject: Extended slicing and Ellipsis - where are they used? In-Reply-To: <1189699345.436400.233460@g4g2000hsf.googlegroups.com> References: <1189699345.436400.233460@g4g2000hsf.googlegroups.com> Message-ID: Rodney Maxwell wrote: > The following are apparently legal Python syntactically: > L[1:3, 8:10] > L[1, ..., 5:-2] > > But they don't seem to work on lists: >>>> l = [0,1,2,3] >>>> l[0:2,3] > Traceback (most recent call last): > File "", line 1, in > TypeError: list indices must be integers >>>> l[...] > Traceback (most recent call last): > File "", line 1, in > TypeError: list indices must be integers > > So where is this extended slicing used? numpy for multidimensional arrays. http://numpy.scipy.org/ -- 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 teroV at nowhere.invalid Fri Sep 28 15:54:40 2007 From: teroV at nowhere.invalid (TeroV) Date: Fri, 28 Sep 2007 22:54:40 +0300 Subject: Bug with lists of pairs of lists and append() In-Reply-To: References: Message-ID: <5_cLi.230301$5E1.185721@reader1.news.saunalahti.fi> Gabriel Zachmann wrote: > Well, > > could some kind soul please explain to me why the following trivial code > is misbehaving? > > > #!/usr/bin/python > s = [] > l = [ 0 ] > r = [0, 0] > while r: > x = (l,r) > print x > s.append( x ) > l.append( r.pop(0) ) > print s > > > > The output I get is: > > ([0], [0, 0]) > ([0, 0], [0]) > [([0, 0, 0], []), ([0, 0, 0], [])] > > and the error is in the last line: the two pairs in the outer list are > identical and they should be equal to the pairs one the first and the > 2nd line, respectively! Shouldn't they? > > I think I'm going nuts -- for the life of me I don't see what's going on > ... > > Thanks a lot in advance for any insights, etc. > > Best regards, > Gabriel. You didn't say what it is supposed to do. But, does replacing line "x = (l, r)" with "x = l[:], r[:]" do the trick? In the original code you do basically the same as this >>> a = [] >>> b = [1,2] >>> a.append(b) >>> b.append(3) >>> a [[1, 2, 3]] HTH :) From dotancohen at gmail.com Mon Sep 10 16:47:00 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 10 Sep 2007 23:47:00 +0300 Subject: Need a KDE app, where to find a coder? Message-ID: <880dece00709101347y41f5fc88q1b22c3dcfe47dd44@mail.gmail.com> I need an application, and I'd like it to be written in Python with QT as I am a KDE user. I simply don't have the time to code it myself, as I've been trying to find the time for half a year now. What are some reputable websites for finding Python coders? If anyone on the list wants the job, this is what I need: I need a hierarchical list manager, similar to ListPro (http://www.iliumsoft.com/site/lp/listpro.htm) which is the app that I'm replacing. Specifically, I need the checkmark (boolen), item (string), date, amount (int/100), and notes fields. As KDE is moving to QT4 in December (with the release of KDE4) it would be best if the app were coded with this in mind. As the application is for my own personal use, I will try to maintain it with the little python that I know, but I may need help along the way. Thanks in advance. Dotan Cohen From nickel_and_dime_2death at yahoo.com Wed Sep 19 03:14:24 2007 From: nickel_and_dime_2death at yahoo.com (nickel_and_dime_2death at yahoo.com) Date: Wed, 19 Sep 2007 00:14:24 -0700 Subject: Troubleshooting installing new package In-Reply-To: References: Message-ID: <1190186064.271030.219480@22g2000hsm.googlegroups.com> On Sep 13, 8:10 pm, "Gheorghe Postelnicu" wrote: > Hi, > > I have Python 2.5 installed on WinXP and I am trying to install a new > package. I ran thesetup.pybuild and I get the following message: > > C:\packages\reedsolomon-0.1>setup.pybuild > running build > running build_ext > error: Python was built with Visual Studio 2003; > extensions must be built with a compiler than can generate compatible binaries. > Visual Studio 2003 was not found on this system. If you have Cygwin installed, > you can try compiling with MingW32, by passing "-c mingw32" tosetup.py. > > I have Visual Studio 2005 Express (the free one) installed. Is there a > way to specify an option to compile using that version of the > compiler? > > Sorry for the silly question and thanks in advance for any helpful suggestions! > -- > Gheorghe Postelnicu, PhD > MGH, Harvard Medical School Hello, newbee here. I was looking for other solutions to other problems. However, in my research for building wxPython I read from the docs/build.html concerning the WIN crowd ... -- [quote] If you woudl rather use a different version of VisualStudio keep in mind that you'll also have to build Python and any other extension modules that you use with that compiler because a different version of the C runtime library is used. The stock Python 2.4 and 2.5 executables are built with MSVC 7.1, and the same rules apply to it.[/ quote] So... did you build your Python2.5?? or did you install the binaries?? It makes a big difference. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 6 01:38:08 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Sep 2007 05:38:08 -0000 Subject: Does shuffle() produce uniform result ? References: <7xejhfbsjo.fsf@ruckus.brouhaha.com> <7xabs39bin.fsf@ruckus.brouhaha.com> <13drijhfqlvlk96@corp.supernews.com> <7xwsv53dtw.fsf@ruckus.brouhaha.com> Message-ID: <13dv4i0lrmsk15@corp.supernews.com> On Tue, 04 Sep 2007 22:01:47 -0700, Paul Rubin wrote: > OK. /dev/random vs /dev/urandom is a perennial topic in sci.crypt and > there are endless long threads about it there, so I tried to give you > the short version, but will give a somewhat longer version here. Thank you. Your points are taken, in particular: > 4) The man page is fairly seriously bogus because it doesn't explain > the real situation with either /dev/urandom or /dev/random. -- Steven. From carsten at uniqsys.com Thu Sep 20 15:55:15 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 20 Sep 2007 15:55:15 -0400 Subject: frange() question In-Reply-To: <87tzppjhe4.fsf@pobox.com> References: <87tzppjhe4.fsf@pobox.com> Message-ID: <1190318115.3392.63.camel@dot.uniqsys.com> On Thu, 2007-09-20 at 18:55 +0000, John J. Lee wrote: > Functions are never generators, senso stricto. There are "generator > functions", which *return* (or yield) generators when you call them. Actually, a generator function is a function that returns a generator. The generator, in turn, is an object that wraps the iterator protocol around a resumable function. When the generator's next() method is called, it resumes its wrapped function that runs until it yields or finishes. When the wrapped function yields a value, it is suspended, and the yielded value is returned as the result of next(). If the wrapped function finished, next() raises StopIteration. Generators are a special case of iterators. Any object that implements the iterator protocol (which among other less important things mandates a next() method that returns the next value or raises StopIteration) is an iterator. Generators simply have their special way (by calling into a resumable function) of implementing the iterator protocol, but any stateful object that returns a value or raises StopIteration in next() is an iterator. > It's true sometimes people refer to generator functions as simply > "generators", but in examples like the above, it's useful to remember > that they are two different things. > > In this case, frange isn't a generator function, because it doesn't > yield. Instead, it returns the result of evaluating a generator > expression (a generator). The generatator expression plays the same > role as a generator function -- calling a generator function gives you > a generator object; evaluating a generator expression gives you a > generator object. There's nothing to stop you returning that > generator object, which makes this function behave just like a regular > generator function. Generator expressions still "yield", but you don't see the yield in the Python source code. Observe: >>> def gf1(): ... for i in (1,2,3): ... yield i ... >>> def gf2(): ... return (i for i in (1,2,3)) ... >>> g1 = gf1() >>> g2 = gf2() >>> g1 >>> g2 >>> dir(g1) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'gi_frame', 'gi_running', 'next', 'send', 'throw'] >>> dir(g2) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'gi_frame', 'gi_running', 'next', 'send', 'throw'] >>> import dis >>> dis.dis(g1.gi_frame.f_code.co_code) 0 SETUP_LOOP 19 (to 22) 3 LOAD_CONST 4 (4) 6 GET_ITER >> 7 FOR_ITER 11 (to 21) 10 STORE_FAST 0 (0) 13 LOAD_FAST 0 (0) 16 YIELD_VALUE 17 POP_TOP 18 JUMP_ABSOLUTE 7 >> 21 POP_BLOCK >> 22 LOAD_CONST 0 (0) 25 RETURN_VALUE >>> dis.dis(g2.gi_frame.f_code.co_code) 0 SETUP_LOOP 18 (to 21) 3 LOAD_FAST 0 (0) >> 6 FOR_ITER 11 (to 20) 9 STORE_FAST 1 (1) 12 LOAD_FAST 1 (1) 15 YIELD_VALUE 16 POP_TOP 17 JUMP_ABSOLUTE 6 >> 20 POP_BLOCK >> 21 LOAD_CONST 0 (0) 24 RETURN_VALUE As you can see, except for a minor optimization in the byte code, there is no discernible difference between the generator that's returned from a generator expression and the generator that's returned from the generator function. Note in particular that the byte code for g2 contains a YIELD_VALUE operation just like g1 does. In fact, generator expressions are merely a short-hand notation for simple generator functions of a particular form. The generator expression g = (expr(x) for x in some_iterable) produces a generator that is almost indistinguishable from, and operationally identical to, the generator produced by the following code: def __anonymous(): for x in some_iterable: yield expr(x) g = __anonymous() del __anonymous Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From lasses_weil at klapptsowieso.net Fri Sep 7 10:06:07 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Fri, 07 Sep 2007 16:06:07 +0200 Subject: Generating a unique identifier In-Reply-To: References: <13e2fgbbpsatm39@corp.supernews.com> Message-ID: <46e15acf$0$16104$9b4e6d93@newsspool1.arcor-online.net> Will Maier wrote: > On Fri, Sep 07, 2007 at 12:03:23PM -0000, Steven D'Aprano wrote: > [...] >> which is easy enough, but I thought I'd check if there was an existing >> solution in the standard library that I missed. Also, for other >> applications, I might want them to be rather less predictable. > > 2.5 includes the uuid module for RFC 4122 universally-unique IDs: > > http://docs.python.org/lib/module-uuid.html > Jesus Christ! What in all the world *doesn't* Python do already?! Can't we now just write up a module for the standard lib that takes care of writing all the other code as well and just forget about getting our hands dirty with programming altogether? /W (just in case: ;)!) From richardjones at optushome.com.au Sat Sep 29 22:55:19 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sun, 30 Sep 2007 12:55:19 +1000 Subject: OSDC 2007 earlybird registration now open! Message-ID: <200709301255.19262.richardjones@optushome.com.au> [and now with more information] The Open Source Developers' Conference is designed by open source developers, for developers and business people. It covers numerous programming languages across a range of operating systems, and related topics such as business processes, licensing, and strategy. Talks vary from introductory pieces through to the deeply technical. Registration for OSDC Australia 2007 (26th to 29th November in Brisbane, Queensland( is now open at http://osdc.com.au/registration/ The earlybird price is $275 (until October 14th), after that the full conference price is $325. All regular tickets include the conference dinner! Peruse the overview of confirmed sessions at: http://www.cgpublisher.com/conferences/107/web/session_descriptions.html OSDC 2007 is proud and grateful to have a group of global as well as local companies sponsoring this year's event: Apress, CNET/BuilderAU, Common Ground, Freeway/Zac-Ware, Google, Linux Magazine, Opengear, Open Query, Rea Group, Red Hat, Sun Microsystems, Trolltech, Woodslane. Sponsorship opportunities are still available - please contact OSDC through their website http://osdc.com.au/ From gdamjan at gmail.com Sun Sep 23 12:24:04 2007 From: gdamjan at gmail.com (Damjan) Date: Sun, 23 Sep 2007 18:24:04 +0200 Subject: annoying stdin/stdout + pipes problem References: <1190554821.677666.93530@w3g2000hsg.googlegroups.com> Message-ID: <46f69324$0$90263$14726298@news.sunsite.dk> > I want to create a program that reads input from stdio that can prompt > a user for input while doing so without getting into problems. ... > As you can see I have commented out what I'd like to do but do not > know how to. Can I somehow halt the previous print to stdout (cat > input.txt) - if so can I then start it again, and how? The trick (which works on Linux for sure) is to open /dev/tty and ask question/get input on/from it. fp = open('/dev/tty', 'r+') fp.write('Prompt: ') answer = fp.readline().strip() I'm not usre for other *nix-es, and on Windows this will surelly not work -- damjan From timr at probo.com Wed Sep 12 23:17:26 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 13 Sep 2007 03:17:26 GMT Subject: anybody has py modules emulating symbian 60 on PC? References: <005f01c7f41d$cb9cfa80$4de1a8c0@amd.com> Message-ID: Steve Holden wrote: > >http://archive.devx.com/wireless/vendordocs/nokia.asp might help. Or it >might not. How utterly refreshing: a completely honest Usenet posting... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From deets at nospam.web.de Thu Sep 20 18:53:40 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Sep 2007 00:53:40 +0200 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190325588.608625.259800@q3g2000prf.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> Message-ID: <5lgc0fF85chjU1@mid.uni-berlin.de> Python Maniac schrieb: > I am new to Python however I would like some feedback from those who > know more about Python than I do at this time. > > def scrambleLine(line): > s = '' > for c in line: > s += chr(ord(c) | 0x80) > return s > > def descrambleLine(line): > s = '' > for c in line: > s += chr(ord(c) & 0x7f) > return s These might benefit from using a lookup-dictionary that maps ord(c) to the outcome of the operation. Actually, it becomes twice as fast: import time lt = {} for i in xrange(255): lt[chr(i)] = chr(i | 0x80) def scrambleLine(line): s = '' for c in line: s += chr(ord(c) | 0x80) return s def scrambleLineLU(line): s = '' for c in line: s += lt[c] return s if __name__ == "__main__": line = "abcdefghijklmnop" * 1000000 start = time.time() scrambleLine(line) print time.time() - start start = time.time() scrambleLineLU(line) print time.time() - start Diez From steve at holdenweb.com Thu Sep 27 20:33:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Sep 2007 20:33:47 -0400 Subject: Importing Module To Use Variables In A Second Module In-Reply-To: References: Message-ID: rshepard at nospam.appl-ecosys.com wrote: > On 2007-09-27, Steve Holden wrote: > >> Self-evidently you are *not* creating the variables you think you are in >> the variablePage module. Have you tried an interactive test? Try this at >> the interpreter prompt: >> >>>>> import variablePage >>>>> dir(variablePage) >> and you will see exactly what names the module is defining in its >> namespace. You could also try >> >>>>> variablePage.__file__ >> to make sure that you are importing the module you think you are. > > Steve, > > Many thanks. > > I _think_ the problem is that the wxPython objects are not instatiated > when I'm trying to access the variables. Since they are instance variables, > they just don't exist yet. > > Learning just when wxPython objects are instantiated is something I've > just begun to do. > > Rich That could be. If they are instance variables, however, you will find you have to access them as variablePage.instancename.attributename regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From hassen62 at voila.fr Sun Sep 16 20:52:43 2007 From: hassen62 at voila.fr (hassen62 at voila.fr) Date: Mon, 17 Sep 2007 02:52:43 +0200 (CEST) Subject: reading xls file using xlrd Message-ID: <3555304.1120741189990363111.JavaMail.www@wwinf4624> Hi, I have installed Xlrd 0.6.1 Win 32. I have a file xls say "file.xls" located as follows:c:/file.xls. This file is composed with two columns of 5 lines. These columns are headed with "Col1" and "Col2", also the 5 rows are named with "Row1",...,"Row2". I have a silly question: What I can do to read this file from The Shell? Thank you very much, Hassen. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andre.roberge at gmail.com Thu Sep 6 18:36:40 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Thu, 06 Sep 2007 22:36:40 -0000 Subject: why should I learn python In-Reply-To: <1189117798.506367.278560@y42g2000hsy.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <1189117798.506367.278560@y42g2000hsy.googlegroups.com> Message-ID: <1189118200.040934.151520@57g2000hsv.googlegroups.com> On Sep 6, 7:29 pm, windandwaves wrote: > On Sep 7, 9:50 am, James Stroud wrote: > > > Seewww.python.org. Trust us all when we say that its the best. > > I get that feeling - yes. Question is: > > 1. what is it good for? Pretty much any programming task, except perhaps those that require extreme computation speed (like weather modeling). > 2. why is it so good? Easy to read, easy to write, good libraries and, I have found, an extremely helpful community. Hobbyists (like me) can work on projects written in Python on and off (sometimes for weeks if not months without programming) and be able to resume the work very quickly (because it's so easy to read and understand the code). Andr? > > I would love to hear some opinions. > > Cheers > > Nicolaas From steve at holdenweb.com Tue Sep 18 21:54:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Sep 2007 21:54:11 -0400 Subject: Custom PYTHONPATH not being seen by -m In-Reply-To: <1190158958.441168.307740@q3g2000prf.googlegroups.com> References: <1190158958.441168.307740@q3g2000prf.googlegroups.com> Message-ID: Vince Castellano wrote: > Hello, > > I am running RHEL5, with Python 2.4.3. I do not experience this > problem on my other machines, which are 2.5. > > The following should demonstrate my issue: > > [16:38][vince:~]$ python -m srctools.symbol_replace -h > python: module srctools.symbol_replace not found > [16:40][vince:~]$ python > Python 2.4.3 (#1, Dec 11 2006, 11:38:52) > [GCC 4.1.1 20061130 (Red Hat 4.1.1-43)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import srctools.symbol_replace >>>> srctools.symbol_replace > symbol_replace.py'> > [16:41][vince:~]$ echo $PYTHONPATH > /usr/local/pymodules > I suspect if you read "What's new in Python 2.5" you will find that the semantics of the -m option changed between the two releases. Let me see ... right, here it is: """ The -m switch added in Python 2.4 to execute a module as a script gained a few more abilities. Instead of being implemented in C code inside the Python interpreter, the switch now uses an implementation in a new module, runpy. The runpy module implements a more sophisticated import mechanism so that it's now possible to run modules in a package such as pychecker.checker. The module also supports alternative import mechanisms such as the zipimport module. This means you can add a .zip archive's path to sys.path and then use the -m switch to execute code from the archive. """ (from http://docs.python.org/whatsnew/pep-338.html). In other words, 2.4 specifically didn't allow the command line import of package submodules. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From carsten at uniqsys.com Mon Sep 24 06:19:12 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Sep 2007 06:19:12 -0400 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <5lpgfuF95s07U3@mid.uni-berlin.de> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> <1190419720.811685.145880@r29g2000hsg.googlegroups.com> <46f6eb3d$0$32060$426a34cc@news.free.fr> <1190606861.982113.25240@d55g2000hsg.googlegroups.com> <46f786cc$0$8901$426a74cc@news.free.fr> <5lpgfuF95s07U3@mid.uni-berlin.de> Message-ID: <1190629152.3385.2.camel@dot.uniqsys.com> On Mon, 2007-09-24 at 10:05 +0000, Marc 'BlackJack' Rintsch wrote: > On Mon, 24 Sep 2007 11:43:59 +0200, Bruno Desthuilliers wrote: > > > You already can create functions without using the def statement: > > > > Help on class function in module __builtin__: > > > > class function(object) > > | function(code, globals[, name[, argdefs[, closure]]]) > > | > > | Create a function object from a code object and a dictionary. > > | The optional name string overrides the name from the code object. > > | The optional argdefs tuple specifies the default argument values. > > | The optional closure tuple supplies the bindings for free variables. > > | > > Where the heck does *this* come from? Neither Python 2.5.1 nor the > 3.0alpha has this in `__builtin__`. It comes from the 'new' module: >>> import new >>> help(new.function) Help on class function in module __builtin__: ... Oddly enough, the help misrepresents which module the function is coming from. -- Carsten Haese http://informixdb.sourceforge.net From ladynikon at gmail.com Fri Sep 14 21:28:12 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 14 Sep 2007 21:28:12 -0400 Subject: vi and python In-Reply-To: <1189818866.523024.196320@g4g2000hsf.googlegroups.com> References: <1189818866.523024.196320@g4g2000hsf.googlegroups.com> Message-ID: <59f9c5160709141828v554c37b6i564f444fd79633c6@mail.gmail.com> Thanks for the link, Apparently when I added python into my use list. Python support was added it :D. I <3 gentoo. From __peter__ at web.de Wed Sep 12 11:35:53 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Sep 2007 17:35:53 +0200 Subject: Get Only the Last Items in a Traceback References: <1189562968.529414.27910@w3g2000hsg.googlegroups.com> <1189609742.781671.143320@g4g2000hsf.googlegroups.com> Message-ID: Am Wed, 12 Sep 2007 15:09:02 +0000 schrieb gregpinero at gmail.com: > On Sep 12, 5:17 am, Peter Otten <__pete... at web.de> wrote: >> >> Your assessment is wrong. You only get the extra lines in the traceback if >> you don't immediately wrap the exec statement in a try ... except block: >> $ cat snip_traceback3.py >> import sys >> import traceback >> >> def alpha(): >> beta() >> >> def beta(): >> gamma() >> >> def gamma(): >> try: >> exec s in {} >> except Exception, e: >> etype, value, tb = sys.exc_info() >> traceback.print_exception(etype, value, tb.tb_next) >> >> s = """ >> def delta(): >> epsilon() >> >> def epsilon(): >> 1/0 >> delta() >> """ >> >> if __name__ == "__main__": >> alpha() >> >> $ python snip_traceback3.py >> Traceback (most recent call last): >> File "", line 7, in >> File "", line 3, in delta >> File "", line 6, in epsilon >> ZeroDivisionError: integer division or modulo by zero >> >> Heureka. > Thanks for the help, Peter. That's exactly what I need. Indeed. But not exactly what you want, it seems. > Now could I > use your tb.tb_next trick a couple times and thus avoid moving the try/ > except? Of course you can cut off the traceback at arbitrary positions. Here's an example that uses the filename: import traceback import sys def tb_filename(tb): return tb.tb_frame.f_code.co_filename def tb_iter(tb): while tb is not None: yield tb tb = tb.tb_next def alpha(): try: beta() except Exception, e: etype, value, tb = sys.exc_info() filename = tb_filename(tb) for tb in tb_iter(tb): if tb_filename(tb) != filename: break traceback.print_exception(etype, value, tb) def beta(): gamma() def gamma(): exec s in {} s = """ def delta(): epsilon() def epsilon(): 1/0 delta() """ if __name__ == "__main__": alpha() Did I mention it already? It's better to move the try ... except. Peter From m.n.summerfield at googlemail.com Fri Sep 14 03:12:48 2007 From: m.n.summerfield at googlemail.com (Mark Summerfield) Date: Fri, 14 Sep 2007 07:12:48 -0000 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189733708.659317.83950@y42g2000hsy.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> <7xps0mmig9.fsf@ruckus.brouhaha.com> <1189733708.659317.83950@y42g2000hsy.googlegroups.com> Message-ID: <1189753968.917636.310120@19g2000hsx.googlegroups.com> On 14 Sep, 02:35, J?rgen Urner wrote: > Puh, what a discussion... most common use case I can think of is > > >> d = {'a': 1, 'b': 2, 'c': 3} > >> for key in d: > >> # do something that relies on order of keys as specified in the constructor > > It's a bit tireing having to type > > >> for key in sorted(d.keys()): > >> do_somethig_with(d[key]) > > instead of a trustfully > > >> for value in d.values(): > >> do_somethig_with(value) > > As far as I can see much cleaner. No black magic needed ++ sort the > dict > to another order and rely on the sort order being stable would be a > really > a nice thing to have. > > My 2 cents, J?rgen What I envisage is: d = ordereddict(a=1, x=20, b=35, m=4) # some time later d["e"] = 15 # later still d["b"] = 70 d.keys() # returns ['a', 'b', 'e', 'm', 'x'] d.values() # returns [1, 70, 15, 4, 20] So no matter _when_ you add because the underlying data structure is ordered (by key) you can always get access in key order. Also, you can't "sort" the ordereddict; it is in key order and that's it. The whole point is that you can use these things and never have to sort; if you need different orders you create extra ordereddicts with suitably munged keys and with values that are object references to the objects you are interested in. In reply to James Stroud: - The reason you can't assign a slice is that the index positions depend on the keys, so if you do: od[newkey] = newvalue where newkey goes (i.e., its index position) depends on how it orders in relation to the rest, so it could go "anywhere". I now feel that offering a slice is wrong because the [] syntax is used for access by key, whereas a slice would be for access by index, so using [] for both would be v. confusing. - James proposed better method names which I've adopted (see later), but I don't think set_value() should be set() because that would make it seem to be the partner of get(), whereas get() uses a key and set_value() uses an index for lookup. - James also suggested a name and behaviour change: keys(fromindex : int = None, uptobutexcludingindex : int = None) - > ordered list of keys So keys() called on its own behaves just like dict.keys() (except that all the keys are returned in order), but with one argument returns the keys with index positions from the given index to the end, and with two arguments returns the keys in the given range of indexes. (Note: in an ordereddict values() returns all the values in key order.) So from the earlier example: d.key(2) # returns 'e' d.item(3) # returns ('m', 4) d.value(4) # returns 20 d.set_value(3, 99) # maybe returns 'm'; but anyway d.value(3) and d['m'] now both return 99 - James (and some others) also felt that insertions should just go as key/value pairs at the end. But that is not what I'm proposing (that's a completely different data structure). The whole point of ordereddict is that whatever you insert and whenever you insert it, the ordereddict is always in key order. Paul Rubin and at least one other person mentioned the use of an AVL tree. At the moment I just want to see if I can get enough consensus on an API and behaviour so that I could put in a PEP for just one ordered data structure. So to clarify, here's the entire API I'm proposing for ordereddict. In all cases the ordereddict is always in (and kept in) key order, and any method that returns a list or iterator always returns that list or iterator (whether of keys or values) in key order: ordereddict(dictionary=None) The argument can be a dict or another ordereddict; all the dict() initializer approaches should also be supported. ordereddict.update(dictonary=None, **kwargs) Same as dict.update()---except that key order is preserved (a point I won't repeat in the others when I say "same as dict", but which is true throughout) @classmethod ordereddict.fromkeys(cls, iterable, value=None) # Same as dict ordereddict.key(index : int) -> key Returns the index-th item's key ordereddict.item(index : int) -> (key, value) Returns the index-th item ordereddict.value(index : int) -> value Returns the index-th item's value ordereddict.set_value(index : int, value) Sets the index-th item's value to value; raises IndexError if index is out of range. If not expensive, maybe return the key. ordereddict.copy() # Same as dict. ordereddict.clear() # Same as dict. ordereddict.get(key, value=None) # Same as dict ordereddict.setdefault(key, value) # Same as dict ordereddict.pop(key, value) # Same as dict ordereddict.popitem() # Same as dict ordereddict.keys(fromindex : int = None, uptoindex : int : None) -> list of keys Returns an ordered list of keys, or a slice of keys if one or two indexes is given ordereddict.values() # Same as dict ordereddict.items() # Same as dict ordereddict.iterkeys() # Same as dict ordereddict.itervalues() # Same as dict ordereddict.iteritems() # Same as dict ordereddict.has_key() # Same as dict Also the same as dict (and as always, working in key order): for key in d: pass if key in d: pass len(d) del d[key] d[key] d[key] = value What this means is that users could drop in an ordereddict in place of a plain dict and get the same behaviour (maybe not the same performance!), but would now find that they could rely on the ordering of keys, as well as having just four additional methods and one existing method with additional optional arguments. From steve at holdenweb.com Mon Sep 10 15:34:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Sep 2007 15:34:52 -0400 Subject: Checking if elements are empty In-Reply-To: References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> <46e2013a$0$7687$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Neil Cerutti wrote: > On 2007-09-10, Chris Mellon wrote: >> On 9/10/07, Neil Cerutti wrote: >>> Agreed; but I prefer 'if y[0] == ""', absent more context and >>> better names. >> Probably should use u"" if you're going to take that route, as >> this will fail spuriously if y[0] contains a unicode string >> that can't be implicitly converted to ascii. Personally, I >> prefer the boolean check and I'll let operations fail elsewhere >> if there's a type mismatch. > > I have a quibble not with the functionality of the boolean check, > but with its expressiveness. if y[0] == "" expresses more, i.e., > that I expect y[0] to contain a Python byte string. > I have a quibble with a test that will raise an exception when the anticipated condition is true. Your test is patently absurd, as you would have discovered had you bothered to try it: >>> y = "" >>> if y[0] == "": ... print "True" ... else: ... print "False" ... Traceback (most recent call last): File "", line 1, in IndexError: string index out of range >>> Further, when the string is *not* the null string the test will always return False, as you will be comparing two strings of unequal length. So, absent a solution that works, len(y) == 0 looks pretty good. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From zentraders at gmail.com Thu Sep 13 21:14:59 2007 From: zentraders at gmail.com (Zentrader) Date: Thu, 13 Sep 2007 18:14:59 -0700 Subject: Decimal formatting In-Reply-To: <1189716651.810481.260850@y42g2000hsy.googlegroups.com> References: <1189716651.810481.260850@y42g2000hsy.googlegroups.com> Message-ID: <1189732499.480959.143760@g4g2000hsf.googlegroups.com> The documentation is here http://docs.python.org/lib/typesseq-strings.html From arnodel at googlemail.com Sat Sep 1 12:46:21 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 01 Sep 2007 09:46:21 -0700 Subject: nameerror upon calling function In-Reply-To: <1188662744.345071.123610@57g2000hsv.googlegroups.com> References: <1188662744.345071.123610@57g2000hsv.googlegroups.com> Message-ID: <1188665181.459022.44520@o80g2000hse.googlegroups.com> On Sep 1, 5:05 pm, seancron wrote: > Hi, > > I have a program that makes a call to a function in a different python > script that I wrote. But, when I call the function I get the > following error: > > NameError: global name 'WSDL' is not defined > > I can't figure out why I'm getting this error since WSDL should be > defined. Here are the two scripts: > > weatherpy.py > from xml.dom import minidom > from SOAPpy import WSDL The statement above needs to be in libndfdsoap.py, not here. > from libndfdsoap import ByDaySOAPRequest > > wsdlfile = 'http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ > ndfdXML.wsdl' > > if __name__ == '__main__': > ByDaySOAPRequest(39.0000, -77.0000, 2004-04-27, 7, '12 hourly') > > libndfdsoap.py > def ByDaySOAPRequest(latitude, longitude, startDate, numDays, > hrFormat): > """Sends a SOAP request using the NDFDgenByDay method and stores > the > response in a file called weather.xml""" > > wsdlfile = 'http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ > ndfdXML.wsdl' > server = WSDL.Proxy(wsdlfile) > response = server.NDFDgenByDay(latitude, longitude, startDate, > numDays, > hrFormat) > xml = open('/weather.xml', 'w') > xml.write(response) > xml.close() > return > > Can somebody please show me how to fix this error? HTH -- Arnaud From cjt22 at bath.ac.uk Mon Sep 10 11:48:58 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Mon, 10 Sep 2007 08:48:58 -0700 Subject: Using a time duration to print out data where every 2 seconds is a pixel In-Reply-To: <1189436278.456311.128260@22g2000hsm.googlegroups.com> References: <1189427545.322679.260970@r29g2000hsg.googlegroups.com> <1189436278.456311.128260@22g2000hsm.googlegroups.com> Message-ID: <1189439338.572188.20690@o80g2000hse.googlegroups.com> On Sep 10, 3:57 pm, cj... at bath.ac.uk wrote: > Thanks however I am still having a problem using the time module for > arithmetic > > My string times are of values such as 09:55:17 > > and I have code such as: > > >from time import * > >startPoint = strptime(step.sTime, "%H:%S:%M") > >finishPoint = strptime(step.fTime, "%H:%S:%M") > >duration = mktime(startPoint) - mktime(finishPoint) > > but it generates the error > > >OverflowError: mktime argument out of range > > Cheers Perhaps I need to import the datetime module? From BjornSteinarFjeldPettersen at gmail.com Sat Sep 29 14:13:26 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sat, 29 Sep 2007 11:13:26 -0700 Subject: Program inefficiency? In-Reply-To: References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> <1191087234.915654.182370@k79g2000hse.googlegroups.com> Message-ID: <1191089606.852125.276040@22g2000hsm.googlegroups.com> On Sep 29, 7:55 pm, Pablo Ziliani wrote: > thebjorn wrote: > > On Sep 29, 5:22 pm, hall.j... at gmail.com wrote: > > >> I wrote the following simple program to loop through our help files > >> and fix some errors (in case you can't see the subtle RE search that's > >> happening, we're replacing spaces in bookmarks with _'s) > >> (...) > > > Ugh, that was entirely too many regexps for my taste :-) > > > How about something like: > > > def attr_ndx_iter(txt, attribute): > > (...) > > def substr_map(txt, indices, fn): > > (...) > > def transform(s): > > (...) > > def zap_spaces(txt, *attributes): > > (...) > > def mass_replace(): > > (...) > > Oh yeah, now it's clear as mud. I'm anxiously awaiting your beacon of clarity ;-) > I do think that the whole program shouldn't take more than 10 lines of > code Well, my mass_replace above is 10 lines, and the actual replacement code is a one liner. Perhaps you'd care to illustrate how you'd shorten that while still keeping it "clear"? > using one sensible regex I have no doubt that it would be possible to do with a single regex. Whether it would be sensible or not is another matter entirely... > (impossible to define without knowing the real input and output formats). Of course, but I don't think you can guess too terribly wrong. My version handles upper and lower case attributes, quoting with single (') and double (") quotes, and any number of spaces in attribute values. It maintains all other text as-is, and converts spaces to underscores in href and name attributes. Did I get anything majorly wrong? > And (sorry to tell) I'm convinced this is a problem for regexes, in > spite of anybody's personal taste. Well, let's see it then :-) smack-smack'ly y'rs -- bjorn From robert.kern at gmail.com Sat Sep 15 23:21:37 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 15 Sep 2007 22:21:37 -0500 Subject: how to join array of integers? In-Reply-To: <13eoniohphkjs95@corp.supernews.com> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <46EBE498.9040800@ehas.org> <13eo1rb73mg8b77@corp.supernews.com> <13eoniohphkjs95@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-09-15, Robert Kern wrote: >> Grant Edwards wrote: >>> On 2007-09-15, Erik Jones wrote: >>> >>>>>> print ''.join([str(i) for i in [1,2,3]]) >>>>> It's better to use generator comprehension instead of LC: >>>>> >>>>> ",".join(str(i) for i in [1, 2, 3]) >>>> Why is that? That entire expression must be evaluated to >>>> obtain the result, so what is the advantage of using a >>>> generator comprehension v. a list comprehension? >>> The generator avoids creating the intermediate list -- it >>> generates the intermediate values on the fly. For short >>> sequences it probably doesn't matter much. For a very long >>> list it's probably noticable. >> Not true. str.join() creates a list from the iterator if it is >> not already a list or a tuple. > > So the iterator avoids creating an intermediate list, but the > join method goes ahead and does it anyway? Yup. >> In Objects/stringobject.c, look at string_join(); it calls >> PySequence_Fast() on the argument. Looking in >> Objects/abstract.c, we see that PySequence_Fast() >> short-circuits lists and tuples but builds a full list from >> the iterable otherwise. > > So what's the point of iterables if code is going to do stuff > like that when it wants to iterate over a sequence? Some code dealing with sequences can be recast in terms of iterators of unknown length. Some can't. Some are better cast in terms of iterators than sequences; some aren't. >> map() seems to reliably be the fastest option, > > Which is apparently going away in favor of the slower iterator > approach? It's only slower in this case. Of course, the main difference is where the loop takes place, in C or in Python. imap() appears to give the same performance as map(). -- 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 samsamrober at yahoo.com Fri Sep 14 02:48:52 2007 From: samsamrober at yahoo.com (samsamrober at yahoo.com) Date: Fri, 14 Sep 2007 06:48:52 -0000 Subject: IT News Message-ID: <1189752532.909252.154580@50g2000hsm.googlegroups.com> Hey watchout IT related News and Blog on www.itnewz.net From deets at nospam.web.de Tue Sep 11 02:13:04 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 11 Sep 2007 08:13:04 +0200 Subject: Need a KDE app, where to find a coder? In-Reply-To: References: Message-ID: <5kmq00F4d2c9U2@mid.uni-berlin.de> Dotan Cohen schrieb: > I need an application, and I'd like it to be written in Python with QT > as I am a KDE user. I simply don't have the time to code it myself, as > I've been trying to find the time for half a year now. > > What are some reputable websites for finding Python coders? If anyone > on the list wants the job, this is what I need: > > I need a hierarchical list manager, similar to ListPro > (http://www.iliumsoft.com/site/lp/listpro.htm) which is the app that > I'm replacing. Specifically, I need the checkmark (boolen), item > (string), date, amount (int/100), and notes fields. As KDE is moving > to QT4 in December (with the release of KDE4) it would be best if the > app were coded with this in mind. As the application is for my own > personal use, I will try to maintain it with the little python that I > know, but I may need help along the way. There are a few places to ask - like guru.com. But you most probably will have to make a financial offer. Apart from that - do you know basket? It's integrated into kontact, and maybe does what you want. Diez From gh at gregor-horvath.com Fri Sep 7 07:41:07 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 07 Sep 2007 13:41:07 +0200 Subject: Class design (information hiding) In-Reply-To: References: Message-ID: <42d6c$46e138d3$547078de$10495@news.chello.at> Alexander Eisenhuth schrieb: > > I'm wodering how the information hiding in python is ment. As I > understand there doesn't exist public / protected / private mechanism, > but a '_' and '__' naming convention. > > As I figured out there is only public and private possible as speakin in > "C++ manner". Are you all happy with it. What does "the zen of python" > say to that design? (protected is useless?) My favourite thread to this FAQ: http://groups.google.at/group/comp.lang.python/browse_thread/thread/2c85d6412d9e99a4/b977ed1312e10b21#b977ed1312e10b21 Greg From kbloom at gmail.com Wed Sep 19 11:38:07 2007 From: kbloom at gmail.com (Ken Bloom) Date: Wed, 19 Sep 2007 15:38:07 GMT Subject: The meaning of a = b in object oriented languages References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> <1190098656.030658.66380@57g2000hsv.googlegroups.com> <_4OdnQm5joyO1m3bnZ2dnUVZ_tuonZ2d@comcast.com> Message-ID: On Tue, 18 Sep 2007 18:02:59 -0400, Lew wrote: > Summercool wrote: >> when a writing or a book reads "a is a Hash object; a is an Array >> object; or a is an Animal object" it is just a short form to say that >> "a is a reference to that object." >> >> b = a means "whatever a is referencing to, now b is referencing it >> too". >> >> so that's why a[1] = "foobar" will change what b will display, but a >> = "foobar" will not change what b will display. > > You can't do both in Java. Is a an array or a String? If a is a String > and b is an array, then neither `a = b' nor `b = a' will compile in > Java. > > Java is a strongly-typed, compiled language which means it does more > static type checking and thus would reject treating a as both an array > and a String. > In that environment the programmer must choose one or the other. In this Java example, a and b are statically typed to be of type Object. Both Strings and Arrays descend from Object. (And primatives like integers and the like will be autoboxed into descendants of Object). -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/ From joemystery123 at gmail.com Thu Sep 20 15:33:31 2007 From: joemystery123 at gmail.com (joemystery123 at gmail.com) Date: Thu, 20 Sep 2007 19:33:31 -0000 Subject: Python Regex Question Message-ID: <1190316811.760038.145850@50g2000hsm.googlegroups.com> I need to extract the number on each  49.950  The actual number between:  49.950  can be any number of digits before decimal and after decimal.  ######.####  How can I just extract the real/integer number using regex? From andrew.arobert at gmail.com Sun Sep 2 16:22:55 2007 From: andrew.arobert at gmail.com (andrew.arobert at gmail.com) Date: Sun, 02 Sep 2007 20:22:55 -0000 Subject: Automation and scheduling of FrontPage publishing using Python In-Reply-To: <1188701337.798785.188420@19g2000hsx.googlegroups.com> References: <1188517723.279932.299400@x40g2000prg.googlegroups.com> <1188698223.393723.151140@d55g2000hsg.googlegroups.com> <1188701337.798785.188420@19g2000hsx.googlegroups.com> Message-ID: <1188764575.438204.117420@r34g2000hsd.googlegroups.com> On Sep 1, 10:48 pm, Jerry wrote: > andrew, > > I would try looking into Windows automation with Python.http://www.google.com/search?q=windows+automation+pythonshould get > you started. The winGuiAuto package may help you out as it is like > have a human click and move throughout the interface. The only > downside is that there is no recorder to help you build the script, so > I would try to do as much in VBA as you can (does FrontPage even > support VBA?) and then just write your python script to get through > the program enough to execute the macro. Yes.. Front page can be run by VB macro but I really did not want to go down that road if it could be avoided. This looks very promising. I've installed the module and run a couple of the basic examples.. Very cool. From bignose+hates-spam at benfinney.id.au Thu Sep 13 05:32:37 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 13 Sep 2007 19:32:37 +1000 Subject: Coming from Perl References: <1189644803.816375.269950@y42g2000hsy.googlegroups.com> Message-ID: <87y7fa52ru.fsf@benfinney.id.au> Amer Neely writes: > Well, I have checked everything I can but I'm getting '500 Internal > Server Error'. This is the HTTP response code saying that the program that should have served the response document instead exited with an error. To debug, you should first run the program (or at least the part that you're trying to implement) *outside* the context of a web server. Do it at a command line, and any errors will show up as exception tracebacks. Only when you have something that performs correctly outside a web server context should you consider how to wrap it in that new (harder-to-debug) context. -- \ "What if the Hokey Pokey IS what it's all about?" ?anonymous | `\ | _o__) | Ben Finney From gagsl-py2 at yahoo.com.ar Mon Sep 17 17:59:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Sep 2007 18:59:06 -0300 Subject: qa References: <46EEEE71.80108@gmail.com> Message-ID: En Mon, 17 Sep 2007 18:15:29 -0300, Shawn Minisall escribi?: > I'm trying to get a space in between these two strings but it's ignoring > the space in between when it prints. > > >>> string.capwords (string.join([s1 + " " + s2])) * 3 > 'Spam Ni!Spam Ni!Spam Ni!' > >>> It doesn't matter how many spaces you put in between, capwords will collapse all of them into a single space. py> from string import capwords py> help(capwords) Help on function capwords in module string: capwords(s, sep=None) capwords(s, [sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. Note that this replaces runs of whitespace characters by a single space. py> capwords(" hello world ") 'Hello World' py> ' '.join([capwords(" hello world ")] * 3) 'Hello World Hello World Hello World' Is that what you want? -- Gabriel Genellina From jbuturff at gmail.com Mon Sep 24 10:34:37 2007 From: jbuturff at gmail.com (Horse) Date: Mon, 24 Sep 2007 14:34:37 -0000 Subject: shutil.copy2 error Message-ID: <1190644477.380312.261840@d55g2000hsg.googlegroups.com> I've written a python script that copies a nightly Oracle backup file to another server. Every couple days, the script fails with this error message: Error copying Q:/Oradata/GISPROD/Backups/3UISN35R_1_1 to s:/gisprod/ backups/3UISN35R_1_1 [Errno 22] Invalid argument Here's the code for the function I'm running. The path names are all correct, and it works *most of the time*. It only fails about once or twice a week. Anyone know where I can get more info on this "errno 22 invalid argument"? def CopyNewFiles(SOURCE_DIR, DEST_DIR): global STATUS try: os.chdir(SOURCE_DIR) for x in os.listdir(SOURCE_DIR): int_time = os.stat(x)[stat.ST_CTIME] str_time = time.ctime(int_time) if datetime.date.fromtimestamp(int_time + 0.00) > YESTERDAY: try: DEST_FILE = os.path.join(DEST_DIR, x) logfile.write(" Copying " + SOURCE_DIR + x + " to " + DEST_FILE + "\n") logfile.flush() if not os.path.isfile(DEST_FILE): shutil.copy2(x, DEST_FILE) else: logfile.write(" File exists. Skipping. \n") logfile.flush() except (IOError, os.error), why: logfile.write("\n\nError copying " + SOURCE_DIR + x + " to " + DEST_FILE + "\n\n") logfile.write("\n" + str(why) + "\n") logfile.flush() STATUS = "FAILED" except: logfile.write("\n\nUnhandled error in CopyNewFiles\n\n") logfile.write("SOURCE_DIR = " + SOURCE_DIR + "\n") logfile.write("DEST_DIR = " + DEST_DIR + "\n") logfile.flush() STATUS = "FAILED" From stodge at gmail.com Mon Sep 17 12:01:58 2007 From: stodge at gmail.com (Stodge) Date: Mon, 17 Sep 2007 09:01:58 -0700 Subject: Saving parameters between Python applications? In-Reply-To: <46ee8be6$0$14822$426a74cc@news.free.fr> References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> <46ee8be6$0$14822$426a74cc@news.free.fr> Message-ID: <1190044918.623773.215920@50g2000hsm.googlegroups.com> You're probably right! Thanks all. :) On Sep 17, 10:15 am, Bruno Desthuilliers wrote: > Stodge a ?crit : > > > > > I'm trying to do the following. I have a Python application that is > > run: > > > python app1.py --location=c:\test1 > > > What I want to do is save the location parameter, so I can then do (in > > the same window): > > > python app2.py > > > And have app2.py automatically have access to the value of "location". > > > Now, the difficult part is, that in another window I want to do: > > > python app1.py --location=c:\test2 > > python app2.py > > > And have app2.py automatically get c:\test2 as the location. So the > > two windows (consoles) are isolated from each other. > > > I thought I could use os.environ, but that doesn't save the variable > > for applications that are run afterwards in the same window. > > > Any suggestions? > > Yes : pass the same arg to both app1.py and app2.py !-) > > Braindead, I know, but still the simplest solution. From jgardner.jonathangardner.net at gmail.com Thu Sep 6 18:06:56 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Thu, 06 Sep 2007 22:06:56 -0000 Subject: why should I learn python In-Reply-To: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: <1189116416.737240.31230@r34g2000hsd.googlegroups.com> On Sep 6, 2:32 pm, windandwaves wrote: > Can someone tell me why I should learn python? I am a webdeveloper, > but I often see Python mentioned and I am curious to find out what I > am missing out on. The reason I use Python is because I get more done quicker with fewer bugs. I used to be a huge perl fan after being a huge C/C++ fan, and Python is where I am right now and have been for the past 6 or more years. From cjt22 at bath.ac.uk Wed Sep 5 08:55:19 2007 From: cjt22 at bath.ac.uk (cjt22 at bath.ac.uk) Date: Wed, 05 Sep 2007 05:55:19 -0700 Subject: Accessing Module variables from another Module In-Reply-To: <46de9f7f$0$30604$426a34cc@news.free.fr> References: <1188981521.735630.133060@r29g2000hsg.googlegroups.com> <46de9f7f$0$30604$426a34cc@news.free.fr> Message-ID: <1188996919.321965.262830@k79g2000hse.googlegroups.com> On Sep 5, 1:22 pm, Bruno Desthuilliers wrote: > cj... at bath.ac.uk a ?crit : > > > Hi > > > I am new to Python (I have come from a large background of Java) and > > wondered if someone could explain to me how I can access variables > > stored in my main module to other functions within other modules > > called > > from this module > > (snip code) > > I am currently just passing the variable in as a parameter > > And this is the RightThing(tm) to do. > > > but I thought with Python there would be a way to gain direct access > > to > > storeList within the modules called from the top main module? > > Yes : passing it as a param !-) > > For other modules to get direct access to main.storeList, you'd need > these modules to import main in these other modules, which would > introduce circular dependencies, which are something you usuallay don't > want. Also, and while it's ok to read imported modules attributes, it's > certainly not a good idea to mutate or rebind them IMHO, unless you're > ok with spaghetti code. Cheers Bruno, I just wanted to make sure I was being consistent with the "Python way of things" :) From byte8bits at gmail.com Wed Sep 26 09:06:54 2007 From: byte8bits at gmail.com (byte8bits at gmail.com) Date: Wed, 26 Sep 2007 06:06:54 -0700 Subject: Script to extract text from PDF files In-Reply-To: References: <1190746968.162359.39890@r29g2000hsg.googlegroups.com> <1190747931.415834.75670@n39g2000hsh.googlegroups.com> Message-ID: <1190812014.319333.104720@22g2000hsm.googlegroups.com> On Sep 25, 10:19 pm, Lawrence D'Oliveiro wrote: > > Doesn't work that well... > > This is inherent in the nature of PDF: it's a page-description language, not > a document-interchange language. Each text-drawing command can put a block > of text anywhere on the page, so you have no idea, just from parsing the > PDF content, how to join these blocks up into lines, paragraphs, columns > etc. So (I'm not being a wise guy) how does pdftotext do it so well? The text I can extract from PDFs is extracted as it appears in the doc. Although there are various ways to insert and encode text in PDFs, it's also well documented in the PDF specifications (http:// www.adobe.com/devnet/pdf/pdf_reference.html). Going back to pdftotext... it works well at extracting text from PDF. I'd like a native Python library that does the same. This can be done. And, it can be done in Python. I've made a small start, my hope was that others would be interested in helping, but I can do it on my own too... it'll just take a lot longer :) Brad From frank at chagford.com Wed Sep 12 09:28:01 2007 From: frank at chagford.com (Frank Millman) Date: Wed, 12 Sep 2007 06:28:01 -0700 Subject: Is the wxPython list down? In-Reply-To: <1189602607.803546.180320@w3g2000hsg.googlegroups.com> References: <1189602607.803546.180320@w3g2000hsg.googlegroups.com> Message-ID: <1189603681.292154.186620@o80g2000hse.googlegroups.com> On Sep 12, 3:10 pm, kyoso... at gmail.com wrote: > Hi, > > Does anyone know if the wxPython mailing list is having issues? I > subscribe to it and haven't seen anything come through since > 09/06/2007. I went to ActiveState's archives and the last message > there is from the 7th (http://aspn.activestate.com/ASPN/Mail/Browse/ > Threaded/wxPython-users). > > Thanks, > > Mike This is from the wxPython home page - "(8-Sept-2007) Yes, the mail lists are down. There were multiple disk failures in RAID5 array of the machine that hosts the mail lists. The hardware has been replaced and data is being restored from tape backups." I noticed that cvs seems to be down as well - maybe it was on the same server. Frank From techrecruit07 at hotmail.com Sun Sep 9 00:13:40 2007 From: techrecruit07 at hotmail.com (TechRecruit Consultants) Date: Sat, 08 Sep 2007 21:13:40 -0700 Subject: req.in Unix/SQL/Oracle/JAVA - Work Location US Message-ID: <1189311220.567843.134390@o80g2000hse.googlegroups.com> Hi Greets! This is sandy,Working in TechRecruit Consultants,Chennai as Head Operaitons - Recruitment. Currently we have openning in Unix/SQL/Oracle/JAVA for ISO 9001:2000/ CMM LEVEL 5 Company in US. About the company:An ISO 9001:2000 /SEI-CMM Level 5 accreditation. Experience:4 - 7 Years Positions:Senior Level JOB LOCATION - US Candidate must also have experience in Unix, SQL, Oracle, and JAVA. Experience with Weblogic and scripting is also highly desirable. Must be a self-starter and have good communication skills. Sound procedures for debugging, coding and testing of changes is needed due to the criticality of the applications supported. Kindly forward your updated profile in Word doc. to sandy at techrecruit.net Please fill the following details and revertback to me. Current CTC: Expected CTC: Notice Period: DOB: Marital Status: Convenient time for Telephonic Interview: With Thanks and Regards, Sandy, Head Operations - Recruitment TechRecruit Consultants, India. From tim.couper at scivisum.co.uk Sat Sep 1 07:34:59 2007 From: tim.couper at scivisum.co.uk (Tim Couper) Date: Sat, 01 Sep 2007 12:34:59 +0100 Subject: So what exactly is a complex number? In-Reply-To: <46D944C8.6090802@wp.pl> References: <451mq4-les.ln1@ozzie.tundraware.com> <46D944C8.6090802@wp.pl> Message-ID: <46D94E63.8050701@scivisum.co.uk> "... I'd hazard a guess you were educated in the USA where doing without understanding has been mastered by teachers and students alike. You're explanation ... """ Grzegorz I think that this is unnecessarily offensive both to the poster and to the many teachers and students of quality in the USA. Maybe it wouldn't be so offensive in Poland, but in the world of first-language English speakers, it is. Tim "European" Couper Dr Tim Couper CTO, SciVisum Ltd www.scivisum.com Grzegorz S?odkowicz wrote: >> Here is a simple explanation (and it is not complete by a long shot). >> >> A number by itself is called a "scalar". For example, when I say, >> "I have 23 apples", the "23" is a scalar that just represents an >> amount in this case. >> >> One of the most common uses for Complex Numbers is in what are >> called "vectors". In a vector, you have both an amount and >> a *direction*. For example, I can say, "I threw 23 apples in the air >> at a 45 degree angle". Complex Numbers let us encode both >> the magnitude (23) and the direction (45 degrees) as a "number". >> >> There are actually two ways to represent Complex Numbers. >> One is called the "rectangular" form, the other the "polar" >> form, but both do the same thing - they encode a vector. >> >> Complex Numbers show up all over the place in engineering and >> science problems. Languages like Python that have Complex Numbers >> as a first class data type allow you do to *arithmetic* on them >> (add, subtract, etc.). This makes Python very useful when solving >> problems for engineering, science, navigation, and so forth. >> >> >> HTH, >> >> > You're mixing definition with application. You didn't say a word about > what complex numbers are, not a word about the imaginary unit, where > does it come from, why is it 'imaginary' etc. Since we're being arses > here I'd hazard a guess you were educated in the USA where doing without > understanding has been mastered by teachers and students alike. You're > explanation of what vectors are is equally bogus but this has already > been pointed out. I'd also like to see a three-dimensional vector > represented by a complex number. > > Besides, I find Wikipedia extremely unhelpful for learning maths, partly > beacuse of it's non-linear nature (while reading an article you come > across a term you don't know, follow a link, then follow three others > and over the next 4 hours you find out lots of interesting things which > are sadly at best tangential to the initial subject) and because it's > written by people who already know a lot about the subject and take many > things for granted. This seems to be a decent introduction: > http://www.ping.be/~ping1339/complget.htm > > Regards, > Greg > From steve at holdenweb.com Wed Sep 19 08:25:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Sep 2007 08:25:43 -0400 Subject: HTTP Protocol Client In-Reply-To: <1190196708.261138.233490@e9g2000prf.googlegroups.com> References: <1190196708.261138.233490@e9g2000prf.googlegroups.com> Message-ID: welcomestocontact at gmail.com wrote: > Hi, > > I am writing http protocol to get some data from servers. If i was > using my localhost, getting replay from local and if want access other > remote sites, i am getting error. Please reply it > > My localhost client script::: > > Code: ( python ) > > > import httplib > > h = httplib.HTTP('localhost',80) > > h.putrequest('GET','') > > h.putheader('User-Agent','Lame Tutorial Code') > > h.putheader('Accept','text/html') > > h.endheaders() > > errcode,errmsg, headers = h.getreply() > > print errcode,errmsg, headers > > > f = h.getfile() # Get file object for reading data > > data = f.read() > > print data > > f.close() > > > > > > the Reply getting from this:::: > > > 403 Forbidden Date: Tue, 18 Sep 2007 05:20:36 GMT > > Server: Apache/2.0.52 (Red Hat) > > Accept-Ranges: bytes > > Content-Length: 3985 > > Connection: close > > Content-Type: text/html; charset=UTF-8 > > And some Html script > > > > > If I want to access other sites::: > > > import httplib > > h = httplib.HTTP('http://Google.com',80) > > h.putrequest('GET','') > > h.putheader('User-Agent','Lame Tutorial Code') > > h.putheader('Accept','text/html') > > h.endheaders() > > > > errcode,errmsg, headers = h.getreply() > > print errcode,errmsg, headers > > > f = h.getfile() # Get file object for reading data > > data = f.read() > > print data > > f.close() > > > I got the error like::: > > Traceback (most recent call last): > File "c.py", line 6, in ? > h.endheaders() > File "/usr/lib/python2.3/httplib.py", line 712, in endheaders > self._send_output() > File "/usr/lib/python2.3/httplib.py", line 597, in _send_output > self.send(msg) > File "/usr/lib/python2.3/httplib.py", line 564, in send > self.connect() > File "/usr/lib/python2.3/httplib.py", line 532, in connect > socket.SOCK_STREAM): > socket.gaierror: (-2, 'Name or service not known') > > > How can I access Remote sites using http protocol . I did'nt write > server script. > I would recommend taking a look at urllib or urllib2 if you just want to write an HTTP client that accesses the server output, there is no need to re-implement low-level HTTP calls. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From mensanator at aol.com Thu Sep 13 13:19:20 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 13 Sep 2007 10:19:20 -0700 Subject: An ordered dictionary for the Python library? In-Reply-To: <1189664832.876539.86800@k79g2000hse.googlegroups.com> References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <7xzlzrtrjn.fsf@ruckus.brouhaha.com> <1189664832.876539.86800@k79g2000hse.googlegroups.com> Message-ID: <1189703960.978455.124440@d55g2000hsg.googlegroups.com> On Sep 13, 1:27 am, Mark Summerfield wrote: > On 13 Sep, 00:03, Paul Rubin wrote: > > > Mark Summerfield writes: > > > I feel that Python lacks one useful data structure: an ordered > > > dictionary. > > > Do other Python programmers feel this lack? Is this worth a PEP? > > > Yes. It should use a functional data structure. > > Could you elaborate? > > Here's my impression of the postings so far: there are 3 categories of > response: > > (A) There is no need for such a thing. > > (B) It is useful, but so easy to implement that it needn't be in the > library. > > (C) It is worth having an ordered data structure of some kind. > > Regarding (A) and (B): I remember Python before it had the sets > module. "There's no need for sets, you can do them with dicts". > Thankfully sets are in the language and I for one use them > extensively. > > For (C) what I had in mind was: > > An API that is identical to a dict, with the few additional methods/ > behaviours listed below: > - If an item is inserted it is put in the right place (because the > underlying data structure, b*tree, skiplist or whatever is > intrinsically ordered by < on the key) > - Extra methods > key_at(index : int) -> key > item_at(index : int) -> (key, value) > value_at(index : int) -> value > set_value_at(index : int, value) # no return value necessary but > maybe key if convenient > od[x:y:z] -> list of values ordered by key # can read a slice but > not assign a slice > and maybe > keys_for(fromindex : int, uptobutexcludingindex : int) -> ordered > list of keys > > I've given examples of the use cases I envisage (and that I use in > both Python with my own ordered dict and in C++ with the map class) in > a previous posting, and I've shown the API I envisage above. I know > that some people might prefer ordering by value or the option of case- > insensitive ordering, but both these can be achieved using the API > above, e.g., > od[value.lower()] = value # case-insensitive ordering of list of > values > And as for duplicates there are two approaches I use: (1) make each > string unique as I showed in my previous post, or (2) use a value that > itself is a list, dict or set. > (As for those who have suggested an ordered data structure that isn't > a dict, I don't see a conflict, I'd be happy to see more data > structures in the collections module.) > > Is what I've suggested sufficient (and sufficiently general) for the > standard library? Is the index the insertion order? The only use I have an ordered dictionary is to quickly determine that a sequence value is the first duplicate found (the structure can have millions of numbers) and then play back (so they don't have to be re-calculated) the sequence from the first duplicate to the end. So I would get the index when I find the duplicate and then iterate data[index:] to get the sequence in insertion order? > If it is not, what should be done, or is there some > other approach and API that would better provide the functionality > envisaged? From Summercoolness at gmail.com Mon Sep 17 03:33:21 2007 From: Summercoolness at gmail.com (Summercool) Date: Mon, 17 Sep 2007 07:33:21 -0000 Subject: where are the .pyc files? In-Reply-To: References: <1189963710.714191.74440@n39g2000hsh.googlegroups.com> <5l57t1F655kfU5@mid.uni-berlin.de> <1189992200.860524.58620@w3g2000hsg.googlegroups.com> Message-ID: <1190014401.434666.110610@19g2000hsx.googlegroups.com> On Sep 16, 6:56 pm, Steve Holden wrote: > Summercool wrote: > > how come a program that runs directly doesn't need to be optimized > > into bytecode first? Or... is it that the interpreter will just run > > the program as it goes by, without ever generating a .pyc file? So > > what if you have a program that you only update every few weeks... > > then you can ask a .pyc to be generated so that it runs faster every > > time? > > You can, if you want, compile a program manually: > > http://docs.python.org/lib/module-compileall.html > > and run the resulting .pyc file if you wish. Most people don't bother, > though. If you have a very large main program you can encapsulate it as > a library and then call the library function from a teent-weeny main > program that isn't worth compiling. that's great... I just wonder why there is no command line that says python -c try.py or something like that to force a generation of the byte code. From nghai.c at gmail.com Mon Sep 3 22:31:16 2007 From: nghai.c at gmail.com (nghai) Date: Tue, 04 Sep 2007 02:31:16 -0000 Subject: Python is overtaking Perl In-Reply-To: <20070904024908.b8aca60c.sulsa@gazeta.pl> References: <1188865943.238573.218750@w3g2000hsg.googlegroups.com> <20070904024908.b8aca60c.sulsa@gazeta.pl> Message-ID: <1188873076.818614.107580@r34g2000hsd.googlegroups.com> I believe that the time-trend chart show the normalized volumes, relative to the total Google search volume, so a decreasing trend doesn't mean a decreasing absolute volume. The trends of "Los Angeles", "China" searches are decreasing over the last three years, but the absolute volumes should not be (given the popularity of Google and the rise of China). Sulsa wrote: > On Tue, 04 Sep 2007 00:32:23 -0000 > Ben wrote: > > > Here are the statistics from Google Trends: > > > > http://benyang22a.blogspot.com/2007/09/perl-vs-python.html > > > > This chart is showing that amount of python programers is smaller every > year :( From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Sep 12 06:36:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 12 Sep 2007 12:36:04 +0200 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> Message-ID: <46e7c10d$0$12917$426a74cc@news.free.fr> Charles Fox a ?crit : > I've just started playing around with Python, as a possible > replacement for a mix of C++, Matlab and Lisp. The language looks > lovely and clean with one huge exception: I do a lot of numerical > modeling, so I deal with objects (like neurons) described > mathematically in papers, by equations like > a_dot = -k(a-u) > In other languages, this translates nicely into code, but as far as I > can tell, Python needs the ugly: > self.a_dot = -self.k(self.a-self.u) "ugliness" is a very subjective notion. As far as I'm concerned, I hate the "m_myMember" C++ convention, and have always used the 'this' (or whatever it's named) pointer/reference/pseudo-reference/whatever in languages where it's implicit - because I don't like such an important thing to be implicit. self.a_dot = - self.k(self.a - self.u) > For large equations this is going to make my code seriously unreadable Ok, but this is another problem. > to the point of needing to switch back to Matlab -- and it seems to go > against everything else about python's simplicity and elegance. Am I > missing something? Yes. > Is there something like a 'with' command that lets > me set the scope, like > > with self: > .a_dot = -.k(.a-.u) Nope. There's a 'with' statement, but it has nothing to do with this. The obvious solution to your problem is to make local references to the needed attributes at the start of your method, ie: def some_calc(self, whatever): k = self.k # yes, it works for methods too a = self.a u = self.u self.a_dot = -k(a-u) > It's premature to make language suggestions as I am new to the > language, but I would have though that making a 'with self' explicit > in all methods would have been neat, so I could just write > .a_dot = -.k(.a-.u) > which would still avoid confusion with local function variables, since > '.a' is different from 'a'. > > Please help if I am missing something -- this looks like a great > language but I am going to mad trying to read numerical code full of > 'self.'s breaking up the equations. The mandatory 'self' (FWIW, you can name it as you want, 'self' is just a convention) has long been the topic of lot of debates. While I do understand your motivations, there are actually good reasons for this design choice, but understanding these reasons requires some knowledge of Python's object model internals. As far as I'm concerned, I'm quite happy with the current design, but I don't do much maths !-) From skip at pobox.com Mon Sep 10 22:27:18 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 10 Sep 2007 21:27:18 -0500 Subject: [PyCON-Organizers] Next PyCon Organizers' Meeting Tuesday, 11 September In-Reply-To: <46E5CFAB.8090802@python.org> References: <46E5CFAB.8090802@python.org> Message-ID: <18149.64774.138831.976974@montanaro.dyndns.org> David> Connection details: David> http://wiki.python.org/moin/PyCon2008/OrganizersMeetingsConnectionDetails Ah, now I remember. GAIM complained: 400: Malformed Jabber ID GAIM recorded my Jabber ID as "skip.montanaro at jabber.org" which seems pretty well-formed to me. Skip From p.lavarre at ieee.org Fri Sep 7 11:36:09 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: Fri, 07 Sep 2007 08:36:09 -0700 Subject: platform system may be Windows or Microsoft since Vista In-Reply-To: <1188661487.176167.32600@57g2000hsv.googlegroups.com> References: <1188578878.264671.296440@k79g2000hse.googlegroups.com> <1188584386.174981.168040@z24g2000prh.googlegroups.com> <1188661487.176167.32600@57g2000hsv.googlegroups.com> Message-ID: <1189179369.101809.298360@g4g2000hsf.googlegroups.com> > > Log a bug @ bugs.python.org > > http://bugs.python.org/issue1082 > TITLE ... platform system may be Windows or Microsoft since Vista Six days gone with no feedback. Something wrong with the input? Maybe the blank Priority field? I agree Severity Major. I'm thinking no priority because there is no fixing this. We now choose between two wrong ways to change the Python Msi installer of Windows: 1. Hide that many people now and for months or years to come will continue to need both halves of the (platform.system() in ('Windows', 'Microsoft') guard. 2. Leave unchanged to require many more people to need both halves in future. I find neither choice inspiring. From gnewsg at gmail.com Fri Sep 28 17:16:43 2007 From: gnewsg at gmail.com (=?iso-8859-1?q?Giampaolo_Rodol=E0?=) Date: Fri, 28 Sep 2007 14:16:43 -0700 Subject: Python and SSL In-Reply-To: <6cydncA2Jpv082DbnZ2dnUVZ_q6dnZ2d@comcast.com> References: <1190959345.041723.108130@k79g2000hse.googlegroups.com> <6cydncA2Jpv082DbnZ2dnUVZ_q6dnZ2d@comcast.com> Message-ID: <1191014203.366766.257640@d55g2000hsg.googlegroups.com> I heard that python 2.6 will include full "server-side SSL support" (whatever this means). Is it true? From steve at holdenweb.com Wed Sep 12 19:54:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Sep 2007 19:54:11 -0400 Subject: newbie: self.member syntax seems /really/ annoying In-Reply-To: <20070912152001.GA20494@sdf.lonestar.org> References: <1189592518.040116.76370@g4g2000hsf.googlegroups.com> <1189604018.520338.162520@57g2000hsv.googlegroups.com> <46e7f450$0$12305$426a74cc@news.free.fr> <1189608231.151112.147550@y42g2000hsy.googlegroups.com> <20070912152001.GA20494@sdf.lonestar.org> Message-ID: J. Clifford Dyer wrote: > On Wed, Sep 12, 2007 at 07:43:51AM -0700, Charles Fox wrote regarding Re: newbie: self.member syntax seems /really/ annoying: >> Thanks guys -- yeah these two stategies (short s.varname; and explicit >> rescoping, a=self.a etc) are more or less what I was using. That's >> still kind of annoying though. >> >> The s.varname approach still makes numerical code much harder to read. >> > > For what it's worth, if you stick with python for a while, you will stop noticing the self, and be able to see what you're looking for quite clearly. > > Moreso if you use s. > Not sure that's true, since it still appears to bug Bruce Eckel ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From zentraders at gmail.com Mon Sep 24 16:10:44 2007 From: zentraders at gmail.com (Zentrader) Date: Mon, 24 Sep 2007 13:10:44 -0700 Subject: Nested For and While Statements In-Reply-To: References: <1190662087.403000.16290@g4g2000hsf.googlegroups.com> Message-ID: <1190664644.936871.57050@57g2000hsv.googlegroups.com> > Your for loops both use the same counting index. Since those variables are local to the for loop, theoretically it should work with both loops using the same variable. Although bad practice, I tested it on my machine and the following code does indeed work as expected, so it appears that the problem is indenting the for loops properly. for j in range( 10 ): print j, "first loop" for j in range( 5 ): print " ", j, "2nd loop" From stefan.behnel-n05pAM at web.de Tue Sep 25 06:20:18 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 25 Sep 2007 12:20:18 +0200 Subject: Inserting an element into existing xml file In-Reply-To: <1190712485.761290.136570@50g2000hsm.googlegroups.com> References: <1190712485.761290.136570@50g2000hsm.googlegroups.com> Message-ID: <46F8E0E2.3050602@web.de> Anand wrote: > I'm new to Python. we are using python2.4. > > I wanted to insert an element into an existing xml file. Can anyone > help me with this? > I've seen lxml and elementTree in python2.5 has some API's to insert > into existing xml file. > We cant use python 2.5 due to some limitations. So how can we do it in > 2.4? Install lxml and read the tutorial. It should be easy to grasp, as the API is very simple. http://codespeak.net/lxml/tutorial.html http://codespeak.net/lxml/tutorial.html#elements-are-lists It's compatible to ElementTree, which you can also install on Python 2.4 (it's what later became part of Python 2.5). Stefan From hvendelbo.dev at googlemail.com Wed Sep 12 14:40:37 2007 From: hvendelbo.dev at googlemail.com (hvendelbo.dev at googlemail.com) Date: Wed, 12 Sep 2007 18:40:37 -0000 Subject: pwdmodule.c Message-ID: <1189622437.459458.129390@57g2000hsv.googlegroups.com> I am trying to compile Python with cmake, but perhaps there are a few dependencies that have not been corrected for Windows compilation. Is pwdmodule.c supposed to be excluded for windows compilation? Are the makefiles the place to look to deduct which files are meant for which platforms? Henrik From tdelaney at avaya.com Mon Sep 24 07:58:43 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 24 Sep 2007 19:58:43 +0800 Subject: sorting a list numbers stored as strings In-Reply-To: <1190633951.3385.23.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > That interpreter session is a work of fiction, since sorted returns > the sorted list instead of sorting the list in place. Also, it's > better (i.e. more readable and likely faster) to use a sort key > function instead of a comparison function whenever possible. In this > case, the sort key function is particularly trivial: > >>>> l = ["1", "11", "2", "22"] >>>> sorted(l, key=int) > ['1', '2', '11', '22'] It does appear trivial in this case, but need to be careful with using int() if any of the strings could have leading zeros. In this case, the fix is almost as trivial: >>>> l = ["01", "11", "08", "22"] >>>> sorted(l, key=lambda x: int(x, 10)) > ['01', '08', '11', '22'] Although I just tried the above using just sorted(l, key=int) and it succeeded. I'm sure that in some version of Python it would have given a ValueError (due to the default radix being 0) but it appears to have changed to a default radix of 10 somewhere along the way. The docs don't specify what the default radix is (I should probably raise a bug report for this). Tim Delaney From ricaraoz at gmail.com Sat Sep 8 18:30:11 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 08 Sep 2007 19:30:11 -0300 Subject: Spell-checking Python source code In-Reply-To: <18c1e6480709081444x69c4d23cx65f7c9b62eda8271@mail.gmail.com> References: <1189285495.185657.88010@o80g2000hse.googlegroups.com> <46E314FD.7030200@bigfoot.com> <18c1e6480709081444x69c4d23cx65f7c9b62eda8271@mail.gmail.com> Message-ID: <46E32273.2050304@bigfoot.com> David wrote: >>> (I know that the better practice is to isolate user-displayed strings >>> from the code, but in this case that just didn't happen.) >>> >> Use the re module, identify the strings and write them to another file, >> then open the file with your spell checker. Program shouldn't be more >> than 10 lines. >> >> > > Have a look at the tokenize python module for the regular expressions > for extracting strings (for all possible Python string formats). On a > Debian box you can find it here: /usr/lib/python2.4/tokenize.py > > It would probably be simpler to hack a copy of that script so it > writes all the strings in your source to a text file, which you then > spellcheck. > > Another method would be to log all the strings your web app writes, to > a text file, then run through your entire site, and then spellcheck > your logfile. > Nice module : import tokenize def processStrings(type, token, (srow, scol), (erow, ecol), line): if tokenize.tok_name[type] == 'STRING' : print tokenize.tok_name[type], token, \ (srow, scol), (erow, ecol), line file = open("myprogram.py") tokenize.tokenize( file.readline, processStrings ) How would you go about writing the output to a file? I mean, I would like to open the file at main level and pass a handle to the file to processStrings to write to it, finally close output file at main level. Probably a class with a processString method? From hall.jeff at gmail.com Sat Sep 29 13:07:06 2007 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Sat, 29 Sep 2007 17:07:06 -0000 Subject: Program inefficiency? In-Reply-To: <1191079347.192272.240540@22g2000hsm.googlegroups.com> References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> Message-ID: <1191085626.316190.258100@y42g2000hsy.googlegroups.com> For anyone that cares, I figured out the "problem"... the webhelp files that it hits the wall on are the compiled search files... They are the only files in the system that have line lengths that are RIDICULOUS in length... I'm looking at one right now that has 32767 characters all on one line... I'm absolutely certain that that's the problem... Thanks for everyone's help From stefan.behnel-n05pAM at web.de Sun Sep 9 06:10:05 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 09 Sep 2007 12:10:05 +0200 Subject: Python syntax wart In-Reply-To: References: <5khh6nF3i5nuU1@mid.uni-berlin.de> <46E390B7.2080808@web.de> Message-ID: <46E3C67D.1080504@web.de> Lawrence D'Oliveiro wrote: > In message <46E390B7.2080808 at web.de>, Stefan Behnel wrote: > >> He means he has to use backslashes instead of parentheses here. >> >> Which is not true, you could easily rephrase this as: >> >> for link in GetEachRecord( >> "links", >> ....): >> out.write( >> .... >> ) >> >> See? No backslash! > > But then you can no longer use indentation to display the two-dimensional > structure of the statement. Not sure what you mean here, but most people wouldn't write such code anyway. You could easily split it up as def format_record(record): return " References: <7x641vh7yx.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: >> So what we need is a poll on what the questions should be. I *love* c.l.py. > > One of the offered answers to the current question should be "never". > That is, I'm hoping to skip 3.0 and switch directly to PyPy. Well, "No current plans" certainly includes "never", even though it might not be quite assertive enough for your tastes. I hope that PyPy will eventually become good enough to overtake CPython as the preferred implementation - it certainly seems to have much greater optimization possibilities than CPython. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From eduardo.padoan at gmail.com Sat Sep 15 13:11:37 2007 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Sat, 15 Sep 2007 14:11:37 -0300 Subject: how to join array of integers? In-Reply-To: <2EE95E6A-D6D0-4742-844E-4F18265DC469@myemma.com> References: <1189859762.563599.269270@g4g2000hsf.googlegroups.com> <13eo0pbiab4spdf@corp.supernews.com> <2EE95E6A-D6D0-4742-844E-4F18265DC469@myemma.com> Message-ID: > > It's nice people have invented so many ways to spell the > > builting "map" ;) > > > >>>> ",".join(map(str,[1,2,3])) > > '1,2,3' > > IIRC, map's status as a builtin is going away. Actually, py3k built-in map == itertools.imap >>> map(str, []) -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt From jeff at jmcneil.net Tue Sep 11 08:28:32 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Tue, 11 Sep 2007 08:28:32 -0400 Subject: IOError - list of all Errno numbers and their meanings? In-Reply-To: <46E68539.1020404@scivisum.co.uk> References: <46E68539.1020404@scivisum.co.uk> Message-ID: <82d28c40709110528g488b9b79yc3733c574de4f0ef@mail.gmail.com> The 'errno' number (at least on the *nix platforms I use) corresponds to the 'errno' number set on system call failure. POSIX.1 specifies a set of standard errors. AFAIK, the 'errno' module should contain the mappings for your system. On 9/11/07, Tim Couper wrote: > As you know, when an IOError is raised, you get a helpful: > > [Errno N] > > Is there a list of all possible values of N which can be returned, and > their meanings? > > -- > Dr Tim Couper > CTO, SciVisum Ltd > > www.scivisum.com > > -- > http://mail.python.org/mailman/listinfo/python-list > From mcknight0219 at gmail.com Sun Sep 16 12:41:08 2007 From: mcknight0219 at gmail.com (Jimmy) Date: Sun, 16 Sep 2007 09:41:08 -0700 Subject: (curses) issue about inch() In-Reply-To: References: <1189955232.216664.167840@19g2000hsx.googlegroups.com> Message-ID: <1189960868.349377.249530@k79g2000hse.googlegroups.com> On Sep 17, 12:07 am, Steve Holden wrote: > Jimmy wrote: > > hi, all > > I attempt to use the function inch() to get the character at the > > current position, and compare it with a particular character like : > > if screen.inch(x,y) == 'F' > > but this method doesn't seem work, can anyone tell me the reason and > > how to corrent it > > thanks > > The reason is because something is wrong, and yo fix it by correcting > that issue. > > In other words, if you could be a bit more specific about *how* it > doesn't work (like, show us the code you are running,a nd any error > messages or evidence of incorrect results) you will be able to get some > help that actually helps you. > > Would you go to a car repair shop with faulty brakes and just tell them > "my car isn't working"? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > > Sorry, the dog ate my .sigline thanks, actually i'm writing a game like mine,the pertainign code is: def mark(): """mark the bomb""" (row, col) = gb.scrn.getyx() x = gb.scrn.inch(row,col) if x == 'F': gb.scrn.addch(row,col, 'X',curses.color_pair(3)) else: gb.scrn.addch(row,col, 'F',curses.color_pair(3)) gb.scrn.move(row,col) gb.scrn.refresh() the situation is x never equals 'F', even when it really is! I checked the mannual and found the return value of inch() consists the actual character(low 8bits) and the attributes, so I tried the following: (x<<24)>>24,cause I guess the int is 32bits long. but it still doesn't work :( From ilikecandy7 at gmail.com Tue Sep 4 10:56:29 2007 From: ilikecandy7 at gmail.com (frenchy64) Date: Tue, 04 Sep 2007 14:56:29 -0000 Subject: Parse or Pass? In-Reply-To: References: <1188917032.271543.236420@d55g2000hsg.googlegroups.com> Message-ID: <1188917789.483017.62070@r34g2000hsd.googlegroups.com> > In general, "parsing" is analyzing the grammatical structure of a > string. People sometimes talk loosely about "parsing the command line". > but I don't think that's normally applied to providing the actual > arguments (corresponding to the definition's "formal parameters") when a > function is called - that's argument passing. > > regards > Steve Thanks Steve, great post! From david at asdf.asdf Sun Sep 9 21:21:58 2007 From: david at asdf.asdf (bambam) Date: Mon, 10 Sep 2007 11:21:58 +1000 Subject: concise code (beginner) References: <13dsvqrqivtf092@corp.supernews.com> <1189020188.842700.50950@d55g2000hsg.googlegroups.com> <1189108607.080926.103650@19g2000hsx.googlegroups.com> <1189183560.572177.56930@r34g2000hsd.googlegroups.com> Message-ID: <13e971s8qujjm3a@corp.supernews.com> > Removing from a list while you iterate will had quadratic performance Anecdote: I was doing a route-finding program for a railway ticketing system. My replacement explained to my boss that it couldn't be done: the problem was one of that class of problems that has no good optimum solution. My replacement told me this while we were doing the hand-over. I told him that the route-finding optimiser was already complete. It did a search of possible routes over the 3 loops, 15 branches and 75 stations in less time than it took to redraw the screen, and that was without even bothering to recode the tail recursion. In my present case, the lists I am working with have ~10 elements. Defined behaviour, even if it was inapropriate for my needs, would be welcome. Language enhancement that make the code clearer and easier would be welcome. Optimisers for large sets I could continue to do by other means. Raw cPython is probably not a good choice for real-time signal processing, but that's not what I am doing. > O(n) to find the element you wish to remove and move over > everything after it, Is that how lists are stored in cPython? It seems unlikely? Steve. "Rhamphoryncus" wrote in message news:1189183560.572177.56930 at r34g2000hsd.googlegroups.com... > On Sep 6, 1:56 pm, Karthik Gurusamy wrote: >> That said, it may be a good future language enhancement to define a >> reasonable consistent behavior for an iterator over a changing >> collection. This occurs quite common when we walk a collection and >> usually delete the current item. >> From martin at v.loewis.de Mon Sep 10 17:34:05 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 10 Sep 2007 23:34:05 +0200 Subject: Why zlib not included in Python tarball? In-Reply-To: References: Message-ID: <46E5B84D.5020803@v.loewis.de> > I need to install my own Python. I compiled Python 2.4.4 from sources. zlib > did not compile - it's not in the lib-dynload directory. > > I did not have this problem with any of my earlier Python compiles. I > routinely compile Python from source. > > What is the correct procedure for installing zlib from source into Python? Depends on the operating system and the Python version. On Unix, you need to install zlib first; if you install a precompiled zlib package, make sure you install the header files as well. Regards, Martin From http Fri Sep 7 22:22:43 2007 From: http (Paul Rubin) Date: 07 Sep 2007 19:22:43 -0700 Subject: Generating a unique identifier References: <13e2fgbbpsatm39@corp.supernews.com> <7x3axq7a8a.fsf@ruckus.brouhaha.com> <13e3us269f59s7a@corp.supernews.com> <7xd4wt99yv.fsf@ruckus.brouhaha.com> Message-ID: <7xtzq57v64.fsf@ruckus.brouhaha.com> Paul Rubin writes: > the probability is about exp(-(2**60 / 2*2**160)) = 1/exp(2**101) Bah. Got that backwards and calculated wrong. The probability of no collisions is exp(-(2**60) / (2*2**160)) = exp(-(2**-101)) = approx (1 - 2**-101) which is very close to 1. The probability of collision is about 2**-101 which is close to 0. Proofread first, then post. I keep getting that in the wrong order. From kay.schluehr at gmx.net Sun Sep 23 21:32:28 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 23 Sep 2007 18:32:28 -0700 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <46f6e9b0$0$32168$426a74cc@news.free.fr> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190413322.962737.53900@r29g2000hsg.googlegroups.com> <1190414192.636397.146450@57g2000hsv.googlegroups.com> <1190443748.907702.154660@22g2000hsm.googlegroups.com> <7xlkazgpc5.fsf@ruckus.brouhaha.com> <1190447257.060479.141280@n39g2000hsh.googlegroups.com> <5lk2olF8gic1U5@mid.uni-berlin.de> <1190454275.282176.90830@k79g2000hse.googlegroups.com> <46f6e9b0$0$32168$426a74cc@news.free.fr> Message-ID: <1190597548.214612.181140@22g2000hsm.googlegroups.com> On 22 Sep., 02:14, Bruno Desthuilliers wrote: > Kay Schluehr a ?crit : > (snip) > > > > > I checked out Io once and I disliked it. I expected Io's prototype OO > > being just a more flexible variant of class based OO but Io couples a > > prototype very closely to its offspring. When A produces B and A.f is > > modified after production of B also B.f is modified. A controls the > > state of B during the whole lifetime of B. I think parents shall not > > do this, not in real life and also not in programming language > > semantics. > > I may totally miss the point, but how is this different from: > > class A(object): > def dothis(self): > print "A.dothis(%s)" % self > > class B(A): > pass > > b = B() > > b.dothis() > > def dothat(self): > print "function dothat(%s)" % self > > A.dothis = dothat > b.dothis() It's not a big deal because you do not use a class to propagate mutable state unless you are using a class attribute intentionally ( i guess you do not overuse it just to avoid object encapsulation and make everything global ). When using a prototype as in Io you need to protect the state of the child object yourself. You can do this by overwriting the objects slots but then you end up writing your own object constructors and the templates accordingly, also named "classes" by some. Not having dedicated object constructors, member variable initializations and the presumed class definition boilerplate comes at the price of introducing them on your own. Prototypes have a purpose of course when you want to transfer state to a newly created object. Using a prototyping mechanism as a generic form of a copy constructor is the right kind to thinking about them IMO. ------------ I have got the impression that the discussion has drifted away from what Paul Rubin suggested, namely abandone the expression/statement distinction. Instead we are discussing the advantages and disadvantages of object models now. Can we stop here, please? From pavlovevidence at gmail.com Sun Sep 9 04:16:58 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 9 Sep 2007 04:16:58 -0400 Subject: Python syntax wart References: Message-ID: <46e3ac02$2$28851$4c368faf@roadrunner.com> On Sun, 09 Sep 2007 17:16:05 +1200, Lawrence D'Oliveiro wrote: > The one thing I don't like about Python syntax is using backslashes to > continue lines. Yes, you can avoid them if you can include parentheses > somehow, but this isn't always possible. > > Possible: > > if ( > quitting > and > len(client["to_write"]) == 0 > and > len(client["read"]) + client["to_read"] == 0 > ) : > close_client(client, "shutting down") > #end if > > Not possible: > > for \ > Link \ > in \ > GetEachRecord \ > ( > "links", > ("from_episode",), > "to_episode = %s", > [EpisodeID], > "order by when_created" > ) \ > : Hmm. Complaints about the backslash come up from time to time, but this is the first time I can recall anyone complaining because you couldn't break a line right after the "for" keyword. I'm sure you'll find agreement that backslash continuations are ugly, but probably hardly anyone feels compelled to use them the way you demonstrate above. [snippage] > #end for No offense, but using things like "#end for" isn't really the best way to impress (most of) the Python community with your eye for syntax. You're relatively new to Python, correct? If so, maybe you should give yourself some time to see if some of Python's unconventional features grow on you. I've found that wherever Python differs from the common ways to do things, it's usually different in a good way. You should give Python a chance to be Python, without trying to force it to be like languages that do things like break for statements into several lines, or use block delimiters. Carl Banks From carsten at uniqsys.com Thu Sep 6 14:14:10 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 06 Sep 2007 14:14:10 -0400 Subject: Beginners Query - Simple counter problem In-Reply-To: <13e0g0id9rlmg71@corp.supernews.com> References: <13e0g0id9rlmg71@corp.supernews.com> Message-ID: <1189102450.3376.17.camel@dot.uniqsys.com> On Thu, 2007-09-06 at 11:00 -0700, Scott David Daniels wrote: > def d6(count): > result = 0 > for die in range(count): > result += random.randint(1, 6) > return result This, of course, can be further improved into: def d6(count): return sum(random.randint(1, 6) for die in range(count)) -- Carsten Haese http://informixdb.sourceforge.net From hassen62 at voila.fr Fri Sep 14 17:56:34 2007 From: hassen62 at voila.fr (hassen62 at voila.fr) Date: Fri, 14 Sep 2007 23:56:34 +0200 (CEST) Subject: reading xls file from python Message-ID: <21903009.66741189806994236.JavaMail.www@wwinf4602> hi friends, I have installed python 2.5 for windows in my pc, I have a file xls say "file.xls" in c:/python25. How I can read this files from Python. Many thanks in advance. Hassen. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steveo at syslang.net Fri Sep 14 16:52:14 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 14 Sep 2007 16:52:14 -0400 (EDT) Subject: 2 daemons write to a single file /w python file IO In-Reply-To: References: Message-ID: On Tuesday, Sep 11th 2007 at 21:17 -0700, quoth Andrey: =>i have a newbie question about the file() function. =>I have 2 daemons running on my linux box. => =>1 will record the IDs to a file - logs.txt =>other 1 will open this file, read the IDs, and then "Clean up the =>file" -logs.txt => =>Since these 2 daemons will run every 2-5mins, I think this will crash, isn't =>it? When both daemons try to write to the file at the same time. => =>I am wondering if this won't crash, OR if there is some simple high-level =>functions can lock the file while writing... =>I also wonder if one side locked the file, what happens if the other side =>try to open this locked file? raise error? so i also need to write a loop to =>wait for the file to release locking? => =>seems a basic easy thing but i just cannot find an simple answer. =>I always advoid this issue by putting them in mysql (well, fast and hassle =>free for locking) This is more of a unix question as opposed to a python question, but I'll 'splain it anyways :-) If two processes each have a channel opened to the same file then it is very possible for the writes to collide. One way to mitigate the damage would be to make sure that the two processes open the file for append access instead of simple write access. This will ensure that the if ProcessA writes data that ProcessB's next write won't overwrite the data that A just wrote. But! It still won't work! You will still get interleaving of data in your output file. They will all get out there, but the data will on occasion look garbled because the interleaving won't look like it was partitioned as the different processes intended. So what's the solution? It turns out that data that is written to a pipe (as opposed to data that is written to a file) is guaranteed to maintain its partitioned integrity. P1 >> fn P2 >> fn If you are the guy who starts P1 and P2 from a parent process(PP) then you could structure your pipes so you end up with PP > fn / \ / \ P1 P2 and just make PP be a multiplexor. :-) -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From saptarshi.guha at gmail.com Sat Sep 22 10:23:56 2007 From: saptarshi.guha at gmail.com (sapsi) Date: Sat, 22 Sep 2007 07:23:56 -0700 Subject: Sets in Python In-Reply-To: References: <1190162387.396681.250190@n39g2000hsh.googlegroups.com> <1190235483.412972.81280@v23g2000prn.googlegroups.com> <13f3m15igkstq2e@corp.supernews.com> <1190260923.243865.312190@z24g2000prh.googlegroups.com> <13f4nclh902f78f@corp.supernews.com> Message-ID: <1190471036.715212.62540@o80g2000hse.googlegroups.com> Thank you everyone for the assistance and for the very informative discussion Regards SM From christopher.pax at gmail.com Fri Sep 28 21:57:50 2007 From: christopher.pax at gmail.com (Chris Pax) Date: Sat, 29 Sep 2007 01:57:50 -0000 Subject: using inspect on pygtk Message-ID: <1191031070.901842.71210@o80g2000hse.googlegroups.com> Hello, I recently been trying to use the inspect module to inspect the arguments of gtk objects, such as gtk.Button. I tried like this: inspect.getargspec(gtk.Button.__init__) and get the fallowing error: File "", line 1, in File "/usr/lib/python2.5/inspect.py", line 743, in getargspec raise TypeError('arg is not a Python function') TypeError: arg is not a Python function I have been trying to do this through code so that I don't have to have a list of all possible gtk classes and their arguments. From ratchetgrid at googlemail.com Sun Sep 16 19:02:30 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Mon, 17 Sep 2007 00:02:30 +0100 Subject: Free Python Ebook In-Reply-To: <46ED0993.5090604@yafd.de> References: <1189932765.100822.82720@r29g2000hsg.googlegroups.com> <46ED0993.5090604@yafd.de> Message-ID: <676224240709161602u4158e146n772b99bb1893a77@mail.gmail.com> Theres a few python ebooks listed on the wiki................ http://wiki.python.org/moin/PythonBooks Hope this helps, Nathan On 16/09/2007, Marco wrote: > Hi George, > > > Please tell me from which website I will get the free Python Ebook. > which one do you mean? > > I only know this one: > http://diveintopython.org > > Bye, > Marco > > PS: Sorry, hit the wrong button the first time ;-) > -- > http://mail.python.org/mailman/listinfo/python-list > From timaranz at gmail.com Sun Sep 30 16:10:40 2007 From: timaranz at gmail.com (timaranz at gmail.com) Date: Sun, 30 Sep 2007 13:10:40 -0700 Subject: GUI for viewing/editing python data structures? In-Reply-To: References: Message-ID: <1191183040.750816.253910@22g2000hsm.googlegroups.com> On Sep 27, 11:23 am, "Joshua J. Kugler" wrote: > A while back, I seem to remember coming across a small program that could > view and edit python data structures via a nice expanding tree view. I'm > now in need of something like that (to verify data is imported correctly > into a shelve file) and having a GUI would be much simpler than trying to > wade through the output of str(d) or repr(d). > > I've tried googling with the obvious keywords (gui (view OR edit) python > data structures) but t didn't get me anywhere. > > Pointers? > > j > > -- > Joshua Kugler > Lead System Admin -- Senior Programmerhttp://www.eeinternet.com > PGP Key:http://pgp.mit.edu/ ID 0xDB26D7CE Try any of the good Python IDE's and use breakpoints and the watch window. I like wing IDE from wingware.com - they have a free version now. From fredrik at pythonware.com Wed Sep 26 04:47:10 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 10:47:10 +0200 Subject: the address of list.append and list.append.__doc__ In-Reply-To: <1190788149.477809.80130@g4g2000hsf.googlegroups.com> References: <1190775258.351819.24930@22g2000hsm.googlegroups.com> <1190780557.879816.13800@d55g2000hsg.googlegroups.com> <1190788149.477809.80130@g4g2000hsf.googlegroups.com> Message-ID: HYRY wrote: > This works, but I think the key of DOC is too long, so I want to use > the id of list.append.__doc__ as the key; or use the id of > list.append: > > DOC[id(list.append.__doc__)] = "..." > DOC[id(list.append)] = "..." > > So, I asked how to get list.append from a.append, and why > id(list.append.__doc__) changes. dictionaries hold *references* to objects, not copies of the object values, so that won't save you anything. From answer654 at 8439.e4ward.com Sat Sep 15 15:59:05 2007 From: answer654 at 8439.e4ward.com (Michael Goerz) Date: Sat, 15 Sep 2007 15:59:05 -0400 Subject: calling locale.setlocale repeatedly Message-ID: <5l2rs3F64tgmU1@mid.uni-berlin.de> Hi, From http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html#guessing-the-encoding: > The way to access the information about the "normal" encoding used on the current computer is through the locale module. Before using locale to retrieve the information you want, you need to call locale.setlocale(locale.LC_ALL, ''). Because of the sensitivity of the underlying C locale module on some platforms, this should only be done once. Why should the call locale.setlocale(locale.LC_ALL, '') only be made once? What exactly is the "sensitivity of the underlying C locale module"? Thanks, Michael From raims at dot.com Sun Sep 23 10:02:11 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 23 Sep 2007 16:02:11 +0200 Subject: newb: Question regarding custom exception References: <1190550748.698865.210740@22g2000hsm.googlegroups.com> Message-ID: <1i4whsf.1x6h74h163pw0aN%raims@dot.com> crybaby wrote: > Why you specify type and name of the exception in your custom > exceptions, It's up to you, if you're interested in the actual exception object you catch it, otherwise not. Take a look at this: -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From wolf_tracks at invalid.com Thu Sep 20 12:29:52 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 20 Sep 2007 16:29:52 GMT Subject: Tutorial or Example (or Tutorial) of Using Canvas to Producea Plot In-Reply-To: References: <13evohih7rkd030@corp.supernews.com><13f0b2qlvj5ige6@corp.supernews.com><9ai0f39lejmjc2qbfcgo1t4h8b3e6ot9jd@4ax.com><1190185249.235840.263260@50g2000hsm.googlegroups.com> Message-ID: <4exIi.685$6p6.482@newssvr25.news.prodigy.net> That's odd; however, it's likely close enough. Hendrik van Rooyen wrote: > "W. Watson" wrote: > > >> I'm just trying to get some feel for how canvas works. I'm about to modify a >> program I use for meteor work. It uses canvas to display images, and I plan >> to draw on the image. For example, I plan to draw compass headings on a >> circle every 30 degrees. Just warming up to the task. > > Don't be surprised if you can't draw a full circle - I have never managed it, > but 359.99 degrees works fine > > - Hendrik > -- Wayne Watson (Nevada City, CA) Web Page: From ptmcg at austin.rr.com Fri Sep 14 01:34:33 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 13 Sep 2007 22:34:33 -0700 Subject: How to Start In-Reply-To: References: Message-ID: <1189748073.196112.254870@w3g2000hsg.googlegroups.com> On Sep 13, 4:59 pm, mrc2... at cox.net (Michael R. Copeland) wrote: > Yes, I could fire up the interactive mode and play with some > statements...but I consider that sort of thing for programming > neophytes or experimenting with specific issues. To misquote Francis Bacon, "you would have fish, but dare not get your fingernails dirty." Back in '62-minus, when you started programming, there was no such thing as "just dive in and try stuff." Imagine if someone had said, "Just punch some random holes in this computer card and feed it in - you'll get the hang of it," you would have thought they were crazy. So you probably read a whole bunch of books first, before you punched your very first card, and then stood in line to feed your deck to the card reader on "the mainframe," then waited anywhere from 15 minutes to an hour or more to get your job output. The length of this cycle was itself a deterrent to interactive experimentation - you had to *know* what you were doing and do it right, or risk wasting an hour because you accidentally punched a character in column 6 instead of column 7. In fact, much of the software development process from that era was oriented around avoiding as many needless compile/run cycles as possible. Well, in 45+ years, things have progressed a bit. Nowadays, I don't pore over my code looking for that stray or missing brace or closing paren - the compiler will tell me in about 3 seconds where these syntax errors are. And so too with Python. Do "neophytes" just dive in and try stuff? What of it? You have chosen a nice simple little problem space, well within the fairway of the vanilla, batteries-included Python. In your noobiness you might write some code that duplicates the features of a standard built-in module, but so what? Isn't your goal to learn the language as well as the libraries? And you would not be the first (nor the last) to post a question to this group along the lines of "can you look at this code and see what I'm doing wrong?" and get back the answer of "what you're doing wrong is writing your own code instead of just using standard module X" - it happens to many newcomers and nearly all survive this early trauma. Just because I can convert a list of data into a histogram in a single line of code if I use itertools.groupby, doesn't invalidate my learning how to do it in 4 lines with a defaultdict, or 6 lines with an explicit for loop. In your shoes, I would pursue a minimalist approach, learning the basic language features, and then browsing through the standard lib docs to get familiar with the available modules. Get a no-frills IDE with a short learning curve - I like SciTE for this, although there is no auto-completion - to help automate your code/run cycle (note: just code/run, no compile step!). I also suggest you go to the Python.org wiki and look for the documentation for experienced programmers who are starting to switch over to Python (http://wiki.python.org/moin/ BeginnersGuide/Programmers) - others have trod this path before, and some have left bread crumbs behind. Best of luck! -- Paul From brown at esteem.com Thu Sep 6 19:26:57 2007 From: brown at esteem.com (Tom Brown) Date: Thu, 6 Sep 2007 16:26:57 -0700 Subject: Subclassing zipfile (new style class) In-Reply-To: References: Message-ID: <200709061626.57801.brown@esteem.com> On Thursday 06 September 2007 16:15, Larry Bates wrote: > I'm trying to learn about subclassing new style classes and the first > project I went to do needs to subclass zipfile to add some methods. > > > Why does this: > > import zipfile > class walkZip(zipfile): > pass > > > if __name__ == "__main__": > print "Hello World" > > Traceback (most recent call last): > File "", line 192, in run_nodebug > File "", line 2, in > TypeError: Error when calling the metaclass bases > module.__init__() takes at most 2 arguments (3 given) > I think because you need to do this: from zipfile import ZipFile class walkZip(ZipFile): pass -Tom From python at hope.cz Sat Sep 15 09:44:36 2007 From: python at hope.cz (Johny) Date: Sat, 15 Sep 2007 06:44:36 -0700 Subject: How to get headers in urllib2 response Message-ID: <1189863876.901048.114410@o80g2000hse.googlegroups.com> Can anyone provide an example how to find out the return code and header from an urllib2 request? For example response = urllib2.urlopen('http://www.google.com').read().strip() provides data but I do not know if the return code was 200 or different. Thanks From sandipan at earthlink.net Tue Sep 4 08:12:22 2007 From: sandipan at earthlink.net (Sandipan Gangopadhyay) Date: Tue, 4 Sep 2007 08:12:22 -0400 Subject: Setting Current Dir in Python Message-ID: <000001c7eeec$d9341470$8b9c3d50$@net> Hi all! I have utility programs in Python that do clean up, image processing tasks on files in a folder. I just drop the program into the folder and run it. I have been double clicking on a Python program in my Windows XP Home to make it run . it sets the program's directory as the current directory when it runs. I have recently installed Python 2.5.1 and Pythonwin (without any errors) on Windows Vista Ultimate. Now, the programs run fine within Pythonwin IDE when current directory is set to the program's directory. But, when I double click them from Windows Explorer, the program is not run. If I run the following program: ============================================================================ =============== # MODULE IMPORT try: import time, os, Image, urllib, string, math, os.path, filecmp, shutil, sys except: strInput = raw_input("Failed import. Hit enter key to continue.") pass # FIGURE OUT CURR DIR try: print "CURENT = %s" % os.listdir(".") print "PARENT = %s" % os.listdir("..") print "ABS PATH = %s" % os.path.abspath(".") print "CURENT = %s" % os.listdir(os.curdir) print "PARENT = %s" % os.listdir(os.pardir) except: strInput = raw_input("Failed os module calls. Hit enter key to end.") pass print strInput = raw_input("Hit enter key to end program") Through Pythonwin IDE without setting the directory (using Open, or Save As), I get: ============================================================================ =============== CURENT = ['addins', 'AppPatch', 'assembly', 'atl80.dll', . - snip - . , 'winsxs', 'WMSysPr9.prx', 'xpsp1hfm.log', '_default.pif'] PARENT = ['$Recycle.Bin', 'autoexec.bat', 'Boot', 'bootmgr', 'BOOTSECT.BAK', 'config.sys', 'Documents and Settings', . - snip - . , 'Program Files', 'ProgramData', 'Python25', . - snip - . , 'System Volume Information', 'temp', 'Users', 'Windows'] ABS PATH = C:\Windows CURENT = ['addins', 'AppPatch', 'assembly', 'atl80.dll', . - snip - ., , 'winsxs', 'WMSysPr9.prx', 'xpsp1hfm.log', '_default.pif'] PARENT = ['$Recycle.Bin', 'autoexec.bat', 'Boot', 'bootmgr', 'BOOTSECT.BAK', 'config.sys', 'Documents and Settings', . - snip - . , 'Program Files', 'ProgramData', 'Python25', . - snip - . , 'System Volume Information', 'temp', 'Users', 'Windows'] If I run it using double click on the program through Windows Explorer, I get: ============================================================================ =============== Nothing . the window closes immediately. Despite the except catches. If I run it from a Command Prompt, by first navigating to the program's directory and then specifying [ python.exe SandhirFileMonitor.py ], I get: ============================================================================ =============== sys:1: DeprecationWarning: Non-ASCII character '\xef' in file SandhirFileMonitor.py on line 356, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details Failed import. Hit enter key to continue. CURENT = ['Diff.txt', 'Folder2', 'report-templates', 'reports - Copy (2).html','reports - Copy (3).html', 'reports - Copy (4).html', 'reports - Copy (5).html', 'reports - Copy.html', 'reports.html', 'SandhirFileBackupUtility - Copy.py', 'SandhirFileBackupUtility.py', SandhirFileBackupUtility.py - Shortcut.lnk', 'SandhirFileMonitor.py'] PARENT = ['BackupV10', 'BackupV11', 'DayReadiness', 'reporterV70'] ABS PATH = E:\Data\ActiveData\SandipanPersonalData\FromNODE06\SoftwareBackups\BackupV11 CURENT = ['Diff.txt', 'Folder2', 'report-templates', 'reports - Copy (2).html', 'reports - Copy (3).html', 'reports - Copy (4).html', 'reports - Copy (5).html', 'reports - Copy.html', 'reports.html', 'SandhirFileBackupUtility - Copy.py', 'SandhirFileBackupUtility.py', 'SandhirFileBackupUtility.py - Shortcut.lnk', 'SandhirFileMonitor.py'] PARENT = ['BackupV10', 'BackupV11', 'DayReadiness', 'reporterV70'] I am obviously missing something very simple, but I can't figure this out . it's been a few days now. Can someone help? Thanks. Sandipan From theller at ctypes.org Fri Sep 7 10:22:29 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 07 Sep 2007 16:22:29 +0200 Subject: py2exe - change name of exe created In-Reply-To: <1189165183.727542.47640@19g2000hsx.googlegroups.com> References: <1189164934.705547.156670@r34g2000hsd.googlegroups.com> <1189165183.727542.47640@19g2000hsx.googlegroups.com> Message-ID: imageguy schrieb: > Sorry for the double post, sent it to quickly. > > I have a setup script like this; > > setup(windows = [{"script":"myprogram.py", > "icon_resources":[(0,"nabbitt.ico")], > "other_resources": [(24,1,manifest)]} > ], > name = "My Program ver 0.1", > data_files = [("",rootdata)], > zipfile = None, > options = {"py2exe": { > "compressed" : 1, > "dll_excludes": > ["w9xpopen.exe"], > "bundle_files": 3 > } > }, > ) > > > Note that every thing works fine with this and creates an exe program > called > "myprogram.exe" > > I would like to setup program to create an output called; > "MyBestProgram.exe" > > IS that at all possible ? Yes. Use a 'dest_base' key in the dictionary, like so: > setup(windows = [{"script":"myprogram.py", > "icon_resources":[(0,"nabbitt.ico")], "dest_base": "MyBestProgram", > "other_resources": [(24,1,manifest)]} ... 'dest_base' is the basename of the destination program that py2exe creates. Thomas From mccredie at gmail.com Fri Sep 21 18:02:44 2007 From: mccredie at gmail.com (Matt McCredie) Date: Fri, 21 Sep 2007 15:02:44 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190394011.148384.106280@q3g2000prf.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> <1190394011.148384.106280@q3g2000prf.googlegroups.com> Message-ID: <9e95df10709211502h5d7ba4apb6f8f54e04711a3e@mail.gmail.com> > Now I think I will code this little scrambler using nothing but the D > Language just to see whether there is any benefit in using D over > Python for this sort of problem. Isn't D compiled to machine code? I would expect it to win hands down. That is, unless it is horribly unoptimized. Matt From s.mientki at id.umcn.nl Tue Sep 25 06:46:20 2007 From: s.mientki at id.umcn.nl (stef) Date: Tue, 25 Sep 2007 12:46:20 +0200 Subject: ANN: PyPE 2.8.7 In-Reply-To: References: Message-ID: Another problem, I tried to run PyPE in my "old IDE", and get the following error: Traceback (most recent call last): File "D:\temp\PyPE-2.8.7-src\PyPE-2.8.7\pype.py", line 20, in ? wxversion.ensureMinimal(v) File "P:\Python\lib\site-packages\wxversion.py", line 178, in ensureMinimal raise VersionError("wxversion.ensureMinimal() must be called before wxPython is imported") VersionError: wxversion.ensureMinimal() must be called before wxPython is imported > cheers, > Stef Mientki From bjourne at gmail.com Mon Sep 17 05:16:06 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 17 Sep 2007 11:16:06 +0200 Subject: SVG to raster conversion. In-Reply-To: <46ED5283.3030004@sdf.lonestar.org> References: <46ED5283.3030004@sdf.lonestar.org> Message-ID: <740c3aec0709170216w6642d414g5e3f9052924a1c38@mail.gmail.com> On 9/16/07, J. Cliff Dyer wrote: > Does anybody know a good solution (preferably in python) for rasterizing > SVG or other vector graphics. > > I'm thinking something like > > vector_image = SVGFile(path_to_image) > raster_image = vector_image.rasterize(format, (width, height), dpi) > raster_image.write(out_file) > > Thanks for any pointers you might have. Use rsvg: import rsvg h = rsvg.Handle('svg-file.svg') pixbuf = h.get_pixbuf() pixbuf.save('foobar.png', 'png') -- mvh Bj?rn From Scott.Daniels at Acm.Org Tue Sep 11 08:58:27 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 11 Sep 2007 05:58:27 -0700 Subject: Enum class with ToString functionality In-Reply-To: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> Message-ID: <13ed45rfqtgqvf0@corp.supernews.com> bg_ie at yahoo.com wrote: > Hi, > > I have the following class - > > class TestOutcomes: > PASSED = 0 > FAILED = 1 > ABORTED = 2 > > plus the following code - > > testResult = TestOutcomes.PASSED > > testResultAsString > if testResult == TestOutcomes.PASSED: > testResultAsString = "Passed" > elif testResult == TestOutcomes.FAILED : > testResultAsString = "Failed" > else: > testResultAsString = "Aborted" > > But it would be much nicer if I had a function to covert to string as > part of the TestOutcomes class. How would I implement this? > > Thanks, > > Barry > class Outcome(object): PASSED, FAILED, ABORTED = range(3) @classmethod def named(class_, value): for name in dir(class_): if name[0] != '_' and getattr(class_, name) == value: return name raise ValueError('Unknown value %r' % value) Outcome.named(2) -Scott David Daniels Scott.Daniels at Acm.Org From gagsl-py2 at yahoo.com.ar Fri Sep 7 06:16:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Sep 2007 07:16:46 -0300 Subject: How to convert None to null value References: Message-ID: En Fri, 07 Sep 2007 06:19:25 -0300, pradeep kumar escribi?: > i am trying to insert records from one table to another table in postgres > sql using the the following code > > posConn.query("insert into > usr(usr_id,usr_name,usr_passwd,grp_cde,usr_type,usr_chk_till_val, \ > > usr_active,usr_daily_auth,usr_lst_login,usr_lst_logout,usr_shift_id,usr_role_level) > values \ > ('%s','%s','%s',%s,%i,%d,'%s',%i,%i,%i,%i,%i)" > %(row[0],row[1],row[2],row[3],row[4],row[5], \ > row[7],row[8],row[10],row[11],row[12],row[14]) ) > > here row[4] column is having null value so python consides it as None but > will insert into the table it inserts as None not null value - You are building the sql statement "by hand": don't do that. The query method receives two arguments: an sql template with placeholders, and a tuple of arguments. This way, None objects are correctly translated into NULL values, embedded quotes are correctly handled, etc. An important point is security - building the sql statement by hand may open the door to sql injection attacks. See for details. - You don't need those \ for line continuation: any expression containing an open ( [ { automatically continues on the following lines until all ) ] } are closed. - Python automatically joins contiguous strings. Combining all the above: posConn.query("insert into usr " "(usr_id,usr_name,usr_passwd,grp_cde,usr_type," "usr_chk_till_val,usr_active,usr_daily_auth," "usr_lst_login,usr_lst_logout,usr_shift_id," "usr_role_level) values " "(%s,%s,%s,%s,%i,%d,%s,%i,%i,%i,%i,%i)" , (row[0],row[1],row[2],row[3],row[4],row[5], row[7],row[8],row[10],row[11],row[12],row[14])) Note the TWO arguments to the query method: all those string fragments are joined into a single string, followed by a comma, and a tuple containing 6 parameters. Parameter markers may be %s,%s,%s... as above, or :1,:2,:3... or ?,?,?... The exact syntax depends on your specific database adapter - you'll have to read its documentation. -- Gabriel Genellina From georgerxz at gmail.com Sun Sep 16 04:46:34 2007 From: georgerxz at gmail.com (GeorgeRXZ) Date: Sun, 16 Sep 2007 01:46:34 -0700 Subject: Try this Message-ID: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> If you have Microsoft windows 98/2000/ME/XP/2003 Operating System on your PC. Then Open the Notepad and type the following sentence, and save the file and close the notepad. Now reopen the file and you will find out that, Notepad is not able to save the following text line. Well you are speed This occurs not only with above sentence but any sentence that has 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) When type following sentence and save file then same thing occurs. This is not Maria GEOrgE << Develop a website that will help people, Avoid spamming, provide quality contents on your website >> http://zsoftwares.googlepages.com/index.htm From sjmachin at lexicon.net Sun Sep 16 16:14:13 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 16 Sep 2007 13:14:13 -0700 Subject: Try this In-Reply-To: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> Message-ID: <1189973653.462130.326280@22g2000hsm.googlegroups.com> On Sep 16, 6:46 pm, GeorgeRXZ wrote: > If you have Microsoft windows 98/2000/ME/XP/2003 Operating System on > your PC. > Then Open the Notepad and type the following sentence, and save the > file and close the notepad. Now reopen the file and you will find out > that, Notepad is not able to save the following text line. > > Well you are speed > > This occurs not only with above sentence but any sentence that has > > 4 3 3 5 (sequence of characters: Well=4 you=3 are=3 speed=5) > > When type following sentence and save file then same thing occurs. > > This is not Maria > > GEOrgE OMG it's mutating - I typed in just one 6-letter word ("donkey") and saved it and opened it again and it had become 3 ****ese characters. Code Four! [1] Man the barricades! Send round the fiery cross! Aux armes, citoyens! Formez vos bataillons! Hang on a minute, by the dawn's early light (it's 06:00 here) the characters look like a tri-zapper Dalek, a WW2 tank, and the sheep character with a "wood" radical. Uh-huh. Looks like they're going to attack some place using a Trojan sheep. Could only be NZ. Who cares? Panic over. ==== [1] "1 if by land, 2 if by sea, 3 if by air, 4 if by internet" From XX.XmcX at XX.XmclaveauX.com Mon Sep 3 00:59:48 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Mon, 03 Sep 2007 06:59:48 +0200 Subject: [python-win32] How can I get the parentWindow.document object? References: <1188695505.993750.180020@19g2000hsx.googlegroups.com> Message-ID: Hi! > ie = win32com.client.Dispatch("InternetExplorer.Application") > doc=ie.Document.parentWindow.document Use bridge variable : window=ie.Document.parentWindow And work with : print window.Document.body.name -- @-salutations Michel Claveau From gagsl-py2 at yahoo.com.ar Tue Sep 18 03:34:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Sep 2007 04:34:24 -0300 Subject: The meaning of a = b in object oriented languages References: <1190094057.976729.285120@n39g2000hsh.googlegroups.com> <1190098656.030658.66380__39607.8769270845$1190098987$gmane$org@57g2000hsv.googlegroups.com> Message-ID: En Tue, 18 Sep 2007 03:57:36 -0300, Summercool escribi?: > i think the line > > a = "different" > > means a is now set to a pointer to the String object with content > "different". > or that "a is now a reference to the String object." > > and b is still a reference to the Array object. so that's why a and b > print out different things. they point to different objects. > > i think: > > whenever in Ruby, Python, and Java, > > a is never an object. a is always a "reference to an object"... this > will solve a lot of puzzles when we don't understand some code > behaviors. Yes, but extrapolating that to "In OOPL, a=b just copies a reference" is wrong. "Old" languages like Fortran use the "boxed" model, and "modern" languages tend to use the "reference" model, and since OO languages are younger... But this rather old post by Alex Martelli explains it better -- Gabriel Genellina From grante at visi.com Tue Sep 11 16:53:00 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 11 Sep 2007 20:53:00 -0000 Subject: Difference between two times (working ugly code, needs polish) References: Message-ID: <13ee01cfc7f4be2@corp.supernews.com> On 2007-09-11, Shawn Milochik wrote: > I have done what I wanted, but I think there must be a much better way. See the strptime() function in either the time or the datetime modules: http://docs.python.org/lib/module-time.html http://docs.python.org/lib/module-datetime.html -- Grant Edwards grante Yow! Here we are in America at ... when do we collect visi.com unemployment? From s.mientki at id.umcn.nl Wed Sep 26 03:50:21 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 26 Sep 2007 09:50:21 +0200 Subject: ANN: PyPE 2.8.7 In-Reply-To: <1190782361.392001.48790@g4g2000hsf.googlegroups.com> References: <1190782361.392001.48790@g4g2000hsf.googlegroups.com> Message-ID: thebjorn wrote: > On Sep 25, 12:37 pm, stef wrote: > >> Josiah Carlson wrote: >> >>> === What is PyPE? === >>> PyPE (Python Programmers' Editor) was written in order to offer a >>> lightweight but powerful editor for those who think emacs is too much >>> and idle is too little. Syntax highlighting is included out of the box, >>> as is multiple open documents via tabs. >>> >> sounds very good, >> so now I want to try it ... >> ... the windows ansi zip file is corrupted :-( >> ... the unicode version crashes :-( >> >> This is what the log file tells: >> Traceback (most recent call last): >> File "pype.py", line 110, in ? >> File "zipextimporter.pyc", line 78, in load_module >> File "configuration.pyc", line 149, in ? >> Exception: Unable to create config directory: 'G:\\.pype' >> >> I don't have a G-drive ;-) >> >> cheers, >> Stef Mientki >> > > You must be doing it wrong. Of course ;-) but what am I doing wrong ? cheers, Stef > Works flawlessly for me (no g: drive here > either) -- well, except that it doesn't have Emacs keybindings . > > -- bjorn > > From gagsl-py2 at yahoo.com.ar Fri Sep 14 23:27:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Sep 2007 00:27:09 -0300 Subject: subclass of integers References: <1189780201.692192.291010@k79g2000hse.googlegroups.com> <1189811796.011837.75780@r29g2000hsg.googlegroups.com> Message-ID: En Fri, 14 Sep 2007 20:16:36 -0300, Dan Bishop escribi?: > On Sep 14, 9:30 am, Mark Morss wrote: >> I would like to construct a class that includes both the integers and >> None. I desire that if x and y are elements of this class, and both >> are integers, then arithmetic operations between them, such as x+y, >> return the same result as integer addition. However if either x or y >> is None, these operations return None. > > Rather than subclassing int, why not just make a singleton NaN object > with overloaded arithmetic operators that all return NaN? Like this: class _NaN(object): __instance = None def __new__(cls): if cls.__instance is None: cls.__instance = super(_NaN, cls).__new__(cls) return cls.__instance __repr__ = __str__ = lambda self: 'NaN' def unop(self): return self def binop(self, other): return self def terop(self, other, unused=None): return self def false2(self, other): return False def true2(self, other): return True def notimpl(self): return NotImplemented __abs__ = __invert__ = __neg__ = __pos__ = unop __add__ = __and__ = __div__ = __divmod__ = __floordiv__ = __lshift__ = __mod__ = __mul__ = __rshift__ = __or__ = __sub__ = __truediv__ = __xor__ = binop __radd__ = __rand__ = __rdiv__ = __rdivmod__ = __rfloordiv__ = __rlshift__ = __rmod__ = __rmul__ = __rpow__ = __rrshift__ = __ror__ = __rsub__ = __rtruediv__ = __rxor__ = binop __pow__ = terop __lt__ = __le__ = __eq__ = __gt__ = __ge__ = false2 __ne__ = true2 del unop, binop, terop, false2, true2, notimpl NaN = _NaN() def test(): assert NaN + 1 is NaN assert 1 & NaN is NaN assert NaN * NaN is NaN assert abs(NaN) is NaN assert str(NaN)=="NaN" assert repr(NaN)=="NaN" assert not (NaN==NaN) assert (NaN!=NaN) assert not (NaN>NaN) assert not (NaN=NaN) assert not (NaN<=NaN) assert not (NaN==1) assert (NaN!=1) assert not (NaN>1) assert not (NaN<1) assert not (NaN>=1) assert not (NaN<=1) assert not (1==NaN) assert (1!=NaN) assert not (1>NaN) assert not (1=NaN) assert not (1<=NaN) assert cmp(NaN, 1)!=0 assert cmp(1, NaN)!=0 #assert cmp(NaN, NaN)!=0 assert NaN is _NaN() assert NaN is type(NaN)() test() -- Gabriel Genellina From arkanes at gmail.com Mon Sep 10 10:24:12 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 10 Sep 2007 09:24:12 -0500 Subject: Checking if elements are empty In-Reply-To: References: <2323A6D37908A847A7C32F1E3662C80E010A0246@dc1ex01.air.org> <46e115e5$0$7691$9b4e6d93@newsspool2.arcor-online.net> <46e2013a$0$7687$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4866bea60709100724k5834823cm2ab0eaa068b20090@mail.gmail.com> On 9/10/07, Neil Cerutti wrote: > On 2007-09-08, Wildemar Wildenburger wrote: > > Lawrence D'Oliveiro wrote: > >>>>> if y[0]: > >>>> Not a good idea. > >>> Why not? > >> > >> Because there is a situation where your version of the test > >> will fail even if the first element of y is non-null. > > > > Such as? Seriously people, a little more verbosity wouldn't > > hurt here. This isn't a mystery game. > > >>> if "": True > ... > >>> if 0: True > ... > >>> if []: True > ... > >>> if {}: True > ... > >>> if None: True > ... > > That's may not be all the possibilities. Lots of Python objects > can evaluate to false in a boolean context. > All of these except 0 and None will also return False if you check the length. In fact, I am not aware of any builtin where len() will return 0, but it will be true in a boolean context. If you're advocating being more specific in the hope of catching errors, this is a pretty terrible example. The OP wasn't checking for "null", whatever that means - he was checking for the empty string, in a list known (or intended) to contain only strings. The simple boolean check is totally appropriate. From istvan.albert at gmail.com Mon Sep 24 14:38:52 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Mon, 24 Sep 2007 18:38:52 -0000 Subject: Newbie completely confused In-Reply-To: References: Message-ID: <1190659132.073599.99190@k79g2000hse.googlegroups.com> Two comments, > ... > self.item3 = float(foo[c]); c+=1 > self.item4 = float(foo[c]); c+=1 > self.item5 = float(foo[c]); c+=1 > self.item6 = float(foo[c]); c+=1 > ... this here (and your code in general) is mind boggling and not in a good way, as for you original question, I don't think that reading in files of the size you mention can cause any substantial problems, I think the problem is somewhere else, you can run the code below to see that the read times are unaffected by the order of processing ---------- import timeit # make a big file NUM= 10**5 fp = open('bigfile.txt', 'wt') longline = ' ABC '* 60 + '\n' for count in xrange( NUM ): fp.write( longline ) fp.close() setup1 = """ def readLines(): data = [] for line in file('bigfile.txt'): data.append( line ) return data """ stmt1 = """ data = readLines() """ stmt2 = """ data = readLines() data = readLines() """ stmt3 = """ data = file('bigfile.txt').readlines() """ def run( setup, stmt, N=5 ): t = timeit.Timer(stmt=stmt, setup=setup) msec = 1000 * t.timeit(number=N)/N print "%f msec/pass" % msec if __name__ == '__main__': for stmt in (stmt1, stmt2, stmt3): run(setup=setup1, stmt=stmt) From pablo at decode.com.ar Sat Sep 29 19:32:54 2007 From: pablo at decode.com.ar (Pablo Ziliani) Date: Sat, 29 Sep 2007 20:32:54 -0300 Subject: Program inefficiency? In-Reply-To: <1191089606.852125.276040@22g2000hsm.googlegroups.com> References: <1191079347.192272.240540@22g2000hsm.googlegroups.com> <1191087234.915654.182370@k79g2000hse.googlegroups.com> <1191089606.852125.276040@22g2000hsm.googlegroups.com> Message-ID: <46FEE0A6.2080405@decode.com.ar> thebjorn wrote: > On Sep 29, 7:55 pm, Pablo Ziliani wrote: > >> thebjorn wrote: >> >>> Ugh, that was entirely too many regexps for my taste :-) >> Oh yeah, now it's clear as mud. >> > > I'm anxiously awaiting your beacon of clarity ;-) > Admittedly, that was a bit arrogant from my part. Sorry. >> I do think that the whole program shouldn't take more than 10 lines of >> code >> > > Well, my mass_replace above is 10 lines, and the actual replacement > code is a one liner. Perhaps you'd care to illustrate how you'd > shorten that while still keeping it "clear"? > I don't think he relevant code was only those 10 lines, but well, you have already responded to the other question yourself in a subsequent post (thanks for saving me a lot of time). I think that "clear" is a compromise between code legibility (most of what you sacrifice using regexes) and overall code length. Even regexes can be legible enough when they are well documented, not to mention the fact that is an idiom common to various languages. >> using one sensible regex >> > > I have no doubt that it would be possible to do with a single regex. > Whether it would be sensible or not is another matter entirely... > Putting it in those terms, I completely agree with you (that's why I suggested letting e.g. BeautifulSoup deal with them). But by "sensible" I meant something different, inherent to the regex itself. For instance, I don't think I need to explain to you why this is not sensible: (href=|HREF=)+(.*)(#)+(.*)(\w\'\?-<:)+(.*)(">)+ > >> (impossible to define without knowing the real input and output formats). >> > > Of course, but I don't think you can guess too terribly wrong. My > version handles upper and lower case attributes, quoting with single > (') and double (") quotes, and any number of spaces in attribute > values. It maintains all other text as-is, and converts spaces to > underscores in href and name attributes. Did I get anything majorly > wrong? > Well, you spent some time interpreting his code. No doubt you are smart, but being a lazy person (not proud of that, unlike other people stating the same) I prefer leaving that part to the interested party. > >> And (sorry to tell) I'm convinced this is a problem for regexes, in >> spite of anybody's personal taste. >> > > Well, let's see it then :-) IMO, your second example proves it well enough. FWIW I did some changes to your code (see attached), because it wasn't taking into account the tag name (), and the names of the attributes (href, name) can appear in other tags as well, so it's a problem. It still doesn't solve the problem of one tag having both attributes with spaces (which can be easily fixed with a second regex, but that was out of question :P), and there can be a lot of other problems (both because I'm far from being an expert in regexes and because I only tested it against the given string), but should provide at least some guidance. I made it also match the id of the target anchor, since a fragment can point both to its name or its id, depending on the doctype. Regards, Pablo -------------- next part -------------- A non-text attachment was scrubbed... Name: fixurls.py Type: text/x-python Size: 1339 bytes Desc: not available URL: From steve at holdenweb.com Fri Sep 28 15:08:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Sep 2007 15:08:25 -0400 Subject: Python 3.0 migration plans? In-Reply-To: <1191004803.604547.213280@o80g2000hse.googlegroups.com> References: <1191002679.569709.16870@22g2000hsm.googlegroups.com> <1191004803.604547.213280@o80g2000hse.googlegroups.com> Message-ID: TheFlyingDutchman wrote: > On Sep 28, 11:16 am, Jean-Paul Calderone wrote: >> On Fri, 28 Sep 2007 11:04:39 -0700, TheFlyingDutchman wrote: >>> [snip] >>> In this case I asked it as part of the original question and it was >>> ignored. I have programmed in C and C++ and a little Pascal many years >>> ago. I don't remember anything about Higher Order Functions and would >>> like to see exactly how you do it and to verify the contention. >> Perhaps you could do a bit of independent research. Then your messages >> to the group could contain more thoughtful questions and responses. >> > But you miss the fact that I am providing value to the group by > providing unthoughtful questions and unthoughtful responses. By having > most of the pocket protectors being thrown at me, I provide a > diversion that allows others to speak more freely and without fear of > reproach. > > It's the knives and hand grenades you want to worry about. We are a very friendly and welcoming group, but we do have our limits. You're fast approaching 100% on my trollometer. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From kyosohma at gmail.com Thu Sep 6 14:16:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 06 Sep 2007 18:16:54 -0000 Subject: Getting original working directory In-Reply-To: References: Message-ID: <1189102614.459515.206700@57g2000hsv.googlegroups.com> On Sep 6, 10:19 am, rave247 rave247 wrote: > Hi, > > I' am unable to solve this problem. I've got python program, it is installed in standard location. I run this program from some location X (note that I just type relative "myscript", leaving operating system to look up script itself using PATH variable) and this program somewhere in the code calls os.chdir() to change it is current working directory and I would need in python code to get the *original* directory location *after* os.chdir() is performed. This means the location X from which script was performed - it is the location I am in after script is finished. > > Thanks for any help One of the best portable ones that I've seen used is this: os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),'.')) I've used it myself and it works for my needs. Mike From see.signature at no.spam Wed Sep 5 03:49:43 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 05 Sep 2007 09:49:43 +0200 Subject: Tkinter(2) References: <1188913329.457394.94220@g4g2000hsf.googlegroups.com> Message-ID: On Tue, 04 Sep 2007 15:42:09 +0200, vijayca wrote: > my python installation is:Active python 2.5.1 > i am using Red Hat Linux > i have the Tkinter module installed but any simple script produces an > error.... > > script: > from Tkinter import Label > widget = Label(None, text='Hello GUI world!') > widget.pack() > widget.mainloop() > > > error: > Traceback (most recent call last): > File "guy.py", line 2, in > widget = Label(None, text='Hello GUI world!') > File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ > INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 2464, in __init__ > Widget.__init__(self, master, 'label', cnf, kw) > File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ > INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1923, in __init__ > BaseWidget._setup(self, master, cnf) > File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ > INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1898, in _setup > _default_root = Tk() > File "/root/Desktop/pythonall/ActivePython-2.5.1.1-linux-x86/ > INSTALLDIR/lib/python2.5/lib-tk/Tkinter.py", line 1636, in __init__ > self.tk = _tkinter.create(screenName, baseName, className, > interactive, wantobjects, useTk, sync, use) > _tkinter.TclError: no display name and no $DISPLAY environment > variable Basically, this error has nothing to do with Python or Tkinter. If you tried to launch any GUI application, you should get the same error. How are you logged in to your computer? Did you do any remote connection via telnet, or rlogin/rsh, or ssh? This error usually happens when you're logged in on a remote machine, and you didn't tell the remote machine where you wanted to display the windows you open. It may also happen when you're logged in as a user, but did a 'su' to change your identity. In any case, solving the problem is quite easy: define the DISPLAY environment variable with the value :0 and it should work. If you're using a remote machine, you may also have to issue a 'xhost + ' on the local machine (the one where the display should occur). HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From sjmachin at lexicon.net Wed Sep 12 19:48:01 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 12 Sep 2007 16:48:01 -0700 Subject: cpython list __str__ method for floats In-Reply-To: References: <13ectngf3aeqrb0@corp.supernews.com> <5kndseF4iskqU1@mid.individual.net> <13eehfo8nr5eu1d@corp.supernews.com> <5kq2n9F4uhr0U1@mid.individual.net> Message-ID: <1189640881.953654.19610@y42g2000hsy.googlegroups.com> On Sep 12, 10:59 pm, Duncan Booth wrote:> [snip] > I believe the claim is that using the full 17 digits ensures the round- > tripping works even if you serialise and deserialise on different > systems, so perhaps we all pay a cost in our interactive sessions for > something which should really be buried deep in IPC code. IPC? Most data transfer between systems in the real world is done using CSV files :-) From panguohualove at sina.com Sat Sep 29 07:17:33 2007 From: panguohualove at sina.com (panguohua) Date: Sat, 29 Sep 2007 04:17:33 -0700 Subject: earn $12800 a month Message-ID: <1191064653.603143.104680@w3g2000hsg.googlegroups.com> www.space666.com From hyena at gmail.com Mon Sep 24 18:49:05 2007 From: hyena at gmail.com (hyena) Date: Tue, 25 Sep 2007 00:49:05 +0200 Subject: is there some module update(install tools)? Message-ID: <8520e$46f83ee4$4df9f6c6$14843@news2.tudelft.nl> Hi, I am quite new to python and am looking for some tools that can install and update modules a bit more intelligent then "python setup.py install". Is there some thing like "yum" in fedora which can search and install/update packages automatically? thanks in advance! From liangxuliang79 at gmail.com Wed Sep 5 08:03:33 2007 From: liangxuliang79 at gmail.com (liangxuliang79 at gmail.com) Date: Wed, 05 Sep 2007 05:03:33 -0700 Subject: =?gb2312?B?udjT2tPDdXJsbGliIHBvc3TP+8+itcTOyszioaM=?= Message-ID: <1188993813.330662.174660@w3g2000hsg.googlegroups.com> ??www.mmmppp333.com?????http://ishare.iask.sina.com.cn/cgi-bin/ fileid.cgi?fileid=844050 ???post fileid=844050???? ??post??????fileid=844050???server?????header?header??local??location?? ???????????????????????mp3??????????????local??????mp3????????????????? ??????????????? ???????python?urllib????urllib????????????local????????local????mp3???? ????????mp3.? ?post????/download.php? post????fileid=844050?????????????????????????? ??????????web??????????? From fructidor00 at gmail.com Sun Sep 9 09:28:57 2007 From: fructidor00 at gmail.com (GuillaumeC) Date: Sun, 09 Sep 2007 13:28:57 -0000 Subject: Organizing Code - Packages In-Reply-To: <1189296296.175857.158770@22g2000hsm.googlegroups.com> References: <1189177596.960379.244990@w3g2000hsg.googlegroups.com> <46e17143$0$6189$426a74cc@news.free.fr> <1189183088.922537.18290@r34g2000hsd.googlegroups.com> <87r6laa0ir.fsf@rudin.co.uk> <46e1a0bc$0$7689$9b4e6d93@newsspool2.arcor-online.net> <1189280539.449868.169910@22g2000hsm.googlegroups.com> <1189296296.175857.158770@22g2000hsm.googlegroups.com> Message-ID: <1189344537.561864.72120@k79g2000hse.googlegroups.com> On Sep 9, 1:04 am, xkenneth wrote: > On Sep 8, 3:35 pm, David wrote: > > > > How do import statements that are declared at the top of a python > > > module work? > > >http://docs.python.org/tut/node8.html > On Sat, 08 Sep 2007 12:42:19 -0700, xkenneth wrote: > > How do import statements that are declared at the top of a python > > module work? > > They import the module. ;-) Well, not only... They also include the names in the namespace. Using the "import * from" form will bind in each of your modules the name of the errors. You should use import XXX and then use the qualified name XXX.myfunction. Then, you avoid conflicts between names and binding every name from your module. See the documentation for reload() also. > Also, are there any good tutorials/examples out there of how to > organize your python code into packges? This is not new, nor specific to Python, but I think it is a good reference: http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf see section: Principles of Package Architecture From lobais at gmail.com Fri Sep 14 01:57:49 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Fri, 14 Sep 2007 07:57:49 +0200 Subject: distutils install-data-hook Message-ID: Hey I have this pythonapp I'm trying to pack, and I've read in the Gnome specifications that I should run "update-icon-cache" after install, in order to get the menus and stuff correctly updated. Is there a way to specify a (list of) commands to be run after installation? From dijkstra.arjen at gmail.com Mon Sep 17 09:00:41 2007 From: dijkstra.arjen at gmail.com (duikboot) Date: Mon, 17 Sep 2007 13:00:41 -0000 Subject: simple regular expression problem Message-ID: <1190034041.796626.66790@n39g2000hsh.googlegroups.com> Hello, I am trying to extract a list of strings from a text. I am looking it for hours now, googling didn't help either. Could you please help me? >>>s = """ \n\n28996\n\n\n28997\n""" >>> regex = re.compile(r'', re.S) >>> L = regex.findall(s) >>> print L ['organisatie>\n28996\n \n\n28997\n\n28996\n \n), (\n28997\n Message-ID: <5kvkmoF5h7l3U2@mid.uni-berlin.de> On Fri, 14 Sep 2007 15:58:39 +0200, Gigs_ wrote: > >>> def factorial(n): > print "n =", n > if n==0: > return 1 > else: > return n * factorial(n-1) > > >>> factorial(3) > n = 3 > n = 2 > n = 1 > n = 0 > 6 > > > now i understand. but one question at the end this function return 1. how python > knows that it needs to multiply 1 with all recursive returns. (why python didnt > sum recursive return with 1?) Because there is a ``*`` and not a ``+`` in the last line of the function. Let's play this through (I abbreviate the function name to just `f()`): Execution of f(3) leads to the second return: r1 f(3): return 3 * f(2) This multiplication can't take place until ``f(2)`` is calculated so the current function call is "suspended" and evaluated later, when the result of ``f(2)`` is known. The call in that line is replaces with the result then. Calling ``f(2)`` leads to: r2 f(2): return 2 * f(1) The same again, another call to `f()` with 1 as argument: r3 f(1): return 1 * f(0) Now the last call takes the other ``if`` branch: r4 f(0): return 1 The 1 is returned to the previus call: r3 f(1): return 1 * 1 This can be evaluated now and is returned to its caller: r2 f(2): return 2 * 1 Again this is evaluated and returned to its caller: r1 f(3): return 3 * 2 And here we have the final result that is returned from the first call to `f()`. Ciao, Marc 'BlackJack' Rintsch From israel at math.MyUniversitysInitials.ca Sun Sep 30 19:51:06 2007 From: israel at math.MyUniversitysInitials.ca (Robert Israel) Date: Sun, 30 Sep 2007 18:51:06 -0500 Subject: [Python] Matrix convergence References: <1191179438.736054.322700@o80g2000hse.googlegroups.com> Message-ID: Zhengzheng Pan writes: > Hi all, > > I'm trying to check whether a (stochastic/transition) matrix > converges, i.e. a function/method that will return True if the input > matrix sequence shows convergence and False otherwise. The background > is a Markov progress, so the special thing about the transition matrix > is the values of elements in each row add up to be 1. Fail to find any > relevant build-in methods in Python... > > Currently the standard theorem on convergence in Markov chain > literature is involved with the properties of aperiodic and > connectivity, which I'm not able to implement with Python either... > Therefore I'm actually also looking for alternative conditions to > check for convergence, and am willing to sacrifice a little bit of > precision. > > If you have any ideas/suggestions on how to examine the convergence of > a matrix in general or specifically about this kind of matrices, and > are willing to share, that'd be really great. > Do you mean you have an n x n stochastic matrix T and you're trying to find out whether the sequence T^j converges? Let A = (I + T)^(n-1) and B = T^((n-1)^2+1). Powers of matrices are easy to compute using repeated squaring. i and j are in the same class iff A_{ij} > 0 and A_{ji} > 0. A class containing state i is recurrent iff A_{ij} = 0 for all j not in the class. A recurrent class containing state i is aperiodic iff B_{ij} > 0 for all j in the class. T^j converges iff all recurrent classes are aperiodic. Thus the test can be written as follows: For each i, either there is some j for which A_{ij} > 0 but A_{ji} = 0, or there is no j for which A_{ij} > 0 but B_{ij} = 0. -- Robert Israel israel at math.MyUniversitysInitials.ca Department of Mathematics http://www.math.ubc.ca/~israel University of British Columbia Vancouver, BC, Canada From xah at xahlee.org Mon Sep 10 18:57:30 2007 From: xah at xahlee.org (Xah Lee) Date: Mon, 10 Sep 2007 15:57:30 -0700 Subject: encoding latin1 to utf-8 In-Reply-To: <1189427146.723304.270600@22g2000hsm.googlegroups.com> References: <1189427146.723304.270600@22g2000hsm.googlegroups.com> Message-ID: <1189465050.827331.211320@r34g2000hsd.googlegroups.com> On Sep 10, 5:25 am, Harshad Modi wrote: > hello , > I make one function for encoding latin1 to utf-8. but i think it is > not work proper. > plz guide me. Hi, what you want is here, including complete code: Converting a File's "Character Set" / Encoding http://xahlee.org/perl-python/charset_encoding.html Xah xah at xahlee.org ? http://xahlee.org/ From zzbbaadd at aol.com Fri Sep 28 04:38:27 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Fri, 28 Sep 2007 01:38:27 -0700 Subject: Python 3.0 migration plans? In-Reply-To: <5m3p1dFbl98pU1@mid.uni-berlin.de> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <87641v4j38.fsf@benfinney.id.au> <1190949502.875203.57690@w3g2000hsg.googlegroups.com> <5m3p1dFbl98pU1@mid.uni-berlin.de> Message-ID: <1190968707.799398.232550@19g2000hsx.googlegroups.com> > > The fact that you compare and criticise the simple annotations like > static or abstract with the much more powerful decorator concept shows > that, despite being the maintainer of a > soon-to-be-ruling-the-python-world Python 3 fork, lack understanding of > even the most basic language features. Which isn't exactly news.[1] Don't you mean "lack appreciation for the non-basic language features"? static, class and abstract are basic language features that I appreciate. "decorators" have been in Python for only a small part of its existence, they aren't in the vast majority of languages (if any other language even has them) which means people write all kinds of software without them. Or rather, most of the software ever written didn't use decorators. Doesn't sound basic at all. > > Maybe you should start using python more and _then_ start discussions > about it's features, when you have good grounds and can provide viable > alternatives? But I guess that's a wish that won't be granted.... static and abstract keywords would seem to be very viable alternatives. Viable enough that several language designers used them. From ldo at geek-central.gen.new_zealand Sun Sep 9 04:05:17 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 09 Sep 2007 20:05:17 +1200 Subject: getting the current function References: Message-ID: In message , Gary Robinson wrote: > I've just never liked the fact that you have to name the function when > accessing those attributes from within the function. If it's any consolation, it's not actually the function name you need to refer to, merely any variable or Python object that happens to hold a reference to the right function: >>> f = lambda x : x + x >>> f(2) 4 >>> f.myattr = "yeah" >>> g = f >>> g.myattr 'yeah' >>> g = [f] >>> g[0].myattr 'yeah' >>> g[0](3) 6 From george.sakkis at gmail.com Fri Sep 21 17:49:59 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 21 Sep 2007 21:49:59 -0000 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190394011.148384.106280@q3g2000prf.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> <1190394011.148384.106280@q3g2000prf.googlegroups.com> Message-ID: <1190411399.483431.86420@w3g2000hsg.googlegroups.com> On Sep 21, 1:00 pm, Python Maniac wrote: > My best runtime with Ruby using the same machine and OS was 67.797 > secs which is 29.8x slower than the fastest Python runtime. This > makes Ruby almost as slow as Python was made faster. The irony with > Ruby was that the use of a hash in Ruby actually made the Ruby code > run slower than when a hash was not used. I'm not familiar with Ruby but chances are that if you post at c.l.ruby you'll get some good suggestions on how to speed up your ruby code too (although the difference may not be so dramatic). > Now I think I will code this little scrambler using nothing but the D > Language just to see whether there is any benefit in using D over > Python for this sort of problem. And then you'll do it in assembly to see how much do you gain compared to D ? If this is not just for learning purposes, perhaps you should be thinking it the other way around: how fast is fast enough ? Optimizing just for the sake of optimization, without a specific performance goal in mind, is not the most productive way to do things (again, leaving learning motivations aside). George From jcd at sdf.lonestar.org Mon Sep 17 06:30:46 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 17 Sep 2007 06:30:46 -0400 Subject: Python "with" In-Reply-To: References: Message-ID: <46EE5756.7090107@sdf.lonestar.org> Ivan Voras wrote: > Laurent Pointal wrote: > >> The ugly part is the 'tmp' name, try to choose a name with a proper >> meaning about what it is really, and it become clean and readable: >> >> filerefs = some.big.structure.or.nested.object.with.file.references >> filerefs.encoding = "utf-8" >> filerefs.name = "MyFileName.txt" >> filerefs.use_quotes = True >> >> Isn't it ? > > Well, no, but this might be due to personal tastes. At least, I don't > think it's better then some other alternatives. For example, in C99 > you can do: > > static struct option_s foo_option = { > .name = "foo", > .type = O_STRING, > .def_value = "default" > }; > > At least to me, this looks even better than the Pascal's syntax. > > So basically, what you're saying is you don't like namespace prefixes at all? Keeping your namespaces separate will help the clarity of your code immensely, unless, arguably, you're doing heavy numerical processing, goes the argument in a recent thread. Probably what will help you the most is not a fancy trick for getting rid of the namespace, but getting over your aversion to them. That will make you a better programmer, in the long run. Debugging will be easier, people will enjoy working with your code more. Clarity is beautiful. Objectively so. Not just some lame "in the eye of the beholder" kind of beautiful. Cheers, Cliff From fw3 at hotmail.co.jp Fri Sep 7 12:42:42 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Fri, 07 Sep 2007 16:42:42 +0000 Subject: Speed of Python Message-ID: Hi, While comparing the speed of octave and matlab, I decided to do a similar test for python and matlab. The result shows that python is slower than matlab by a factor of 5. It is not bad since octave is about 30 time slower than matlab. Here is the result in matlab: Elapsed time is 0.015389 seconds. and in Python: >>> t=timeit.Timer("bench1.bench1(10)","import bench1") >>> t.repeat(1,1) [0.071012377266015392] Here is the bench1.py: import math def bench1(n): for i in range(n): for j in range(1000): m=j+1 z=math.log(m) z1=math.log(m+1) z2=math.log(m+2) z3=math.log(m+3) z4=math.log(m+4) z5=math.log(m+5) z6=math.log(m+6) z7=math.log(m+7) z8=math.log(m+8) z9=math.log(m+9) return z9 Is my conclusion correct that Python is slower than matlab? Are there any way to speed it up? It seems Python automatically created bench1.pyc. Does Python automatically execute the bench1.pyc to speed it up? Thanks Frank _________________________________________________________________ ???????? ????????????????????????? http://chizumaga.jp/ From __peter__ at web.de Mon Sep 24 12:24:22 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Sep 2007 18:24:22 +0200 Subject: Converting numbers to unicode charaters References: <1190641342.127770.115610@y42g2000hsy.googlegroups.com> Message-ID: Duncan Booth wrote: > Laurent Pointal wrote: > >> You may eventually use a more condensed expression and avoid n >> concatenation of n chars using join, like this: >> >> >>> u''.join(unichr(int(x,16)) for x in ['42','72','61','64']) >> u'Brad' > > Or even avoid the loop completely: > >>>> hexs = ['42', '72', '61', '64'] >>>> u'\\x'.join(['']+hexs).decode('string-escape') > 'Brad' > > (but for that to work you really do need to be sure that all the values are > 2 characters). Or >>> "".join(['42', '72', '61', '74']).decode("hex").decode("latin1") u'Brat' (same caveat) Peter From bdesth.quelquechose at free.quelquepart.fr Wed Sep 19 15:52:06 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 19 Sep 2007 21:52:06 +0200 Subject: Using pseudonyms (was Re: Python 3K or Python 2.9?) In-Reply-To: References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46effd63$0$16044$426a74cc@news.free.fr> Message-ID: <46f17e0d$0$31727$426a34cc@news.free.fr> Aahz a ?crit : > In article <46effd63$0$16044$426a74cc at news.free.fr>, > Bruno Desthuilliers wrote: > (snip) >>>>>(For those joining only recently, my full legal name is "Aahz", which I >>>>>changed from my former name precisely because of attitudes like Bruno's.) >> >>For the record, I usually don't give a damn about what >>name/nickname/whatever peoples use. > > > Then why mention pseudonyms at all? My fault - I'm sometimes a bit overreactive, and Mr TheFlyingDutchman, (aka zzbbaadd) was starting to get on my nerves. I know I shouldn't have post this one, and I apologize. From gagsl-py2 at yahoo.com.ar Thu Sep 13 01:51:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Sep 2007 02:51:04 -0300 Subject: Python code-writing for the blind. Was (Re: newbie: stani's pythoneditor if-else) References: <1189531123.283413.160870@22g2000hsm.googlegroups.com> <588D53831C701746A2DF46E365C018CE01D2CB3F@LITEXETSP001.etrsouth.corp.entergy.com> Message-ID: En Tue, 11 Sep 2007 14:28:35 -0300, Hamilton, William escribi?: > Can you set SPE to use a single space rather than the typical four > spaces? Python should accept it just fine. You'll still have problems > reading other people's code. Maybe you can write a quick script that > converts code down to one-space indents. The existing demo script reindent.py (in tools/Scripts) does exactly that, but using 4 spaces. Just replace the number 4 in its source code by a variable name (it occurs only twice) and it's done. -- Gabriel Genellina From pavlovevidence at gmail.com Fri Sep 21 19:52:41 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 21 Sep 2007 19:52:41 -0400 Subject: Would Anonymous Functions Help in Learning Programming/Python? References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> Message-ID: <46f45f02$0$15350$4c368faf@roadrunner.com> On Fri, 21 Sep 2007 21:37:18 +0000, Cristian wrote: > Although his learning experience has gone mostly smoothly, he's hit a > lot of speed bumps with functions. Specifically, he's having trouble > thinking of functions as first order data (don't worry, I haven't > confused him with such terminology yet). He had a little trouble > understanding that you can pass functions as arguments to other > functions (e.g., passing a key to the list.sort method). He also had a > little trouble grasping functions within other functions. Last but not > least, he had trouble grasping methods in class declarations, especially > the required self as the first argument (I'm sure he wasn't the first). First of all, let me say that I think "functions as first class data" is helpful, but not crucial, to programming in Python, and there are many people who simply don't need the lesson. Especially someone like an engineer (in the classical sense), who isn't building versatile software packages, won't need to resort to functional programming much. For straightforward tasks, like sorting lists with a custom ordering, functional progamming merely a convenience, and can be done without. So I'm -1 on syntactic changes to the language to support a pedagogical use that's not crucially important. Now, as for the more general question--How do you teach functional concepts?--because some people do need to know it. I suspect it's one of those things where there are two possibilities and not much in between. Either 1. The person gets it right away. or 2. The person doesn't get it right away. In the latter case, trying to teach it conceptually is probably hopeless. Best thing to do is teach functional usage for certain use cases. For instance, teach someone to define a function returning a key, and have them use "key=myfunc" in list.sort--and not worry about why it works. If they keep at it, eventually one of two things will happen. Either, 2a. The person will have an "A ha! I get it now!" moment, and will finally understand the concept. or 2b. The person will never get it. Carl Banks From gandalf at designaproduct.biz Thu Sep 13 05:55:26 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 13 Sep 2007 11:55:26 +0200 Subject: I want py2exe not to create library.zip In-Reply-To: <13egu7rmilu2ia4@corp.supernews.com> References: <13egu7rmilu2ia4@corp.supernews.com> Message-ID: <46E9090E.2080108@designaproduct.biz> >> I want py2exe not to create library.zip. >> > > setup ( > [...] > options = {"py2exe": {"skip_archive":1}} > ) > Cool! Just what I needed. Where it is documented? Ah, in the source. :-) From simon.hibbs at gmail.com Wed Sep 19 15:46:22 2007 From: simon.hibbs at gmail.com (Simon Hibbs) Date: Wed, 19 Sep 2007 12:46:22 -0700 Subject: Using python to create windows apps that everyone can use? In-Reply-To: References: <7C008A37566.00000D2Atomharding@inbox.com> Message-ID: <1190231182.174676.306980@r29g2000hsg.googlegroups.com> On 9/18/07, Thomas Harding wrote: > Hi guys, sorry to post another topic on this, as I am aware that it has > already been posted a few times, but not with specifically what I am looking > for. I want an app that makes a gui interface for python (similar to > Microsoft visual studio or qt designer, not a code based one) and/ or an app > that can make this into a .exe that can be opened by any person on any > computer without python installed. For windows only, there's always Iron Python. This allows you to use Visual Studio, the commercial or the express version, to create the GUI in VB or C# and from that call Python code that does all the heavy lifting. I'd second the recommendation for QtDesigner if you want cross- platform capability. Simon Hibbs From gregpinero at gmail.com Wed Sep 12 14:31:56 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Wed, 12 Sep 2007 18:31:56 -0000 Subject: Get Only the Last Items in a Traceback In-Reply-To: References: <1189562968.529414.27910@w3g2000hsg.googlegroups.com> <1189609742.781671.143320@g4g2000hsf.googlegroups.com> Message-ID: <1189621916.517654.200410@g4g2000hsf.googlegroups.com> On Sep 12, 11:35 am, Peter Otten <__pete... at web.de> wrote: > Am Wed, 12 Sep 2007 15:09:02 +0000 schrieb gregpin... at gmail.com: > > > > > On Sep 12, 5:17 am, Peter Otten <__pete... at web.de> wrote: > > >> Your assessment is wrong. You only get the extra lines in the traceback if > >> you don't immediately wrap the exec statement in a try ... except block: > >> $ cat snip_traceback3.py > >> import sys > >> import traceback > > >> def alpha(): > >> beta() > > >> def beta(): > >> gamma() > > >> def gamma(): > >> try: > >> exec s in {} > >> except Exception, e: > >> etype, value, tb = sys.exc_info() > >> traceback.print_exception(etype, value, tb.tb_next) > > >> s = """ > >> def delta(): > >> epsilon() > > >> def epsilon(): > >> 1/0 > >> delta() > >> """ > > >> if __name__ == "__main__": > >> alpha() > > >> $ python snip_traceback3.py > >> Traceback (most recent call last): > >> File "", line 7, in > >> File "", line 3, in delta > >> File "", line 6, in epsilon > >> ZeroDivisionError: integer division or modulo by zero > > >> Heureka. > > Thanks for the help, Peter. That's exactly what I need. > > Indeed. But not exactly what you want, it seems. > > > Now could I > > use your tb.tb_next trick a couple times and thus avoid moving the try/ > > except? > > Of course you can cut off the traceback at arbitrary positions. Here's an > example that uses the filename: > > import traceback > import sys > > def tb_filename(tb): > return tb.tb_frame.f_code.co_filename > > def tb_iter(tb): > while tb is not None: > yield tb > tb = tb.tb_next > > def alpha(): > try: > beta() > except Exception, e: > etype, value, tb = sys.exc_info() > filename = tb_filename(tb) > for tb in tb_iter(tb): > if tb_filename(tb) != filename: > break > traceback.print_exception(etype, value, tb) > > def beta(): > gamma() > > def gamma(): > exec s in {} > > s = """ > def delta(): > epsilon() > > def epsilon(): > 1/0 > delta() > """ > > if __name__ == "__main__": > alpha() > > Did I mention it already? It's better to move the try ... except. > > Peter This approach is ideal. Indirect, but ideal :-) I'll apply it tonight. It's complicated but suffice it to say it would be difficult to move the try/except. Thanks for the help. Way to know about tracebacks, very impressive! -Greg From jjl at pobox.com Wed Sep 19 15:39:36 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 19 Sep 2007 19:39:36 GMT Subject: Odd files; just left behind? References: Message-ID: <878x725ts7.fsf@pobox.com> Robin Becker writes: > I see a folder .python-eggs in my home directory on one of our servers > with various .so files > > ~/.python-eggs/MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg-tmp/_mysql.so > > are these just left behind from some install process? Ah, it's about the resource extraction feature of setuptools. It's possible for zipped eggs to contain resources that have to be extracted to the filesystem. It puts them in the directory you saw (or somewhere else -- see the docstring in my other reply). http://peak.telecommunity.com/DevCenter/PkgResources#resource-extraction http://peak.telecommunity.com/DevCenter/setuptools#automatic-resource-extraction John From jgardner.jonathangardner.net at gmail.com Tue Sep 11 16:41:40 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Tue, 11 Sep 2007 20:41:40 -0000 Subject: Python Database Apps In-Reply-To: <1189543168.276429.290180@e34g2000pro.googlegroups.com> References: <1189479130.905136.196820@r34g2000hsd.googlegroups.com> <1189543168.276429.290180@e34g2000pro.googlegroups.com> Message-ID: <1189543300.428589.150280@t8g2000prg.googlegroups.com> On Sep 11, 1:39 pm, Jonathan Gardner wrote: > > For client-side apps, managing a PostgreSQL installation might be > asking too much. But for a web site or web service, I absolutely > recommend it. I should mention that I wrote a medical billing software app (client side--PyQt) in Python with a PostgreSQL backend and there were no problems (aside from managing the database--which was easy.) That was over 4 years ago though. From fredrik at pythonware.com Wed Sep 26 07:27:02 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Sep 2007 13:27:02 +0200 Subject: Documentation about pyexpat In-Reply-To: <7.0.1.0.1.20070926124001.01c055b8@medienkonzepte.de> References: <7.0.1.0.1.20070926124001.01c055b8@medienkonzepte.de> Message-ID: Horst J?ger wrote: > is there any documentation about the pyexpat lib? observation 1: http://docs.python.org/lib/module-xml.parsers.expat.html "This module uses the pyexpat module to provide access to the Expat parser. Direct use of the pyexpat module is deprecated." observation 2: $ more xml/parsers/expat.py """Interface to the Expat non-validating XML parser.""" __version__ = '$Revision: 17640 $' from pyexpat import * From sbassi at clubdelarazon.org Sun Sep 16 17:25:41 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 16 Sep 2007 18:25:41 -0300 Subject: Saving parameters between Python applications? In-Reply-To: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> References: <1189969538.830532.98840@g4g2000hsf.googlegroups.com> Message-ID: <9e2f512b0709161425p56089b8bg148a95bccfca6781@mail.gmail.com> On 9/16/07, Stodge wrote: > python app1.py --location=c:\test1 > What I want to do is save the location parameter, so I can then do (in > the same window): > python app2.py > And have app2.py automatically have access to the value of "location". Do app1.py to save a pickle of the value you want app2 to read. -- Sebasti?n Bassi (???????). Diplomado en Ciencia y Tecnolog?a. Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From sjmachin at lexicon.net Mon Sep 3 20:10:53 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 03 Sep 2007 17:10:53 -0700 Subject: trap setting attribute when the attribute is dict In-Reply-To: References: <1188845236.417709.307160@50g2000hsm.googlegroups.com> Message-ID: <1188864653.854065.80100@g4g2000hsf.googlegroups.com> On Sep 4, 5:47 am, wrote: > Arnaud Delobelle wrote: > > On Sep 3, 7:00 pm, wrote: > > >> I want to do something like this. My class/instance has a dict as a > >> property. I want the instance to catch the change in the dict (change > >> in some values, addition/deletion of key/value etc) to be recognized by > >> the class instance. > > >> How can I do this? Any suggestions are very well appreciated. > > >> Here is an example of what I want my class to behave: > > >> class test(object): > >> def __init__(self): > >> self._d = {} > >> self._changed = False > >> def getd(self): > >> print 'called getd' > >> return self._d > >> # dont know what to do next > >> def setd(self,val): > >> print 'called setd', key, val > >> self._d[key] = val > > Where does the 'key' come from? Perhaps you need to look further into > > how properties work. > > This obviously doesn't work... > > > > >> self._changed = True > >> d = property(getd,setd,None,None) > > >> def getc(self): > >> return self._changed > >> changed = property(getc,None,None,None) > > >> if __name__ == '__main__': > >> obj = test() > >> print 'obj.changed = ', obj.changed > >> print > > >> # I want obj to know that its propety d being changed here > >> print "t.d['a'] = 1" > >> obj.d['a'] = 1 > >> print > > >> # I want the "changed" property to be True > >> print 'obj.changed = ', obj.changed > > > You can't do that with plain dicts, and I'm not sure it is often a > > good idea. However you could create a class that behaves like a dict > > but calls a function each time an item is set, e.g. (made up > > terminology): > >>>> class TriggerDict(object): > > ... def __init__(self, trigger, val=None): > > ... self.trigger = trigger > > ... self.dict_ = val or {} > > ... def __setitem__(self, key, val): > > ... self.trigger(self, key, val) > > ... self.dict_[key] = val > > ... def __getitem__(self, key): > > ... return self.dict_[key] > > ... > >>>> def trigger(d, k, v): > > ... print '%s => %s' % (k, v) > > ... > >>>> td = TriggerDict(trigger) > >>>> td['spanish'] = 'inquisition' # see side effect below. > > spanish => inquisition > >>>> td['spanish'] > > 'inquisition' > > > Obviously your trigger function would set the _changed attribute of > > the test object instead. And again it is probably not a good idea > > unless you know exactly what you are doing. If it was me, I'd try to > > rethink my design instead. > > Thank you for suggestion, Arnaud. > > Since you are discouraging this idea of trigger, may I ask an advice of > if my intention was legitimate one or not? > > My intention was to have a propery 'sum' in my object, and which has sum > of all the values() of the dict (i have code to make sure that the value > of dict are all numeric). I could just the propery being calculated > everytime the property got __getattr__. But I thought that it was > inefficient to calculate the same number over and over when the value is > already known. So I was thiking of calculating the number only when the > dict got modified. > > I also experimented with the idea of subclassing dict itself to > calculate the sum. Is this what would be better solution? > And what's wrong with calculating the value when you need it ... def thedictsum(self): return sum(self.thedict.itervalues()) How big will the dict be, how often will it be updated, how often will the sum be required? Have you done timings of any of the options? You say you have code to check that the values are numeric; why not put this together with maintenance of the sum into a method which clients must use to update the dict? BTW, my motto: "__" == "Danger, Will Robinson!" == "Wrong way, go back" :-) HTH, John From jcd at sdf.lonestar.org Fri Sep 21 19:27:30 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 21 Sep 2007 19:27:30 -0400 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <1190415741.380795.259050@y42g2000hsy.googlegroups.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <1190415741.380795.259050@y42g2000hsy.googlegroups.com> Message-ID: <46F45362.7090604@sdf.lonestar.org> Cristian wrote: > On Sep 21, 3:44 pm, Ron Adam wrote: > > >> I think key may be to discuss names and name binding with your friend. How >> a name is not the object it self, like a variable is in other languages. >> For example show him how an object can have more than one name. And discus >> how names can be bound to nearly anything, including classes and functions. >> > > I could discuss name binding but it would be great if Python said this > itself. After all, you can even bind a module with the foo = bar > syntax by using __import__ function. If function definitions followed > the same pattern, I think a beginner would subconsciously (maybe even > consciously) realize that function names are just like everything > else. Actually, this would be helpful for many people. If you come > from a language like Java you're used to thinking of attributes and > methods as living in different namespaces. I think a new syntax will > encourage seasoned programmers think in a more Pythonic way. > However, you still have to solve the problem of using a single-line construct (x = y) with a multi-line definition. That is the essential difference that def is designed to solve. The __import__ trick works because import is also a single line construct. The only proposal given in this thread is using consistent indentation within the parentheses, but parentheses are already explicitly designed to let you ignore the whitespace rules. To suddenly create a situation in which you have significant whitespace on the right side of an assignment statement, and *within parentheses* will break too much code, and make the solution unnecessarily ugly. Multi-line lambdas have been rejected because of this very problem, so unless you have a clean solution, I think your proposal falls into the category of "would be nice, but not in Python." Cheers, Cliff From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 3 05:17:19 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 03 Sep 2007 11:17:19 +0200 Subject: TypeError: 'module object is not callable' In-Reply-To: References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> Message-ID: <46dbd11e$0$6228$426a74cc@news.free.fr> Amit Khemka a ?crit : (snip) > The exception is being raised as you are being confused about the > names ie: you have a class named "Step" in a module named "Step.py" . Actually, the module is named 'Step', not 'Setp.py' !-) From shankarjee at gmail.com Wed Sep 19 13:10:32 2007 From: shankarjee at gmail.com (Shankarjee Krishnamoorthi) Date: Wed, 19 Sep 2007 12:10:32 -0500 Subject: Embedding a executable inside Python Script In-Reply-To: <13f2la0dq3gm0bf@corp.supernews.com> References: <13f2la0dq3gm0bf@corp.supernews.com> Message-ID: I missed the obvious fact there. Thanks. I added it to the PATH and that fixed everything. Shankarjee On 9/19/07, Grant Edwards wrote: > On 2007-09-19, Shankarjee Krishnamoorthi wrote: > > > I have a exe made with py2exe for my Python routine. The issue > > I am running into is this. All the exes (mycode.exe and > > other_executable.exe) are placed in a Network drive(Say I:) so > > that people can access it. > > > > When the user calls this from a Local Drice(Say C:) The output is like this > > C:> I:\mycode.exe input_file other_executable_file.exe is not found..... > > The problem is that 'other_executable.exe' isn't in a directory > that's on the current PATH. > > > Is there any way where I can circumvent this. Thanks > > Either set the PATH environment variable to include the > directory where other_executable.exe is located or specify the > complete path to other_executable.exe in your os.system() call. > > -- > Grant Edwards grante Yow! I hope the > at ``Eurythmics'' practice > visi.com birth control ... > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Sun Sep 30 20:37:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Sep 2007 21:37:06 -0300 Subject: Command-line does work when scheduled References: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> <1191104269.578536.56470@g4g2000hsf.googlegroups.com> <1191114246.668635.327080@o80g2000hse.googlegroups.com> <1191163376.067339.34740@d55g2000hsg.googlegroups.com> Message-ID: En Sun, 30 Sep 2007 11:42:56 -0300, Jim escribi?: > On Sep 29, 8:45 pm, "Gabriel Genellina" > wrote: >> The %* at the end is important: if you created the association by using >> "Open with...", or selecting Python from the list of installed programs, >> very likely the command says only "%1" - that is, the script being open, >> but without any additional arguments. > I believe I get the correct results as follows: > ============================================== > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > J:\Jim Crerar\mypython\misc>assoc .py > .py=Python.File > > J:\Jim Crerar\mypython\misc>ftype Python.File > Python.File="E:\Python25\python.exe" "%1" %* > > J:\Jim Crerar\mypython\misc> > =============================================== > What else could be wrong? No more ideas... I think the scheduler just executes the command line, and if it works in a console, should work in the scheduler too... Unless you execute the job under another user, who has a different association for .py files, that's the only reason I can think of. -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 24 05:45:43 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 24 Sep 2007 11:45:43 +0200 Subject: about __str__ In-Reply-To: References: <46f37540$0$16854$426a74cc@news.free.fr> Message-ID: <46f78734$0$8901$426a74cc@news.free.fr> Mikael Olofsson a ?crit : > Bruno Desthuilliers wrote: >> def __str__(self): >> return "<%s:%s>" % (self.commiterID_, self.commits_) > > I would write that in the following way: > > def __str__(self): > return "<%(commiterID_)s:%(commits_)s>" % self.__dict__ > > More explicit IMHO. And easier to maintain, especially if the string > would contain several insertions. Agreed. Well, at least until you want to access something that's not in the instance's __dict__ !-) From xcarma at gmail.com Sat Sep 15 10:15:06 2007 From: xcarma at gmail.com (xcarma at gmail.com) Date: Sat, 15 Sep 2007 14:15:06 -0000 Subject: DDE error Poke Failed Message-ID: <1189865706.655384.272470@y42g2000hsy.googlegroups.com> Hi First of all I am a beginner with python and I am a bit fooling around to check wich possibilities I have. I'm trying to get some data to an internal developped application. Server: DDE Topic: SCSDDeServer Item: SendCustomerData Item data: value, value, value I got the following code import win32ui, dde server = dde.CreateServer() server.Create("test") conversation = dde.CreateConversation(server) conversation.ConnectTo("SCS","SCSDDeServer") conversation.Poke('"SendCustomerData", "S1234567,,"') When I run this I get Traceback (most recent call last): File "U:\python\scs.py", line 6, in conversation.Poke('"SendCustomerData", "S1234567"') error: Poke failed Am I doing anything wrong? Or is it possible that the SCS application only accepts pokes from a specific program? Regards Maarten From apardon at forel.vub.ac.be Thu Sep 13 03:06:45 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Sep 2007 07:06:45 GMT Subject: An ordered dictionary for the Python library? References: <1189582425.329676.215730@r29g2000hsg.googlegroups.com> <13efnmi4n959a59@corp.supernews.com> <1189601205.503841.327170@o80g2000hse.googlegroups.com> <1189605250.186948.303130@50g2000hsm.googlegroups.com> Message-ID: On 2007-09-12, Mark Summerfield wrote: > On 12 Sep, 13:46, Michele Simionato > wrote: >> On Sep 12, 2:42 pm, Steven D'Aprano > >> cybersource.com.au> wrote: >> > On Wed, 12 Sep 2007 07:33:45 +0000, Mark Summerfield wrote: >> > In fact, I'm not sure what people mean by ordered dicts. I assume they >> > mean the keys are ordered, not the values. But ordered by what? Insertion >> > order? Modification order? Alphabetical order? >> >> Insertion order. >> >> M.S. > > > Actually I meant by key order, so insertion order doesn't matter at > all. If you need a dictionary-like data structure that respects > insertion order you could use a list of (key, value) tuples. If you want a dictionary that iterates over his keys and does so in a sorted manner you probably want a tree. One posible implemenation can be found here: http://www.pardon-sleeuwaegen.be/antoon/avltree.html I hope it is usefull to you. -- Antoon Pardon From f.guerrieri at gmail.com Sun Sep 30 11:48:25 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Sun, 30 Sep 2007 17:48:25 +0200 Subject: s.split() on multiple separators In-Reply-To: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> References: <1191160394.870241.171200@w3g2000hsg.googlegroups.com> Message-ID: <79b79e730709300848u58ddd797nfb434d2f5de7c862@mail.gmail.com> On 9/30/07, mrkafk at gmail.com wrote: > Hello everyone, > > OK, so I want to split a string c into words using several different > separators from a list (dels). Have a look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303342 which contains several ways to solve the problem. You could both translate all your separators to a single one, and then split over it, or (maybe the simpler solution) going for the list comprehension solution. francesco From steven.bethard at gmail.com Fri Sep 28 19:42:49 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Sep 2007 17:42:49 -0600 Subject: Can I overload the compare (cmp()) function for a Lists ([]) index function? In-Reply-To: <1191002767.350147.153910@57g2000hsv.googlegroups.com> References: <1191000652.430036.288400@y42g2000hsy.googlegroups.com> <1191002767.350147.153910@57g2000hsv.googlegroups.com> Message-ID: irstas at gmail.com wrote: > On Sep 28, 8:30 pm, xkenneth wrote: >> Looking to do something similair. I'm working with alot of timestamps >> and if they're within a couple seconds I need them to be indexed and >> removed from a list. >> Is there any possible way to index with a custom cmp() function? >> >> I assume it would be something like... >> >> list.index(something,mycmp) >> >> Thanks! > > Wouldn't it be enough to get the items that are "within a couple of > seconds" out of the list and into another list. Then you can process > the other list however you want. Like this: > > def isNew(x): > return x < 5 > > data = range(20) > print data > out, data = filter(isNew, data), filter(lambda x: not isNew(x), data) > print out, data Slightly off topic here, but these uses of filter will be slower than the list comprehension equivalents:: out = [x for x in data if x < 5] data = [x for x in data if x >= 5] Here are sample timings:: $ python -m timeit -s "data = range(20)" -s "def is_new(x): return x < 5" "filter(is_new, data)" 100000 loops, best of 3: 5.05 usec per loop $ python -m timeit -s "data = range(20)" "[x for x in data if x < 5]" 100000 loops, best of 3: 2.15 usec per loop Functions like filter() and map() are really only more efficient when you have an existing C-coded function, like ``map(str, items)``. Of course, if the filter() code is clearer to you, feel free to use it, but I find that most folks find list comprehensions easier to read than map() and filter() code. STeVe From ratchetgrid at googlemail.com Sun Sep 16 19:14:37 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Mon, 17 Sep 2007 00:14:37 +0100 Subject: adding a static class to another class Message-ID: <676224240709161614i2c418bf0s550728e611ca79d1@mail.gmail.com> HI, I m trying to start an api in a similar way to the djangic way of Class.objects.all(). Ie objects is a "Manager" class. So: class Foo(object): def __init__(self): self.test = "NEE" class Manager(object): def __init__(self): pass def all(self): return "COCONUTS" Because of how some of the code is set up I cant use metaclasses........so I try to use a decorator: def addto(instance): def decorator(f): import new f = new.instancemethod(f, instance, instance.__class__) setattr(instance, "objects", f) return f return decorator class Manager(object): @addto(Foo) def __init__(self): ............. however this only binds the init method to the Foo.objects, so not what I want. If I try using classmethod...then it just says the Foo.objects doesnt exist. Does anyone have any ideas how I can accomplish this using decorators? And also preventing more than one Manager instance instantiated at one time. Many Thanks in advance, Nathan From bulliver at badcomputer.org Fri Sep 7 13:58:35 2007 From: bulliver at badcomputer.org (darren kirby) Date: Fri, 07 Sep 2007 11:58:35 -0600 Subject: passing command line arguments In-Reply-To: <93066C069973ED448DC2BCEA9C44A7383BE32D@efmailx> References: <93066C069973ED448DC2BCEA9C44A7383BE32D@efmailx> Message-ID: <200709071158.35779.bulliver@badcomputer.org> quoth the Brian McCann: > Hi, > > when I run the script show_args2.py > > # ./show_args2.py 1 2 3 > > I get the following error > > Traceback (most recent call last): > File "./show_args2.py", line 4, in ? > print 'The arguments of %s are "%s"' %s \ > NameError: name 's' is not defined > > > ##################################### > > this is the script > #!/usr/bin/python > import sys, string > print 'The arguments of %s are "%s"' %s \ > (sys.argv[0], string.join(sys.argv[1:])) You don't want the 's' on the last format operator. Try: print 'The arguments of %s are "%s"' % \ (sys.argv[0], string.join(sys.argv[1:])) > any help would be greatly appreciated > > -Brian -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 From gagsl-py2 at yahoo.com.ar Fri Sep 28 21:24:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Sep 2007 22:24:29 -0300 Subject: Emailing the attachment created with the Quick Screenshots Script(Python + PIL) References: <000001c801e8$1eb8ff20$eafca8c0@tfccorp.intra> Message-ID: En Fri, 28 Sep 2007 12:56:18 -0300, Mark Bratcher escribi?: > The quick screenshots script works great for the project I'm working on > and > I'm trying to modify it to include emailing the JPG file it generates. I > retrieved both scripts from the Python Archives. The modified script is > pasted below and the errors below that. My goal is to have the latest > date > stamped file emailed to me. > editorstring='"start"%s" "%s"'% (ImageEditorPath,saveas) #Just for > Windows > right now? Do you really want to open the image with MSPaint? If not, remove the above line and the os.system call (it's wrong, anyway...) > # me == the sender's email address > > # family = the list of all recipients' email addresses > > msg['From'] = ("Mark Bratcher") > > msg['To'] = COMMASPACE.join("Mark Bratcher") Ouch... Try printing msg['To'] (before correcting anything) and see what happens :) msg['From'] = "your at email.address" msg['To'] = "the.destination at email.address" They might be the same address. That COMMASPACE.join was to account for multiple recipients - just ignore it for now. > for file in "c:\downloads\python\Attachments\*.jpg": a) This `for` iterates over all the LETTERS on c:\downloads... b) The path should be written r"c:\downloads..." as seen on the first lines on your script c) Don't you want a SINGLE jpg? Why iterate over all ones? You already know the filename, it's the `saveas` variable above. Replace the whole for loop with: # Open the files in binary mode. Let the MIMEImage class automatically fp = open(saveas, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) > # Send the email via our own SMTP server. > s = smtplib.SMTP() Above, you may need to provide details about your SMTP, like SMTP("mail.cclpcitrus.com") > s.connect() > s.sendmail(me, family, msg.as_string()) > s.close() me? family? Try with: s.sendmail(msg['From'], msg['To'], msg.as_string()) Good luck! -- Gabriel Genellina From jstroud at mbi.ucla.edu Wed Sep 5 16:37:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 05 Sep 2007 13:37:37 -0700 Subject: concise code (beginner) In-Reply-To: <1189020188.842700.50950@d55g2000hsg.googlegroups.com> References: <13dsvqrqivtf092@corp.supernews.com> <1189020188.842700.50950@d55g2000hsg.googlegroups.com> Message-ID: Karthik Gurusamy wrote: > On Sep 5, 11:17 am, James Stroud wrote: >> >> for i in xrange(number_of_reads): >> for dev in devs: >> try: >> _reader = getattr(dev, 'read%d' % i) >> _reader() >> except Exception, e: >> print e >> devs.remove(dev) > > I see in many of the solutions suggested above, the devs sequence/ > iterator is being modified while iterating. I know it is not defined > for interation over dictionary keys. Are they defined for other > collections like lists? Good eye! My code is broke as you have noticed: py> r = range(5) py> for i in r: ... print i ... if i % 2: ... r.remove(i) ... 0 1 3 For longer sequences, the algorithm I've used in these cases in the past goes something like this: py> r = range(10, 17) py> print r [10, 11, 12, 13, 14, 15, 16] py> py> i = 0 py> while i < len(r): ... j = r[i] ... print j ... if j % 2: ... r.remove(j) ... else: ... i += 1 ... 10 11 12 13 14 15 16 py> print r [10, 12, 14, 16] Which would change my problematic code above to: for i in xrange(number_of_reads): j = 0 while j < len(devs): try: _reader = getattr(devs[j], 'read%d' % i) _reader() j += 1 except Exception, e: print e devs.remove(dev) Another way is to make a copy of devs, if devs is short, which makes my problematic code into a matter of a "typo"--maybe I can make this claim to save some face? for i in xrange(number_of_reads): for dev in devs[:]: try: _reader = getattr(dev, 'read%d' % i) _reader() except Exception, e: print e devs.remove(dev) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steve at holdenweb.com Tue Sep 11 08:08:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Sep 2007 08:08:07 -0400 Subject: anybody has py modules emulating symbian 60 on PC? In-Reply-To: <005f01c7f41d$cb9cfa80$4de1a8c0@amd.com> References: <005f01c7f41d$cb9cfa80$4de1a8c0@amd.com> Message-ID: Ginger wrote: > like appuifw/graphics/sysinfo modules, > i've get some primary modules of these, they do what they did on S60 platform. u can get them from http://pdis.hiit.fi/pdis/ > but these modules i get are rather simple ones, and a full emulation is needed ..., so anyone who has it, plz send me a copy, with my appreciation. > http://archive.devx.com/wireless/vendordocs/nokia.asp might help. Or it might not. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From __peter__ at web.de Thu Sep 13 04:34:17 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Sep 2007 10:34:17 +0200 Subject: cannot declare global vars! References: Message-ID: Konstantinos Pachopoulos wrote: > i had posted earlier for not being able to declare global vars. No i Post a followup in that thread then rather than starting a new one. > followed the suggestions and created a class, but still the vars do not > seem to have a global scope. I have tried pretty much everything. Any > advice appreciated... Here: [snip mess] What Guillaume C. meant is: To make a variable that is assigned within a function global you have to declare it global def foo(): global x x = 42 foo() print x but that having many of these globals is a bad design and you should use instance attributes instead: class A(object): def foo(self): self.x = 42 a = A() a.foo() print a.x Personally, I often prefer def foo(): return 42 x = foo() print x which is both explicit and concise. These are basic considerations in Python, so I suggest that you read an introductory text on the language before you proceed with your endeavours. Peter From steve at holdenweb.com Thu Sep 6 07:50:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Sep 2007 04:50:15 -0700 Subject: SQLite and coercing to Unicode - please help. In-Reply-To: <46dfdd18$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> References: <46dfcbea$0$89178$7b0f0fd3@mistral.news.newnet.co.uk> <46dfdd18$0$89254$7b0f0fd3@mistral.news.newnet.co.uk> Message-ID: special_dragonfly wrote: > That helped immensely Steve thank you. You're right, this is my first really > big project ever really, not just in Python. > Just to clarify, my UPDATE statement instead of looking like this: > > longstring="UPDATE SecB SET > currencyCode='"+Values[1]+"',issuerName='"+Values[2] > "',instrName='"+Values[3]+\ > "',instrShortName='"+Values[4]+"',instrType='"+Values[5]+"',secCode='"+Values[6]+\ > "',SEDOL='"+Values[7]+"',Date='"+Values[8]+"',SuspendedState='"+Values[9]+\ > "',bidPrice='"+Values[10]+"',offerPrice='"+Values[11]+"',midPrice='"+Values[12]+\ > "',standardMarketSize='"+Values[13]+"',openOrClosed='"+Values[14]+\ > "' WHERE secBoardId='"+Values[0]+"'" > cursor.execute(longstring) > > should instead look more like this: > cursor.execute('UPDATE SecB SET > (?,?,?,?,?,?,?,?,?,?,?,?,?,?)',tuple(Values[1:])) ? > Closer. It really needs to be more like cursor.execute("""UPDATE SecB SET currencyCode=?, issuerName=?, instrName=?, ... openOrClosed=? WHERE secBoardId=?""", data) In this case, since the secBoardID is used as the last parameter, data really needs to be se at data = tuple(Values[1:] + Values[:1]) But of course it would probably be easier to assemble Values in the right order in the first place. You will still need to turn it into a tuple, however, for cursor.execute(). > The Elements list was from a time when it looked less pretty than it does > now, where I iterated through it and didn't catch errors at all. > > Thank you again for your help and when it's finished and working I'll repost > it online somewhere for ideas on how to optimise it slightly more! > Dominic > Good one! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From jeff at jmcneil.net Thu Sep 20 11:30:03 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 20 Sep 2007 11:30:03 -0400 Subject: Python-list Digest, Vol 48, Issue 301 In-Reply-To: <200709201724.23611.cscheit@lstm.uni-erlangen.de> References: <200709201724.23611.cscheit@lstm.uni-erlangen.de> Message-ID: <82d28c40709200830o45b8079ey73227c07d97d6cd6@mail.gmail.com> Zip do what you want? Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> l1 = [1,2,3,4,5] >>> l2 = ['a', 'b', 'c', 'd', 'e'] >>> for i,j in zip(l1, l2): ... print i,j ... 1 a 2 b 3 c 4 d 5 e >>> You can also do the same thing using itertools.izip, but it will return an iterator as opposed to building a new list. -Jeff On 9/20/07, Christoph Scheit wrote: > Hello, > > is there a way to do something like > for i,j in l1, l2: > print i,j > > ? > Thanks in advance, > Chris > > -- > > ============================ > M.Sc. Christoph Scheit > Institute of Fluid Mechanics > FAU Erlangen-Nuremberg > Cauerstrasse 4 > D-91058 Erlangen > Phone: +49 9131 85 29508 > ============================ > -- > http://mail.python.org/mailman/listinfo/python-list > From dion at richland.k12.la.us Sun Sep 23 23:04:18 2007 From: dion at richland.k12.la.us (dion at richland.k12.la.us) Date: Mon, 24 Sep 2007 04:04:18 +0100 Subject: here is the weekend report, please review it. Message-ID: <46F72932.6080401@hotmail.com> News Expected Monday From SREA SCORE ONE INC (S R E A) $0.1 Last time we saw news from SREA it rocketed. Don't let it get away, get all over SREA first thing Mon. From jcd at sdf.lonestar.org Sun Sep 16 21:59:53 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Sun, 16 Sep 2007 21:59:53 -0400 Subject: Try this In-Reply-To: <1189990689.259451.232570@g4g2000hsf.googlegroups.com> References: <1189932394.353862.201750@g4g2000hsf.googlegroups.com> <13eqsdfsfvsa16f@corp.supernews.com> <1189969529.652871.19280@50g2000hsm.googlegroups.com> <1189979679.969074.216490@y42g2000hsy.googlegroups.com> <1189981681.745195.18130@y42g2000hsy.googlegroups.com> <1189983233.709832.124290@19g2000hsx.googlegroups.com> <1189984913.956999.163100@n39g2000hsh.googlegroups.com> <1189990689.259451.232570@g4g2000hsf.googlegroups.com> Message-ID: <46EDDF99.1090407@sdf.lonestar.org> mensanator at aol.com wrote: > The very presence of an algorithm to detect encoding is a bug. > Files with they .txt extension should always be treated as ANSI > even if they contain binary data. Notepad should never be > allowed to try to decide what the encoding is if the the open > dialog has the encoding set to ANSI. > > Mmmmm, yeah.... I'm going to have to go ahead and, uh, disagree with you there. If I open a text file in WordPad, and then do a save as, I get the following choices, all specifying an extension of .txt Text Document Text Document - MS-DOS Format Unicode Document If Microsoft offers to create documents in three different formats with the same extension, it damn well better make some effort to figure out which one it's trying to open when it reopens those same documents. Cheers, Cliff From jscrerar at compuserve.com Sat Sep 29 21:04:06 2007 From: jscrerar at compuserve.com (Jim) Date: Sat, 29 Sep 2007 18:04:06 -0700 Subject: Command-line does work when scheduled In-Reply-To: References: <1191098074.342460.52130@n39g2000hsh.googlegroups.com> <1191104269.578536.56470@g4g2000hsf.googlegroups.com> Message-ID: <1191114246.668635.327080@o80g2000hse.googlegroups.com> On Sep 29, 6:56 pm, "Gabriel Genellina" wrote: > En Sat, 29 Sep 2007 19:17:49 -0300, Jim escribi?: > > > > > > > On Sep 29, 3:19 pm, "Gabriel Genellina" > > wrote: > >> En Sat, 29 Sep 2007 17:34:34 -0300, Jim > >> escribi?: > > >> > I want to schedule a Python program that reads the command line for > >> > input. However, when adding an argument to the command line Python > >> > will not pick it up when using Windows scheduled tasks. > > >> > How do I get it to work? > > >> Do you write the command line when defining the task? Using double > >> quotes > >> around arguments with spaces? > >> It works fine for me. > > > I ran the following on the Scheduled Tasks: > > "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py" n > > "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py n" > > "J:\Jim Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py" "n" > > None of them work. > > However, no problem with running from *.bat file or directly from > > shortcut on my Desktop. > > Try prepending the Python executable: > > C:\Python25\Python.exe "J:\Jim > Crerar\MyPython\Zero_OE_Counter\Zero_OE_Counter.py" n > > If it works this way, maybe the .py file extension is not correctly > registered. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - Yes, it works this way. How do I register the .py extension correctly? Thanks, Jim From dickinsm at gmail.com Sun Sep 2 13:42:23 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 02 Sep 2007 17:42:23 -0000 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers In-Reply-To: <1i3t4ha.1r0xx7414w0taxN%aleax@mac.com> References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188742231.470668.29910@g4g2000hsf.googlegroups.com> <1i3t4ha.1r0xx7414w0taxN%aleax@mac.com> Message-ID: <1188754943.512850.158320@y42g2000hsy.googlegroups.com> On Sep 2, 12:55 pm, al... at mac.com (Alex Martelli) wrote: > Mark Dickinson wrote: > > Well, for one thing, you're creating half a million xrange objects in > > the course of the search. All the C code has > > to do is increment a few integers. > > I don't think the creation of xrange objects is a meaningful part of > Python's execution time here. Consider: > [...] Agreed---I just came to the same conclusion after doing some tests. So maybe it's the billion or so integer objects being created that dominate the running time? (Not sure how many integer objects actually are created here: doesn't Python cache *some* small integers?) Mark From joemystery123 at gmail.com Fri Sep 21 08:42:34 2007 From: joemystery123 at gmail.com (crybaby) Date: Fri, 21 Sep 2007 05:42:34 -0700 Subject: newb: BeautifulSoup In-Reply-To: <1190360304.800016.219320@k79g2000hse.googlegroups.com> References: <1190343890.375836.78630@r29g2000hsg.googlegroups.com> <1190360304.800016.219320@k79g2000hse.googlegroups.com> Message-ID: <1190378554.524052.220750@22g2000hsm.googlegroups.com> I added extra td tags to your example, for whatever reason I am getting None. When I do the following: print all_tds[0].string print all_tds[8].string from BeautifulSoup import BeautifulSoup doc = """
hello
worldgoodbye
|  48.884  |  49.950  |  69.322  |  99.740  |
""" soup = BeautifulSoup(doc) tables = soup.findAll('table') target_table = tables[1] all_tds = target_table.findAll('td') print all_tds[0].string print all_tds[8].string tds_str = all_tds[8].string print tds_str Output I am getting is following: >>> hello None None I am not sure why I am getting None for these lines: print all_tds[0].string print all_tds[8].string On Sep 21, 3:38 am, 7stud wrote: > On Sep 20, 9:04 pm, crybaby wrote: > > > I need to traverse a html page with big table that has many row and > > columns. For example, how to go 35th td tag and do regex to retireve > > the content. After that is done, you move down to 15th td tag from > > 35th tag (35+15) and do regex to retrieve the content? > > 1) You can find your table using one of these methods: > > a) > target_table = soup.find('table', id='car_parts') > > b) > tables = soup.findall('table') > target_table = tables[2] > > The tables are put in a list in the order that they appear on the > page. > > 2) You can get all the td's in the table using this statement: > > all_tds = target_table.findall('td') > > 3) You can get the contents of the tags using these statements: > > print all_tds[34].string > print all_tds[49].string > > Here is an example: > > from BeautifulSoup import BeautifulSoup > > doc = """ > > > > > > >
> > > > >
hello
worldgoodbye
> > > """ > > soup = BeautifulSoup(doc) > > tables = soup.findAll('table') > target_table = tables[1] > > all_tds = target_table.findAll('td') > print all_tds[0].string > print all_tds[2].string > > --output:-- > hello > goddbye From thorsten at thorstenkampe.de Mon Sep 3 14:45:58 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 3 Sep 2007 19:45:58 +0100 Subject: list index() References: <1188456273.102334.48660@50g2000hsm.googlegroups.com> <87hcmhebwv.fsf@benfinney.id.au> <5jn9qgFdmbcU3@mid.uni-berlin.de> Message-ID: * Terry Reedy (Fri, 31 Aug 2007 02:28:36 -0400) > "Marc 'BlackJack' Rintsch" wrote in message > news:5jn9qgFdmbcU3 at mid.uni-berlin.de... > | On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote: > | > zzbbaadd at aol.com writes: > | >> What's with the index() function of lists throwing an exception on not > | >> found? > | > > | > It's letting you know that the item isn't in the list. There's no > | > sensible return value from an "index" function in that condition. > | > | What about -1? C programmers do this all the time. :-) > > Because they do not have exceptions. They have plenty of - but they can't catch them :) Thorsten From bjorn.kempen at gmail.com Sat Sep 15 17:17:50 2007 From: bjorn.kempen at gmail.com (buffi) Date: Sat, 15 Sep 2007 21:17:50 -0000 Subject: how could change backcolor of console? In-Reply-To: References: Message-ID: <1189891070.245458.49100@r29g2000hsg.googlegroups.com> On Sep 15, 3:55 pm, wan... at 126.com wrote: > Hi,everyone: I am a c programmer,and want using Python instead of C > I can change backcolor using C,like this: > > textbackground(color); > > How can I do in Python? > > Best regards > > ? ? ? ??? ? ? ? 07 ? ? ? ? ? ? ? ? ? ? ? textbackground() is not part of the C programming language but rather a part of an rather old module for msdos. http://en.wikipedia.org/wiki/Conio.h If you want terminal colors in python you can use the curses module but I doubt that it will work in windows. http://docs.python.org/lib/module-curses.html From ldo at geek-central.gen.new_zealand Fri Sep 7 04:12:35 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 07 Sep 2007 20:12:35 +1200 Subject: Getting original working directory References: <1658.1882-17889-1055570935-1189104422@seznam.cz> Message-ID: In message , Steve Holden wrote: > Python runs as a sub-process. The parent process (the one that started > Python) contains the working directory that the Python interpreter > inherited from it. But you can't expect to just go poking around inside > the environment of your parent process... Under Linux: os.readlink("/proc/%d/cwd" % os.getppid()) From bignose+hates-spam at benfinney.id.au Wed Sep 12 22:20:41 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 13 Sep 2007 12:20:41 +1000 Subject: Python 3K or Python 2.9? References: <1189567628.877156.27620@g4g2000hsf.googlegroups.com> <46e7974d$0$31726$426a74cc@news.free.fr> <5kq1hgF4r90oU1@mid.individual.net> <1189618530.872819.136450@57g2000hsv.googlegroups.com> <1189619033.968437.286580@g4g2000hsf.googlegroups.com> <5kr8vlF53m8gU3@mid.individual.net> <1189643616.826715.58150@d55g2000hsg.googlegroups.com> <87sl5j5r34.fsf@benfinney.id.au> <1189646281.569796.267940@d55g2000hsg.googlegroups.com> Message-ID: <87ir6f5mrq.fsf@benfinney.id.au> TheFlyingDutchman writes: > I would mention that an instance is passed as the first parameter > argument of a method if the methods were declared with the extra > argument and called with the extra argument: > > a = MyClass() > > my_method(a,someParameter) Are you unaware that this is the way it works already? >>> class Foo(object): ... def bar(self, baz): ... print baz ... >>> foo = Foo() >>> Foo.bar("spam") Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method bar() must be called with Foo instance as first argument (got str instance instead) >>> Foo.bar(foo, "spam") spam >>> foo.bar("spam") spam The latter two statements are equivalent. The 'instance.method(args)' syntax is just sugar for 'Class.method(instance, args)'. -- \ "Choose mnemonic identifiers. If you can't remember what | `\ mnemonic means, you've got a problem." -- Larry Wall | _o__) | Ben Finney From gagsl-py2 at yahoo.com.ar Fri Sep 14 23:50:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Sep 2007 00:50:50 -0300 Subject: reading xls file from python References: <21903009.66741189806994236.JavaMail.www@wwinf4602> Message-ID: En Fri, 14 Sep 2007 18:56:34 -0300, escribi?: > I have installed python 2.5 for windows in my pc, I have a file xls say > "file.xls" in c:/python25. How I can read this files from Python. Many > thanks in advance. Try xlrd: http://www.python.org/pypi/xlrd -- Gabriel Genellina From mensanator at aol.com Thu Sep 20 19:13:35 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 20 Sep 2007 16:13:35 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: <1190328413.226577.206740@k79g2000hse.googlegroups.com> References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> Message-ID: <1190330015.131971.265680@y42g2000hsy.googlegroups.com> On Sep 20, 5:46 pm, Paul Hankin wrote: > On Sep 20, 10:59 pm, Python Maniac wrote: > > > I am new to Python however I would like some feedback from those who > > know more about Python than I do at this time. > > > def scrambleLine(line): > > s = '' > > for c in line: > > s += chr(ord(c) | 0x80) > > return s > > > def descrambleLine(line): > > s = '' > > for c in line: > > s += chr(ord(c) & 0x7f) > > return s > > ... > > Well, scrambleLine will remove line-endings, so when you're > descrambling > you'll be processing the entire file at once. This is particularly bad > because of the way your functions work, adding a character at a time > to > s. > > Probably your easiest bet is to iterate over the file using read(N) > for some small N rather than doing a line at a time. Something like: > > process_bytes = (descrambleLine, scrambleLine)[action] > while 1: > r = f.read(16) > if not r: break > ff.write(process_bytes(r)) > > In general, rather than building strings by starting with an empty > string and repeatedly adding to it, you should use ''.join(...) > > For instance... > def descrambleLine(line): > return ''.join(chr(ord(c) & 0x7f) for c in line) > > def scrambleLine(line): > return ''.join(chr(ord(c) | 0x80) for c in line) > > It's less code, more readable and faster! I would have thought that also from what I've heard here. def scrambleLine(line): s = '' for c in line: s += chr(ord(c) | 0x80) return s def scrambleLine1(line): return ''.join([chr(ord(c) | 0x80) for c in line]) if __name__=='__main__': from timeit import Timer t = Timer("scrambleLine('abcdefghijklmnopqrstuvwxyz')", "from __main__ import scrambleLine") print t.timeit() ## scrambleLine ## 13.0013366039 ## 12.9461998318 ## ## scrambleLine1 ## 14.4514098748 ## 14.3594400695 How come it's not? Then I noticed you don't have brackets in the join statement. So I tried without them and got ## 17.6010847978 ## 17.6111472418 Am I doing something wrong? > > -- > Paul Hankin From zzbbaadd at aol.com Mon Sep 10 08:07:47 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 10 Sep 2007 05:07:47 -0700 Subject: Python syntax wart In-Reply-To: <1189405211.875217.176620@57g2000hsv.googlegroups.com> References: <1189405211.875217.176620@57g2000hsv.googlegroups.com> Message-ID: <1189426067.777376.106470@r34g2000hsd.googlegroups.com> On Sep 9, 11:20 pm, TheFlyingDutchman wrote: > It may be that a language that doesn't have a statement terminator > (which can be end-of-line) needs a statement continuation symbol. > (Excluding languages like Lisp that have parentheses everywhere). Actually I guess Python does have a statement terminator - end-of- line. If you use end-of-line as your statement terminator it is difficult and maybe impossible to avoid a line-continuation character in those situations where you don't want an end-of-line to terminate your statement. From joshua at eeinternet.com Wed Sep 19 16:58:15 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 19 Sep 2007 12:58:15 -0800 Subject: A struct for 2.4 that supports float's inf and nan? Message-ID: I'm trying to put some values into a struct. Some of these values are NaN and Inf due to the nature of the data. As you well may know, struct (and other things) in Python <= 2.4 doesn't support inf and nan float values. You get the dreaded "SystemError: frexp() result out of range" error. Before I go and write my own little wrapper, has anyone out there written an "extended" struct that supports the inf and nan values? I know this is fixed in 2.5, but using that isn't an option at this point, as users will be running older versions of python. I suppose I could get the relevant source from the 2.5 source and compile it as a custom package, but that wouldn't be very transparent for my users, and would probably be getting in way over my head. :) Ideas? Suggestions? j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From grante at visi.com Thu Sep 6 22:31:54 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Sep 2007 02:31:54 -0000 Subject: why should I learn python References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> <1189117798.506367.278560@y42g2000hsy.googlegroups.com> <1189118200.040934.151520@57g2000hsv.googlegroups.com> Message-ID: <13e1e0qmc5o4v79@corp.supernews.com> On 2007-09-06, Andr? wrote: > On Sep 6, 7:29 pm, windandwaves wrote: >> On Sep 7, 9:50 am, James Stroud wrote: >> >> > Seewww.python.org. Trust us all when we say that its the best. >> >> I get that feeling - yes. Question is: >> >> 1. what is it good for? > > Pretty much any programming task, except perhaps those that require > extreme computation speed (like weather modeling). Even then there are some very powerful numerical and scientific libraries that are _way_ easier to use from Python that they are from C and Fortran (the languages in which such libraries are often written). You gain 99% of the speed with none of the pain. -- Grant Edwards grante Yow! Vote for ME at -- I'm well-tapered, visi.com half-cocked, ill-conceived and TAX-DEFERRED! From bj_666 at gmx.net Sun Sep 9 02:12:39 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Sep 2007 06:12:39 GMT Subject: Python syntax wart References: Message-ID: <5khh6nF3i5nuU1@mid.uni-berlin.de> On Sun, 09 Sep 2007 17:16:05 +1200, Lawrence D'Oliveiro wrote: > The one thing I don't like about Python syntax is using backslashes to > continue lines. Yes, you can avoid them if you can include parentheses > somehow, but this isn't always possible. > > Possible: > > [?] > > Not possible: > > for \ > Link \ > in \ > GetEachRecord \ > ( > "links", > ("from_episode",), > "to_episode = %s", > [EpisodeID], > "order by when_created" > ) \ > : > out.write \ > ( > "

Back to episode %d\n" > % > ( > LinkToMe({"ep" : Link["from_episode"]}), > Link["from_episode"] > ) > ) > #end for What do you mean by not possible!? This compiles fine for me. Ciao, Marc 'BlackJack' Rintsch From mail at microcorp.co.za Sat Sep 1 03:36:48 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 1 Sep 2007 09:36:48 +0200 Subject: Is there a simple way to exit a while loop on keystroke? References: <1188578827.809840.90100@r29g2000hsg.googlegroups.com> Message-ID: <01f301c7ec71$4b989960$03000080@hendrik> "gsxg" wrote: > I am new to python, and have written a simple program to read a port > via telnet. I would like it to run until any key is pressed. Of > course I wouldn't mind requiring a specific keystroke in the future, > but I would think this is simpler for now. > > I have used kbhit() and getch() many times in C, but I can't find > anything similar in Python. I am using Linux also, so the msvcrt > code isn't an option. I have tried sys.stdin.read(), but that hangs > UNTIL a key is pressed. Unblock the stdin using the fcntl module. Then you get an IOError if there is nothing. def unblock(f): """Given file f , sets it unblock flag to true""" fcntl.fcntl(f.fileno(),fcntl.F_SETFL,os.O_NONBLOCK) f is the file object you get from the open... hth - Hendrik From claird at lairds.us Sun Sep 2 11:39:34 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 2 Sep 2007 15:39:34 +0000 Subject: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers References: <1188733902.513512.87510@r34g2000hsd.googlegroups.com> <1188735642.391419.103650@19g2000hsx.googlegroups.com> <1188740716.423349.304370@y42g2000hsy.googlegroups.com> <1188742231.470668.29910@g4g2000hsf.googlegroups.com> Message-ID: In article <1188742231.470668.29910 at g4g2000hsf.googlegroups.com>, Mark Dickinson wrote: >On Sep 2, 9:45 am, jwrweather... at gmail.com wrote: >> [snip code] >> >> Thanks for that. I realise that improving the algorithm will speed >> things up. I wanted to know why my less than perfect algorithm was so >> much slower in python than exactly the same algorithm in C. Even when >> turning off gcc's optimiser with the -O0 flag, the C version is still >> >> > 100 times quicker. > >Well, for one thing, you're creating half a million xrange objects in >the course of the search. All the C code has >to do is increment a few integers. > >Mark > Right: Mr. Dickinson's original question is entirely legitimate, and it's not adequate to respond, as some follow-ups did, with ways to improve the Python-coded algorithm. The correct answer, which I want to reinforce, is that the exhibited Python and C versions are NOT "exactly the same algorithm", at least not without more quali- fication. Part of Python expertise is to recognize that creation of xrange objects, mentioned above, is far from free. Also, -O3 gives C the opportunity, also remarked in a follow-up, to factor calculations outside their loops. From wolf_tracks at invalid.com Fri Sep 21 16:44:19 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 21 Sep 2007 20:44:19 GMT Subject: An Editor that Skips to the End of a Def In-Reply-To: <46f3708c$0$32593$426a74cc@news.free.fr> References: <87odfxjn16.fsf@rudin.co.uk> <87hclpjm3a.fsf@rudin.co.uk> <874phou1pa.fsf@benfinney.id.au> <46f3708c$0$32593$426a74cc@news.free.fr> Message-ID: Well, you may. Unfortunately, there are many NGs that do the opposite. Bruno Desthuilliers wrote: > W. Watson a ?crit : >> How about in the case of MS Win? >> >> Ben Finney wrote: >>> >>> (Please don't top-post. Instead, reply below each point to which >>> you're responding, removing quoted text irrelevant to your response.) >>> > > Wayne, may I second Ben on his suggestion to stop top-posting ? -- Wayne Watson (Nevada City, CA) Web Page: From nagle at animats.com Sat Sep 29 00:09:22 2007 From: nagle at animats.com (John Nagle) Date: Sat, 29 Sep 2007 04:09:22 GMT Subject: Python 3.0 migration plans? In-Reply-To: <1191010125.107578.67700@g4g2000hsf.googlegroups.com> References: <1190942968.920485.311870@g4g2000hsf.googlegroups.com> <%q0Li.725$ih1.539@nlpi068.nbdc.sbc.com> <1i555ag.9ez4uvf4583jN%aleax@mac.com> <1191010125.107578.67700@g4g2000hsf.googlegroups.com> Message-ID: George Sakkis wrote: > On Sep 28, 11:53 am, John Nagle wrote: > >> Alex Martelli wrote: >>> John Nagle wrote: >>>> TheFlyingDutchman wrote: >>>>> It seems that Python 3 is more significant for what it removes than >>>>> what it adds. >>>>> What are the additions that people find the most compelling? >>>> I'd rather see Python 2.5 finished, so it just works. >>> And I'd rather see peace on Earth and goodwill among men than _either_ >>> Python 3 or your cherished "finished" 2.5 -- the comparison and implied >>> tradeoff make about as much sense as yours. >> Insofar as Python has an organization, it's not adequately managing >> extension modules. Each extension module has its own infrastructure, >> with its own build procedures, its own bug list, and its own maintainers. >> There's not even an archive. Unlike CPAN, Cheese Shop is just a directory of >> URLs. >> >> Take a look at how Perl does it. Here are the instructions on >> how to contribute to CPAN: >> >> http://www.cpan.org/modules/04pause.html >> >> There's a way to get your module into the system, a standardized format, >> build, and installation procedure, and an archive which is mirrored. >> There's a common bug reporting system. Modules abandoned by their >> original developers are not lost, and can be "adopted" by someone else. >> >> Python doesn't have any of this. And that's far more of a problem >> than Python 3.x. > > Does Perl support extension modules, and if so, are they so prevalent > as in Python ? Yes, Perl supports non-Perl extension modules. But most of the important ones are either maintained as part of the standard Perl distribution, or supported by the organization that provides whatever they link to. For example, MySQL AB supports a Perl binding to MySQL, but not a Python binding. John Nagle From bronger at physik.rwth-aachen.de Thu Sep 6 18:44:17 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 07 Sep 2007 00:44:17 +0200 Subject: why should I learn python References: <1189114328.695921.230270@d55g2000hsg.googlegroups.com> Message-ID: <87zlzzs9by.fsf@wilson.homeunix.com> Hall?chen! Tom Brown writes: > [...] Python has been by far the easiest to develop in. Some > people might say it is not "real programming" because it is so > easy. I can't believe this. Have you really heard such a statement? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From kyosohma at gmail.com Thu Sep 6 14:05:46 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 06 Sep 2007 18:05:46 -0000 Subject: Finding specific date ranges In-Reply-To: References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> <1189099759.833051.253020@y42g2000hsy.googlegroups.com> Message-ID: <1189101946.318748.99670@y42g2000hsy.googlegroups.com> On Sep 6, 12:41 pm, Tim Golden wrote: > > Thanks! I'll try it both ways and see if there's any appreciable > > difference in speed, although since it will be packaged into an > > executable, that may not be an issue anyway. > > > Mike > > I honestly doubt there's any advantage to my approach, certainly > not in terms of speed. It's really only if it happens to suit > your mind better, or take advantage of structures you might > already have in place, etc. > > TJG For completeness, here's my method for comparison's sake: date_list = [('12/31/2006', '01/13/2007'), ('01/14/2007', '01/27/2007'), ('01/28/2007', '02/10/2007'), ('02/11/2007', '02/24/2007'), ('02/25/2007', '03/10/2007'), ('03/11/2007', '03/24/2007'), ('03/25/2007', '04/07/2007'), ('04/08/2007', '04/21/2007'), ('04/22/2007', '05/05/2007'), ('05/06/2007', '05/19/2007'), ('05/20/2007', '06/02/2007'), ('06/03/2007', '06/16/2007'), ('06/17/2007', '06/30/2007') ] vac_periods = [] found = False for d in date_list: begin = d[0][0:2] end = d[1][0:2] if begin == end and found == False: vac_periods.append(d) found = True else: found = False print vac_periods Isn't it kind of late in the day over there, Tim? Anyway, your method is probably clearer to read whereas mine doesn't require anything to be imported. I didn't even realize there was a calendar module...or maybe I forgot about it. Mike From bkline at rksystems.com Mon Sep 17 16:29:52 2007 From: bkline at rksystems.com (Bob Kline) Date: Mon, 17 Sep 2007 16:29:52 -0400 Subject: Un(der)documented bits of cgi.py In-Reply-To: References: Message-ID: Aahz wrote: > What I suggest doing is submitting a doc patch to > http://bugs.python.org/ Done. Thanks for the suggestion. Bob From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Sep 24 07:09:54 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 24 Sep 2007 13:09:54 +0200 Subject: Would Anonymous Functions Help in Learning Programming/Python? In-Reply-To: <13f8r9sj0b9q94e@corp.supernews.com> References: <1190410638.211343.241690@y42g2000hsy.googlegroups.com> <1190411282.060772.289270@y42g2000hsy.googlegroups.com> <1190412475.772358.109810@n39g2000hsh.googlegroups.com> <13f8r9sj0b9q94e@corp.supernews.com> Message-ID: <46f79aef$0$30457$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 21 Sep 2007 22:07:55 +0000, Cristian wrote: > >> True, there is lambda, but that is very limited. It might be useful for >> key arguments, but not much else. > > No, lambda is useful for anything that any other function is useful for, > provided that you can write it as a single expression and not need to use > statements. Which makes a great difference in practice !-) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Sep 4 10:20:34 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 04 Sep 2007 16:20:34 +0200 Subject: Printing lists in columns In-Reply-To: <1188913394.763871.218660@d55g2000hsg.googlegroups.com> References: <1188809299.316203.85930@22g2000hsm.googlegroups.com> <46dbd11e$0$6228$426a74cc@news.free.fr> <1188816626.021956.281040@22g2000hsm.googlegroups.com> <5k2cjmF1r2aiU1@mid.uni-berlin.de> <1188836008.656284.76160@o80g2000hse.googlegroups.com> <46dc6f49$0$6207$426a34cc@news.free.fr> <1188900397.459760.259580@k79g2000hse.googlegroups.com> <1188906767.737741.267350@19g2000hsx.googlegroups.com> <1188913394.763871.218660@d55g2000hsg.googlegroups.com> Message-ID: <46dd69b1$0$24998$426a74cc@news.free.fr> cjt22 at bath.ac.uk a ?crit : (snip) > Thanks guys > > I have a list of lists such as > a = ["1" , "2"] b = ["4", "5", "6"] c = ["7",8", "9"] > Stored in another list: d = [a,b,c] > > I know this makes me sound very stupid but how would I specify > in the parameter the inner lists without having to write them all out > such as: > > for row in izip_longest(d[0], d[1], d[2], fillvalue='*'): > print ', '.join(row) > > i.e. How could I do the following if I didn't know how many list of > lists I had. for row in izip_longest(*d, fillvalue='*'): print ', '.join(row) HTH From steve at holdenweb.com Wed Sep 26 15:56:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 26 Sep 2007 15:56:07 -0400 Subject: regex with specific list of string In-Reply-To: <1190831706.3397.94.camel@dot.uniqsys.com> References: <1190821357.753909.178210@50g2000hsm.googlegroups.com> <1190827835.3397.76.camel@dot.uniqsys.com> <46FAA145.8050406@decode.com.ar> <1190831706.3397.94.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > On Wed, 2007-09-26 at 15:13 -0300, Pablo Ziliani wrote: >> Carsten Haese wrote: >>> Unfortunately, that also matches margarine, mayonnaise, and octopus, >>> just to name a few ;-) >> (and so does the solution you sent before :) > > No, it doesn't. > >>>> s = set(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', > ... 'sep', 'oct', 'nov', 'dec']) >>>> 'margarine' in s > False >>>> 'mayonnaise' in s > False >>>> 'octopus' in s > False > >> This is fine IMO since the OP didn't specify the opposite. > > True, but my crystal ball tells me that the OP wants exact matches. > (Extrapolating from another post made by the OP earlier today, I'm > guessing he has a list of column names to include in an SQL "order by" > clause, and he wants to check them for validity first.) > Well, as somebody else already pointed out, the OP's query was completely misconceived in the first place, and he would have been better recasting it in a more natural way. However, I am not going to claim that my psychic powers are clearly superior to yours ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline From wolf_tracks at invalid.com Fri Sep 21 08:34:01 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 21 Sep 2007 05:34:01 -0700 Subject: Drawing a 640x480 Raw Image In-Reply-To: <5lh5q2F87tctU1@mid.uni-berlin.de> References: <5lh5q2F87tctU1@mid.uni-berlin.de> Message-ID: Very good. I'll give it a try. Marc 'BlackJack' Rintsch wrote: > On Thu, 20 Sep 2007 20:49:59 -0700, W. Watson wrote: > >> W. Watson wrote: >>> I'm getting a 640x480 greyscale image from a video device. I'd like to >>> place it on a canvas and then draw on the image. Does PIL or some image >>> facility allow me to do that? >> Corrected misspelling in Subject. The image here is nothing more than a >> 640x480 byte array. Each byte is a gra[e]yscale value. > > PIL can do this: > > from PIL import Image > > def main(): > width = 640 > height = 480 > image = Image.new('L', (width, height)) > data = [x * y % 256 for x in xrange(width) for y in xrange(height)] > image.putdata(data) > image.save('test.png') > > `data` can be any iterable with byte values. > > Ciao, > Marc 'BlackJack' Rintsch -- Wayne Watson (Nevada City, CA) Web Page: From hat at se-162.se.wtb.tue.nl Tue Sep 25 05:53:50 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 25 Sep 2007 11:53:50 +0200 Subject: sorteddict PEP proposal [started off as orderedict] References: <1190710402.481693.5110@50g2000hsm.googlegroups.com> Message-ID: On 2007-09-25, Mark Summerfield wrote: > If there is positive feedback I will submit the PEP to the reviewers, > so if you think it is a good idea please say so. (I'm sure that if you > _don't_ like it you'll tell me anyway:-) I like the idea, ie +1. > This PEP proposes the addition of a sorted dictionary class to the > standard library's collections module. You don't seem to mention the sort criterium. I'd suggest to use the __lt__ operator, which you probably intended since it is commonly used. Also, can I specify a custom sort function, as with list.sort() ? > In addition, the keys() method has two optional arguments: > > keys(firstindex : int = None, secondindex : int = None) -> list of Not sure this is a good idea. Wouldn't simply mysorteddict.keys()[firstindex:secondindex] be much better? It can do all you propose, and more (with iterators/generators and such). I see no need to implement it inside the sorteddict as well. > Since the sorteddict's data is always kept in key order, indexes > (integer offsets) into the sorteddict make sense. Five additional > methods are proposed to take advantage of this: > > key(index : int) -> value > > item(index : int) -> (key, value) > > value(index : int) -> key > > set_value(index : int, value) > > delete(index : int) I wouldn't do this. It breaks compability with the normal dict. A beginning user will expect dict and sorteddict to behave the same (except for sortedness), including their set of supporting functions imho. Otherwise, please make a case for them (and maybe even a new PEP to get them in both types of dicts). > Examples > > To keep a collection of filenames on a case-insensitive file > system in > sorted order, we could use code like this: > > files = collections.sorteddict.sorteddict() > for name in os.listdir("."): > files[name.lower()] = name The more interesting case would be to you preserve case of the files within the keys. I usually need this data structure with an A* algorithm implementation, where I need to obtain the cheapest solution found so far. > for item in listOfItems: > itemsByDate["%s\t%17X" % (item.date, id(item))] = item > itemsByName["%s\t%17X" % (item.name, id(item))] = item > itemsBySize["%s\t%17X" % (item.size, id(item))] = item Wouldn't a line like "itemsBySize[(item.size, id(item))] = item" do as well? (or with a custom sort function on items?) > Now we can iterate in date or name order, for example: > > for item in itemsByDate: > print item.name, item.date Hmm, not with dict: >>> for x in {1:10, 2:20}: ... print x ... 1 2 So you should get your "%s\t%17X" strings here. Sincerely, Albert From zzbbaadd at aol.com Mon Sep 10 23:33:48 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Mon, 10 Sep 2007 20:33:48 -0700 Subject: Enum class with ToString functionality In-Reply-To: <87odg99a6p.fsf@benfinney.id.au> References: <1189416537.050002.61120@r34g2000hsd.googlegroups.com> <87bqca9hrw.fsf@benfinney.id.au> <1189472591.797327.189180@w3g2000hsg.googlegroups.com> <87sl5m7xxm.fsf@benfinney.id.au> <1189478288.237609.25140@50g2000hsm.googlegroups.com> <87odg99a6p.fsf@benfinney.id.au> Message-ID: <1189481628.270743.181300@g4g2000hsf.googlegroups.com> On Sep 10, 8:02 pm, Ben Finney wrote: > TheFlyingDutchman writes: > > On Sep 10, 7:12 pm, Ben Finney > > wrote: > > > TheFlyingDutchman writes: > > > > Looking at the documentation it looks excellent. But I don't > > > > understand the 0.4.2 version number, > > > > Note the tag that says the "Development Status" is "Beta". > > > What is the difference between this version and the 1.0 version? > > I don't know yet, since my time machine is currently in for repairs. > > -- > \ "If you ever reach total enlightenment while you're drinking a | > `\ beer, I bet it makes beer shoot out your nose." -- Jack Handey | > _o__) | > Ben Finney When you were developing your Enum module, how did you determine you were at the 0.4.2 version as opposed to the 0.7.1 version or the 0.9.2 version? From timaranz at gmail.com Wed Sep 26 23:16:56 2007 From: timaranz at gmail.com (timaranz at gmail.com) Date: Wed, 26 Sep 2007 20:16:56 -0700 Subject: Using closures and partial functions to eliminate redundant code In-Reply-To: References: Message-ID: <1190863016.582558.139250@r29g2000hsg.googlegroups.com> On Sep 27, 2:01 pm, Matthew Wilson wrote: > I wrote some code to create a user and update a user on a remote box by > sending emails to that remote box. When I was done, I realized that my > create_user function and my update_user function were effectively > identical except for different docstrings and a single different value > inside: > > ### VERSION ONE > > def create_user(username, userpassword, useremail): > "Send an email that will create a user in the remote system." > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject="CREATE", body=email_body) > > def update_user(username, userpassword, useremail): > "Send an email that will update a user's password in the remote system." > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject="UPDATE", body=email_body) > > ### END > > Then I came up with this approach to avoid all that redundant text: > > ### VERSION TWO > > def _f(mode): > > if mode not in ("create", "update"): > raise ValueError("mode must be create or update!") > > def _g(username, userpassword, useremail): > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject=mode.upper(), body=email_body) > > # Seems goofy, but other ways are there? > > docstrings = {'create': "Send an email that will create a user in the remote system.", > 'update': "Send an email that will update a user's password in the remote system."} > > _g.__doc__ = docstrings[mode] > > return _g > > # Then I created my functions like this: > > v2_create_user = _f("create") > v2_update_user = _f("update") > > ### END > > Finally, I came up with this approach: > > ### VERSION THREE > > from functools import partial > > def _h(mode, username, userpassword, useremail): > > if mode not in ("create", "update"): > raise ValueError("mode must be create or update!") > > # Build email > email_body = """ > USERNAME = %s > USERPASSWORD = %s > USEREMAIL = %s > """ % (username, userpassword, useremail) > > # send it. > send_email(subject=mode.upper(), body=email_body) > > # I can't figure out how to set up the docstring on these. > > v3_create_user = partial(_h, mode="create") > v3_update_user = partial(_h, mode="update") > > ### END > > I'm interested to hear how other people deal with really similar code. > The similarity just bugs me. However, I wonder if using stuff like > closures or partial function application is needlessly showy. > > Also, I hope anyone here can help me figure out how to attach a > meaningful docstring for my version three code. > > Thanks in advance! > > Matt Without using partials, I would do something like def _create_or_update_user(mode, username, userpassword, useremail) blah, blah, blah def update_user(username, userpassword, useremail): 'update doc string' return _create_or_update_user('update', username, userpassword, useremail) def create_user(username, userpassword, useremail): 'create doc string' return _create_or_update_user('create', username, userpassword, useremail) Cheers Tim From kyosohma at gmail.com Fri Sep 7 09:32:28 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 07 Sep 2007 13:32:28 -0000 Subject: Finding specific date ranges In-Reply-To: <1189122086.388859.146670@r34g2000hsd.googlegroups.com> References: <1189090603.285778.282060@g4g2000hsf.googlegroups.com> <1189122086.388859.146670@r34g2000hsd.googlegroups.com> Message-ID: <1189171948.864647.83280@57g2000hsv.googlegroups.com> On Sep 6, 6:41 pm, Zentrader wrote: > On Sep 6, 7:56 am, kyoso... at gmail.com wrote: > > > December 31, 2006 January 13, 2007 # doesn't earn > > January 14, 2007 January 27, 2007 # does earn > > January 28, 2007 February 10, 2007 # doesn't > > February 11, 2007 February 24, 2007 # does > > Am I over simplifying if I say that since it appears to be a two week > pay period, the date has to be greater than the 11th unless the first, > or first and second, are on a weekend, in which case it would be > 12 > or > 13? Or a reasonable facsimile thereof, depending on whether or > not the two week period is Saturday through Friday. Yeah it is a 2-week period, but the starting day can change depending on whether or not you're salaried. I haven't even looked at how we handle unions. Ugh. But yes, you are correct. Mike From raychorn at hotmail.com Fri Sep 21 13:00:11 2007 From: raychorn at hotmail.com (Python Maniac) Date: Fri, 21 Sep 2007 10:00:11 -0700 Subject: I could use some help making this Python code run faster using only Python code. In-Reply-To: References: <1190325588.608625.259800@q3g2000prf.googlegroups.com> <1190328413.226577.206740@k79g2000hse.googlegroups.com> <1190330015.131971.265680@y42g2000hsy.googlegroups.com> <1190357165.381313.197910@19g2000hsx.googlegroups.com> Message-ID: <1190394011.148384.106280@q3g2000prf.googlegroups.com> On Sep 21, 12:56 am, Duncan Booth wrote: > George Sakkis wrote: > > It has to do with the input string length; try multiplying it by 10 or > > 100. Below is a more complete benchmark; for largish strings, the imap > > version is the fastest among those using the original algorithm. Of > > course using a lookup table as Diez showed is even faster. FWIW, here > > are some timings (Python 2.5, WinXP): > > > scramble: 1.818 > > scramble_listcomp: 1.492 > > scramble_gencomp: 1.535 > > scramble_map: 1.377 > > scramble_imap: 1.332 > > scramble_dict: 0.817 > > scramble_dict_map: 0.419 > > scramble_dict_imap: 0.410 > > I added another one: > > import string > scramble_translation = string.maketrans(''.join(chr(i) for i in xrange > (256)), ''.join(chr(i|0x80) for i in xrange(256))) > def scramble_translate(line): > return string.translate(line, scramble_translation) > > ... > funcs = [scramble, scramble_listcomp, scramble_gencomp, > scramble_map, scramble_imap, > scramble_dict, scramble_dict_map, scramble_dict_imap, > scramble_translate > ] > > and I think I win: > > scramble: 1.949 > scramble_listcomp: 1.439 > scramble_gencomp: 1.455 > scramble_map: 1.470 > scramble_imap: 1.546 > scramble_dict: 0.914 > scramble_dict_map: 0.415 > scramble_dict_imap: 0.416 > scramble_translate: 0.007 Wow ! Now I am very impressed with Python ! The difference between where I began (70.155 secs) and where we end (2.278 secs) is a whopping 30.8x faster using some rather simple techniques that are nothing more than variations on the theme of hoisting function calls out of loops along with using some very powerful iterator functions from Python. My best runtime with Ruby using the same machine and OS was 67.797 secs which is 29.8x slower than the fastest Python runtime. This makes Ruby almost as slow as Python was made faster. The irony with Ruby was that the use of a hash in Ruby actually made the Ruby code run slower than when a hash was not used. Now I think I will code this little scrambler using nothing but the D Language just to see whether there is any benefit in using D over Python for this sort of problem. From __peter__ at web.de Tue Sep 4 17:06:51 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 4 Sep 2007 23:06:51 +0200 Subject: Undeterministic strxfrm? References: Message-ID: Am Tue, 04 Sep 2007 19:54:57 +0000 schrieb Tuomas: > I get the same unstability with my locale 'fi_FI.utf8' too, so I am > wondering if the source of the problem is the clib or the Python wrapper > around it. Differences in strxfrm results for identical source are > allways in the few latest bytes of the results. Python seems to be the culprit as there is a relatively recent strxfrm-related bugfix, see http://svn.python.org/view/python/trunk/Modules/_localemodule.c?rev=54669 If I understand it correctly the error makes it likely that the resulting string has trailing garbage characters. Peter From sysfault at gmail.com Thu Sep 20 12:22:05 2007 From: sysfault at gmail.com (Anthony Greene) Date: Thu, 20 Sep 2007 12:22:05 -0400 Subject: os.path.getmtime() and compare with a date type In-Reply-To: <1190302285.127448.288010@22g2000hsm.googlegroups.com> References: <1190302285.127448.288010@22g2000hsm.googlegroups.com> Message-ID: <46F29E2D.2040808@gmail.com> junchi.tang at gmail.com wrote: > Hi, > I am new to python and are tryint to write a simple program delete log > files that are older than 30 days. > > So I used os.path.getmtime(filepath) and compare it with a date but it > does not compile. > > threshold_time = datetime.date.today() - datetime.timedelta(days=30) > mod_time = os.path.getmtime(file_path) > > if( mod_time < threshold_time): > #delete file > > However the interpreter complains at the if line, say "can't comapre > datetime.date to int > > How can I covert one of them to make it work? > > Thank you! > > You are looking for datetime.datetime.fromtimestamp(mod_time) From steven.bethard at gmail.com Thu Sep 27 19:06:25 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Sep 2007 17:06:25 -0600 Subject: getopt with negative numbers? In-Reply-To: References: <1190913250.198794.269530@k79g2000hse.googlegroups.com> Message-ID: <0a6dnQmBPIzuqmHbnZ2dnUVZ_vihnZ2d@comcast.com> Casey wrote: > Is there an easy way to use getopt and still allow negative numbers as > args? [snip] > Alternatively, does optparse handle this? Peter Otten wrote: > optparse can handle options with a negative int value; "--" can be used to > signal that no more options will follow: > >>>> import optparse >>>> parser = optparse.OptionParser() >>>> parser.add_option("-a", type="int") >